3 * A NetworkPackage class. This class implements Deliverable and Receivable
4 * because all network packages should be deliverable to other nodes and
5 * receivable from other nodes. It further provides methods for reading raw
6 * content from template engines and feeding it to the stacker for undeclared
9 * The factory method requires you to provide a compressor class (which must
10 * implement the Compressor interface). If you don't want any compression (not
11 * adviceable due to increased network load), please use the NullCompressor
12 * class and encode it with BASE64 for a more error-free transfer over the
15 * For performance reasons, this class should only be instanciated once and then
16 * used as a "pipe-through" class.
18 * @author Roland Haeder <webmaster@ship-simu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.ship-simu.org
23 * @todo Needs to add functionality for handling the object's type
25 * This program is free software: you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation, either version 3 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, Registerable, Visitable {
40 * Package mask for compressing package data:
41 * 0: Compressor extension
43 * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
47 const PACKAGE_MASK = '%s%s%s%s%s%s%s';
50 * Separator for the above mask
52 const PACKAGE_MASK_SEPARATOR = '^';
55 * Size of an array created by invoking
56 * explode(NetworkPackage::PACKAGE_MASK_SEPARATOR, $content).
58 const PACKAGE_CONTENT_ARRAY_SIZE = 4;
61 * Separator for checksum
63 const PACKAGE_CHECKSUM_SEPARATOR = '_';
66 * Array indexes for above mask, start with zero
68 const INDEX_COMPRESSOR_EXTENSION = 0;
69 const INDEX_PACKAGE_DATA = 1;
71 const INDEX_CHECKSUM = 3;
74 * Array indexes for raw package array
76 const INDEX_PACKAGE_SENDER = 0;
77 const INDEX_PACKAGE_RECIPIENT = 1;
78 const INDEX_PACKAGE_CONTENT = 2;
79 const INDEX_PACKAGE_STATUS = 3;
80 const INDEX_PACKAGE_SIGNATURE = 4;
83 * Size of the decoded data array ('status' is not included)
85 const DECODED_DATA_ARRAY_SIZE = 4;
88 * Named array elements for decoded package content
90 const PACKAGE_CONTENT_EXTENSION = 'compressor';
91 const PACKAGE_CONTENT_MESSAGE = 'message';
92 const PACKAGE_CONTENT_TAGS = 'tags';
93 const PACKAGE_CONTENT_CHECKSUM = 'checksum';
96 * Named array elements for package data
98 const PACKAGE_DATA_SENDER = 'sender';
99 const PACKAGE_DATA_RECIPIENT = 'recipient';
100 const PACKAGE_DATA_CONTENT = 'content';
101 const PACKAGE_DATA_STATUS = 'status';
102 const PACKAGE_DATA_SIGNATURE = 'signature';
107 const PACKAGE_STATUS_NEW = 'new';
108 const PACKAGE_STATUS_FAILED = 'failed';
109 const PACKAGE_STATUS_DECODED = 'decoded';
114 const PACKAGE_TAGS_SEPARATOR = ';';
117 * Raw package data separator
119 const PACKAGE_DATA_SEPARATOR = '#';
122 * Network target (alias): 'upper hubs'
124 const NETWORK_TARGET_UPPER_HUBS = 'upper';
127 * Network target (alias): 'self'
129 const NETWORK_TARGET_SELF = 'self';
132 * TCP package size in bytes
134 const TCP_PACKAGE_SIZE = 512;
136 /**************************************************************************
137 * Stacker for out-going packages *
138 **************************************************************************/
141 * Stacker name for "undeclared" packages
143 const STACKER_NAME_UNDECLARED = 'package_undeclared';
146 * Stacker name for "declared" packages (which are ready to send out)
148 const STACKER_NAME_DECLARED = 'package_declared';
151 * Stacker name for "out-going" packages
153 const STACKER_NAME_OUTGOING = 'package_outgoing';
155 /**************************************************************************
156 * Stacker for incoming packages *
157 **************************************************************************/
160 * Stacker name for "incoming" decoded raw data
162 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
165 * Stacker name for handled decoded raw data
167 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
170 * Stacker name for "chunked" decoded raw data
172 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
175 * Stacker name for new messages
177 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
179 /**************************************************************************
180 * Stacker for other/internal purposes *
181 **************************************************************************/
184 * Stacker name for "back-buffered" packages
186 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
189 * Protected constructor
193 protected function __construct () {
194 // Call parent constructor
195 parent::__construct(__CLASS__);
199 * Creates an instance of this class
201 * @param $compressorInstance A Compressor instance for compressing the content
202 * @return $packageInstance An instance of a Deliverable class
204 public static final function createNetworkPackage (Compressor $compressorInstance) {
206 $packageInstance = new NetworkPackage();
208 // Now set the compressor instance
209 $packageInstance->setCompressorInstance($compressorInstance);
212 * We need to initialize a stack here for our packages even for those
213 * which have no recipient address and stamp... ;-) This stacker will
214 * also be used for incoming raw data to handle it.
216 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
218 // At last, set it in this class
219 $packageInstance->setStackerInstance($stackerInstance);
222 $packageInstance->initStackers();
224 // Get a visitor instance for speeding up things
225 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
227 // Set it in this package
228 $packageInstance->setVisitorInstance($visitorInstance);
230 // Get crypto instance and set it in this package
231 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
232 $packageInstance->setCryptoInstance($cryptoInstance);
234 // Get a singleton package assembler instance from factory and set it here
235 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
236 $packageInstance->setAssemblerInstance($assemblerInstance);
238 // Return the prepared instance
239 return $packageInstance;
243 * Initialize all stackers
245 * @param $forceReInit Whether to force reinitialization of all stacks
248 protected function initStackers ($forceReInit = false) {
252 self::STACKER_NAME_UNDECLARED,
253 self::STACKER_NAME_DECLARED,
254 self::STACKER_NAME_OUTGOING,
255 self::STACKER_NAME_DECODED_INCOMING,
256 self::STACKER_NAME_DECODED_HANDLED,
257 self::STACKER_NAME_DECODED_CHUNKED,
258 self::STACKER_NAME_NEW_MESSAGE,
259 self::STACKER_NAME_BACK_BUFFER
262 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
267 * "Getter" for hash from given content
269 * @param $content Raw package content
270 * @return $hash Hash for given package content
272 private function getHashFromContent ($content) {
274 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
277 // @TODO crc32() is very weak, but it needs to be fast
280 self::PACKAGE_CHECKSUM_SEPARATOR .
281 $this->getSessionId() .
282 self::PACKAGE_CHECKSUM_SEPARATOR .
283 $this->getCompressorInstance()->getCompressorExtension()
291 * Checks whether the checksum (sometimes called "hash") is the same
293 * @param $decodedContent Package raw content
294 * @param $decodedData Whole raw package data array
295 * @return $isChecksumValid Whether the checksum is the same
297 private function isChecksumValid (array $decodedContent, array $decodedData) {
299 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
302 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
305 return $isChecksumValid;
309 * Change the package with given status in given stack
311 * @param $packageData Raw package data in an array
312 * @param $stackerName Name of the stacker
313 * @param $newStatus New status to set
316 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
317 // Skip this for empty stacks
318 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
319 // This avoids an exception after all packages has failed
323 // Pop the entry (it should be it)
324 $nextData = $this->getStackerInstance()->popNamed($stackerName);
326 // Compare both signatures
327 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
329 // Temporary set the new status
330 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
333 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
337 * "Getter" for hash from given content and sender's session id
339 * @param $decodedContent Decoded package content
340 * @param $sessionId Session id of the sender
341 * @return $hash Hash for given package content
343 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
345 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
348 // @TODO crc32() is very weak, but it needs to be fast
350 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
351 self::PACKAGE_CHECKSUM_SEPARATOR .
353 self::PACKAGE_CHECKSUM_SEPARATOR .
354 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
361 ///////////////////////////////////////////////////////////////////////////
362 // Delivering packages / raw data
363 ///////////////////////////////////////////////////////////////////////////
366 * Delivers the given raw package data.
368 * @param $packageData Raw package data in an array
371 private function declareRawPackageData (array $packageData) {
373 * We need to disover every recipient, just in case we have a
374 * multi-recipient entry like 'upper' is. 'all' may be a not so good
375 * target because it causes an overload on the network and may be
376 * abused for attacking the network with large packages.
378 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
380 // Discover all recipients, this may throw an exception
381 $discoveryInstance->discoverRecipients($packageData);
383 // Now get an iterator
384 $iteratorInstance = $discoveryInstance->getIterator();
386 // Rewind back to the beginning
387 $iteratorInstance->rewind();
389 // ... and begin iteration
390 while ($iteratorInstance->valid()) {
392 $currentRecipient = $iteratorInstance->current();
395 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
397 // And enqueue it to the writer class
398 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
401 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
403 // Skip to next entry
404 $iteratorInstance->next();
408 * The recipient list can be cleaned up here because the package which
409 * shall be delivered has already been added for all entries from the
412 $discoveryInstance->clearRecipients();
416 * Delivers raw package data. In short, this will discover the raw socket
417 * resource through a discovery class (which will analyse the receipient of
418 * the package), register the socket with the connection (handler/helper?)
419 * instance and finally push the raw data on our outgoing queue.
421 * @param $packageData Raw package data in an array
424 private function deliverRawPackageData (array $packageData) {
426 * This package may become big, depending on the shared object size or
427 * delivered message size which shouldn't be so long (to save
428 * bandwidth). Because of the nature of the used protocol (TCP) we need
429 * to split it up into smaller pieces to fit it into a TCP frame.
431 * So first we need (again) a discovery class but now a protocol
432 * discovery to choose the right socket resource. The discovery class
433 * should take a look at the raw package data itself and then decide
434 * which (configurable!) protocol should be used for that type of
437 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
439 // Now discover the right protocol
440 $socketResource = $discoveryInstance->discoverSocket($packageData);
443 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
445 // We have to put this socket in our registry, so get an instance
446 $registryInstance = SocketRegistry::createSocketRegistry();
448 // Get the listener from registry
449 $helperInstance = Registry::getRegistry()->getInstance('connection');
452 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
453 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
456 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
458 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
461 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
462 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
463 // Is not connected, then we cannot send
464 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
466 // Shutdown the socket
467 $this->shutdownSocket($socketResource);
471 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
473 // Make sure the connection is up
474 $helperInstance->getStateInstance()->validatePeerStateConnected();
477 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
479 // Enqueue it again on the out-going queue, the connection is up and working at this point
480 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
483 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
487 * Sends waiting packages
489 * @param $packageData Raw package data
492 private function sendOutgoingRawPackageData (array $packageData) {
496 // Get the right connection instance
497 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
499 // Is this connection still alive?
500 if ($helperInstance->isShuttedDown()) {
501 // This connection is shutting down
502 // @TODO We may want to do somthing more here?
506 // Sent out package data
507 $sentBytes = $helperInstance->sendRawPackageData($packageData);
509 // Remember unsent raw bytes in back-buffer, if any
510 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
514 * Generates a signature for given raw package content and sender id
516 * @param $content Raw package data
517 * @param $senderId Sender id to generate a signature for
518 * @return $signature Signature as BASE64-encoded string
520 private function generatePackageSignature ($content, $senderId) {
521 // ash content and sender id together, use md5() as last algo
522 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getNodeId(), false));
524 // Encrypt the content again with the hash as a key
525 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
527 // Encode it with BASE64
528 $signature = base64_encode($encryptedContent);
535 * Checks whether the signature of given package data is 'valid', here that
536 * means it is the same or not.
538 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
539 * @return $isSignatureValid Whether the signature is valid
540 * @todo Unfinished area, signatures are currently NOT fully supported
542 private function isPackageSignatureValid (array $decodedArray) {
543 // Generate the signature of comparing it
544 $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
547 //$isSignatureValid =
548 die(__METHOD__.': signature='.$signature.chr(10).',decodedArray='.print_r($decodedArray,true));
552 * "Enqueues" raw content into this delivery class by reading the raw content
553 * from given helper's template instance and pushing it on the 'undeclared'
556 * @param $helperInstance An instance of a HelpableHub class
559 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance) {
560 // Get the raw content ...
561 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
563 // ... and compress it
564 $content = $this->getCompressorInstance()->compressStream($content);
566 // Add magic in front of it and hash behind it, including BASE64 encoding
567 $content = sprintf(self::PACKAGE_MASK,
568 // 1.) Compressor's extension
569 $this->getCompressorInstance()->getCompressorExtension(),
571 self::PACKAGE_MASK_SEPARATOR,
572 // 2.) Raw package content, encoded with BASE64
573 base64_encode($content),
575 self::PACKAGE_MASK_SEPARATOR,
577 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
579 self::PACKAGE_MASK_SEPARATOR,
581 $this->getHashFromContent($content)
584 // Now prepare the temporary array and push it on the 'undeclared' stack
585 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
586 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
587 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
588 self::PACKAGE_DATA_CONTENT => $content,
589 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
590 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
595 * Checks whether a package has been enqueued for delivery.
597 * @return $isEnqueued Whether a package is enqueued
599 public function isPackageEnqueued () {
600 // Check whether the stacker is not empty
601 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
608 * Checks whether a package has been declared
610 * @return $isDeclared Whether a package is declared
612 public function isPackageDeclared () {
613 // Check whether the stacker is not empty
614 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
621 * Checks whether a package should be sent out
623 * @return $isWaitingDelivery Whether a package is waiting for delivery
625 public function isPackageWaitingForDelivery () {
626 // Check whether the stacker is not empty
627 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
630 return $isWaitingDelivery;
634 * Delivers an enqueued package to the stated destination. If a non-session
635 * id is provided, recipient resolver is being asked (and instanced once).
636 * This allows that a single package is being delivered to multiple targets
637 * without enqueueing it for every target. If no target is provided or it
638 * can't be determined a NoTargetException is being thrown.
641 * @throws NoTargetException If no target can't be determined
643 public function declareEnqueuedPackage () {
644 // Make sure this method isn't working if there is no package enqueued
645 if (!$this->isPackageEnqueued()) {
646 // This is not fatal but should be avoided
647 // @TODO Add some logging here
652 * Now there are for sure packages to deliver, so start with the first
655 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
657 // Declare the raw package data for delivery
658 $this->declareRawPackageData($packageData);
660 // And remove it finally
661 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
665 * Delivers the next declared package. Only one package per time will be sent
666 * because this may take time and slows down the whole delivery
671 public function deliverDeclaredPackage () {
672 // Sanity check if we have packages declared
673 if (!$this->isPackageDeclared()) {
674 // This is not fatal but should be avoided
675 $this->debugOutput('PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
680 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
683 // And try to send it
684 $this->deliverRawPackageData($packageData);
686 // And remove it finally
687 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
688 } catch (InvalidStateException $e) {
689 // The state is not excepected (shall be 'connected')
690 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
692 // Mark the package with status failed
693 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
698 * Sends waiting packages out for delivery
702 public function sendWaitingPackage () {
703 // Send any waiting bytes in the back-buffer before sending a new package
704 $this->sendBackBufferBytes();
706 // Sanity check if we have packages waiting for delivery
707 if (!$this->isPackageWaitingForDelivery()) {
708 // This is not fatal but should be avoided
709 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
714 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
717 // Now try to send it
718 $this->sendOutgoingRawPackageData($packageData);
720 // And remove it finally
721 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
722 } catch (InvalidSocketException $e) {
723 // Output exception message
724 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
726 // Mark package as failed
727 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
731 ///////////////////////////////////////////////////////////////////////////
732 // Receiving packages / raw data
733 ///////////////////////////////////////////////////////////////////////////
736 * Checks whether decoded raw data is pending
738 * @return $isPending Whether decoded raw data is pending
740 private function isDecodedDataPending () {
741 // Just return whether the stack is not empty
742 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
749 * Checks whether new raw package data has arrived at a socket
751 * @param $poolInstance An instance of a PoolableListener class
752 * @return $hasArrived Whether new raw package data has arrived for processing
754 public function isNewRawDataPending (PoolableListener $poolInstance) {
755 // Visit the pool. This monitors the pool for incoming raw data.
756 $poolInstance->accept($this->getVisitorInstance());
758 // Check for new data arrival
759 $hasArrived = $this->isDecodedDataPending();
766 * Handles the incoming decoded raw data. This method does not "convert" the
767 * decoded data back into a package array, it just "handles" it and pushs it
772 public function handleIncomingDecodedData () {
774 * This method should only be called if decoded raw data is pending,
777 if (!$this->isDecodedDataPending()) {
778 // This is not fatal but should be avoided
779 // @TODO Add some logging here
783 // Very noisy debug message:
784 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
786 // "Pop" the next entry (the same array again) from the stack
787 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
789 // Make sure both array elements are there
791 (is_array($decodedData)) &&
792 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
793 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
797 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
798 * only want to handle unhandled packages here.
800 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
801 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
803 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
804 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
805 // It is there and should be removed
806 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
809 // This package is "handled" and can be pushed on the next stack
810 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
814 * Adds raw decoded data from the given handler instance to this receiver
816 * @param $handlerInstance An instance of a Networkable class
819 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
821 * Get the decoded data from the handler, this is an array with
822 * 'decoded_data' and 'error_code' as elements.
824 $decodedData = $handlerInstance->getNextDecodedData();
826 // Very noisy debug message:
827 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
829 // And push it on our stack
830 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
834 * Checks whether incoming decoded data is handled.
836 * @return $isHandled Whether incoming decoded data is handled
838 public function isIncomingDecodedDataHandled () {
839 // Determine if the stack is not empty
840 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
847 * Checks whether the assembler has pending data left
849 * @return $isHandled Whether the assembler has pending data left
851 public function ifAssemblerHasPendingDataLeft () {
852 // Determine if the stack is not empty
853 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
860 * Handles the attached assemler's pending data queue to be finally
861 * assembled to the raw package data back.
865 public function handleAssemblerPendingData () {
867 $this->getAssemblerInstance()->handlePendingData();
871 * Assembles incoming decoded data so it will become an abstract network
872 * package again. The assembler does later do it's job by an other task,
873 * not this one to keep best speed possible.
877 public function assembleDecodedDataToPackage () {
878 // Make sure the raw decoded package data is handled
879 assert($this->isIncomingDecodedDataHandled());
881 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
882 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
884 // Start assembling the raw package data array by chunking it
885 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
887 // Remove the package from 'handled_decoded' stack ...
888 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
890 // ... and push it on the 'chunked' stacker
891 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
895 * Accepts the visitor to process the visit "request"
897 * @param $visitorInstance An instance of a Visitor class
900 public function accept (Visitor $visitorInstance) {
902 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
905 $visitorInstance->visitNetworkPackage($this);
908 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
916 public function clearAllStacker () {
917 // Call the init method to force re-initialization
918 $this->initStackers(true);
921 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
925 * Removes the first failed outoging package from the stack to continue
926 * with next one (it will never work until the issue is fixed by you).
929 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
930 * @todo This may be enchanced for outgoing packages?
932 public function removeFirstFailedPackage () {
933 // Get the package again
934 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
936 // Is the package status 'failed'?
937 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
939 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
943 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
947 * "Decode" the package content into the same array when it was sent.
949 * @param $rawPackageContent The raw package content to be "decoded"
950 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
952 public function decodeRawContent ($rawPackageContent) {
953 // Use the separator '#' to "decode" it
954 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
956 // Assert on count (should be always 3)
957 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
959 // Generate the signature of comparing it
961 * @todo Unsupported feature of "signed" messages commented out
962 if (!$this->isPackageSignatureValid($decodedArray)) {
963 // Is not valid, so throw an exception here
964 die('INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
969 * Create 'decodedData' array with all assoziative array elements,
972 $decodedData = array(
973 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
974 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
975 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
976 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED
984 * Handles decoded data for this node by "decoding" the 'content' part of
985 * it. Again this method uses explode() for the "decoding" process.
987 * @param $decodedData An array with decoded raw package data
989 * @throws InvalidDataChecksumException If the checksum doesn't match
991 public function handleDecodedData (array $decodedData) {
993 * "Decode" the package's content by a simple explode() call, for
994 * details of the array elements, see comments for constant
997 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
999 // Assert on array count for a very basic validation
1000 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1002 // Convert the indexed array into an associative array
1003 $decodedContent = array(
1004 // Compressor's extension used to compress the data
1005 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1006 // Package data (aka "message") in BASE64-decoded form
1007 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1008 // Tags as an indexed array for "tagging" the message
1009 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1010 // Checksum of the _decoded_ data
1011 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM]
1014 // Is the checksum valid?
1015 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1016 // Is not the same, so throw an exception here
1017 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1021 * It is the same, then decompress it, the original message is than
1024 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1026 // And push it on the next stack
1027 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1031 * Checks whether a new message has arrived
1033 * @return $hasArrived Whether a new message has arrived for processing
1035 public function isNewMessageArrived () {
1036 // Determine if the stack is not empty
1037 $hasArrived = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1044 * Handles newly arrived messages
1048 public function handleNewlyArrivedMessage () {
1049 // Get it from the stacker, it is the full array with the decoded message
1050 $decodedContent = $this->getStackerInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1052 die('decodedContent='.print_r($decodedContent,true));