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 - 2012 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_PROTOCOL = 'protocol';
101 const PACKAGE_DATA_CONTENT = 'content';
102 const PACKAGE_DATA_STATUS = 'status';
103 const PACKAGE_DATA_SIGNATURE = 'signature';
108 const PACKAGE_STATUS_NEW = 'new';
109 const PACKAGE_STATUS_FAILED = 'failed';
110 const PACKAGE_STATUS_DECODED = 'decoded';
113 * Constants for message data array
115 const MESSAGE_ARRAY_DATA = 'message_data';
116 const MESSAGE_ARRAY_TYPE = 'message_type';
121 const PACKAGE_TAGS_SEPARATOR = ';';
124 * Raw package data separator
126 const PACKAGE_DATA_SEPARATOR = '#';
129 * Network target (alias): 'upper hubs'
131 const NETWORK_TARGET_UPPER_HUBS = 'upper';
134 * Network target (alias): 'self'
136 const NETWORK_TARGET_SELF = 'self';
139 * TCP package size in bytes
141 const TCP_PACKAGE_SIZE = 512;
143 /**************************************************************************
144 * Stacker for out-going packages *
145 **************************************************************************/
148 * Stacker name for "undeclared" packages
150 const STACKER_NAME_UNDECLARED = 'package_undeclared';
153 * Stacker name for "declared" packages (which are ready to send out)
155 const STACKER_NAME_DECLARED = 'package_declared';
158 * Stacker name for "out-going" packages
160 const STACKER_NAME_OUTGOING = 'package_outgoing';
162 /**************************************************************************
163 * Stacker for incoming packages *
164 **************************************************************************/
167 * Stacker name for "incoming" decoded raw data
169 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
172 * Stacker name for handled decoded raw data
174 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
177 * Stacker name for "chunked" decoded raw data
179 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
181 /**************************************************************************
182 * Stacker for incoming messages *
183 **************************************************************************/
186 * Stacker name for new messages
188 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
191 * Stacker name for processed messages
193 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
195 /**************************************************************************
196 * Stacker for other/internal purposes *
197 **************************************************************************/
200 * Stacker name for "back-buffered" packages
202 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
205 * Protected constructor
209 protected function __construct () {
210 // Call parent constructor
211 parent::__construct(__CLASS__);
215 * Creates an instance of this class
217 * @param $compressorInstance A Compressor instance for compressing the content
218 * @return $packageInstance An instance of a Deliverable class
220 public static final function createNetworkPackage (Compressor $compressorInstance) {
222 $packageInstance = new NetworkPackage();
224 // Now set the compressor instance
225 $packageInstance->setCompressorInstance($compressorInstance);
228 * We need to initialize a stack here for our packages even for those
229 * which have no recipient address and stamp... ;-) This stacker will
230 * also be used for incoming raw data to handle it.
232 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
234 // At last, set it in this class
235 $packageInstance->setStackerInstance($stackerInstance);
238 $packageInstance->initStackers();
240 // Get a visitor instance for speeding up things
241 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
243 // Set it in this package
244 $packageInstance->setVisitorInstance($visitorInstance);
246 // Get crypto instance and set it in this package
247 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
248 $packageInstance->setCryptoInstance($cryptoInstance);
250 // Get a singleton package assembler instance from factory and set it here
251 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
252 $packageInstance->setAssemblerInstance($assemblerInstance);
254 // Return the prepared instance
255 return $packageInstance;
259 * Initialize all stackers
261 * @param $forceReInit Whether to force reinitialization of all stacks
264 protected function initStackers ($forceReInit = false) {
268 self::STACKER_NAME_UNDECLARED,
269 self::STACKER_NAME_DECLARED,
270 self::STACKER_NAME_OUTGOING,
271 self::STACKER_NAME_DECODED_INCOMING,
272 self::STACKER_NAME_DECODED_HANDLED,
273 self::STACKER_NAME_DECODED_CHUNKED,
274 self::STACKER_NAME_NEW_MESSAGE,
275 self::STACKER_NAME_PROCESSED_MESSAGE,
276 self::STACKER_NAME_BACK_BUFFER
279 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
284 * "Getter" for hash from given content
286 * @param $content Raw package content
287 * @return $hash Hash for given package content
289 private function getHashFromContent ($content) {
291 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
294 // @TODO crc32() is very weak, but it needs to be fast
297 self::PACKAGE_CHECKSUM_SEPARATOR .
298 $this->getSessionId() .
299 self::PACKAGE_CHECKSUM_SEPARATOR .
300 $this->getCompressorInstance()->getCompressorExtension()
308 * Checks whether the checksum (sometimes called "hash") is the same
310 * @param $decodedContent Package raw content
311 * @param $decodedData Whole raw package data array
312 * @return $isChecksumValid Whether the checksum is the same
314 private function isChecksumValid (array $decodedContent, array $decodedData) {
316 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
319 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
322 return $isChecksumValid;
326 * Change the package with given status in given stack
328 * @param $packageData Raw package data in an array
329 * @param $stackerName Name of the stacker
330 * @param $newStatus New status to set
333 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
334 // Skip this for empty stacks
335 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
336 // This avoids an exception after all packages has failed
340 // Pop the entry (it should be it)
341 $nextData = $this->getStackerInstance()->popNamed($stackerName);
343 // Compare both signatures
344 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
346 // Temporary set the new status
347 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
350 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
354 * "Getter" for hash from given content and sender's session id
356 * @param $decodedContent Decoded package content
357 * @param $sessionId Session id of the sender
358 * @return $hash Hash for given package content
360 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
362 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
365 // @TODO crc32() is very weak, but it needs to be fast
367 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
368 self::PACKAGE_CHECKSUM_SEPARATOR .
370 self::PACKAGE_CHECKSUM_SEPARATOR .
371 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
378 ///////////////////////////////////////////////////////////////////////////
379 // Delivering packages / raw data
380 ///////////////////////////////////////////////////////////////////////////
383 * Delivers the given raw package data.
385 * @param $packageData Raw package data in an array
388 private function declareRawPackageData (array $packageData) {
390 * We need to disover every recipient, just in case we have a
391 * multi-recipient entry like 'upper' is. 'all' may be a not so good
392 * target because it causes an overload on the network and may be
393 * abused for attacking the network with large packages.
395 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
397 // Discover all recipients, this may throw an exception
398 $discoveryInstance->discoverRecipients($packageData);
400 // Now get an iterator
401 $iteratorInstance = $discoveryInstance->getIterator();
403 // Rewind back to the beginning
404 $iteratorInstance->rewind();
406 // ... and begin iteration
407 while ($iteratorInstance->valid()) {
409 $currentRecipient = $iteratorInstance->current();
412 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
414 // And enqueue it to the writer class
415 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
418 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
420 // Skip to next entry
421 $iteratorInstance->next();
425 * The recipient list can be cleaned up here because the package which
426 * shall be delivered has already been added for all entries from the
429 $discoveryInstance->clearRecipients();
433 * Delivers raw package data. In short, this will discover the raw socket
434 * resource through a discovery class (which will analyse the receipient of
435 * the package), register the socket with the connection (handler/helper?)
436 * instance and finally push the raw data on our outgoing queue.
438 * @param $packageData Raw package data in an array
441 private function deliverRawPackageData (array $packageData) {
443 * This package may become big, depending on the shared object size or
444 * delivered message size which shouldn't be so long (to save
445 * bandwidth). Because of the nature of the used protocol (TCP) we need
446 * to split it up into smaller pieces to fit it into a TCP frame.
448 * So first we need (again) a discovery class but now a protocol
449 * discovery to choose the right socket resource. The discovery class
450 * should take a look at the raw package data itself and then decide
451 * which (configurable!) protocol should be used for that type of
454 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
456 // Now discover the right protocol
457 $socketResource = $discoveryInstance->discoverSocket($packageData);
460 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
462 // We have to put this socket in our registry, so get an instance
463 $registryInstance = SocketRegistry::createSocketRegistry();
465 // Get the listener from registry
466 $helperInstance = Registry::getRegistry()->getInstance('connection');
469 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
470 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
473 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
475 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
478 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
479 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
480 // Is not connected, then we cannot send
481 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
483 // Shutdown the socket
484 $this->shutdownSocket($socketResource);
488 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
490 // Make sure the connection is up
491 $helperInstance->getStateInstance()->validatePeerStateConnected();
494 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
496 // Enqueue it again on the out-going queue, the connection is up and working at this point
497 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
500 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
504 * Sends waiting packages
506 * @param $packageData Raw package data
509 private function sendOutgoingRawPackageData (array $packageData) {
513 // Get the right connection instance
514 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
516 // Is this connection still alive?
517 if ($helperInstance->isShuttedDown()) {
518 // This connection is shutting down
519 // @TODO We may want to do somthing more here?
523 // Sent out package data
524 $sentBytes = $helperInstance->sendRawPackageData($packageData);
526 // Remember unsent raw bytes in back-buffer, if any
527 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
531 * Generates a signature for given raw package content and sender id
533 * @param $content Raw package data
534 * @param $senderId Sender id to generate a signature for
535 * @return $signature Signature as BASE64-encoded string
537 private function generatePackageSignature ($content, $senderId) {
538 // ash content and sender id together, use md5() as last algo
539 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getNodeId(), false));
541 // Encrypt the content again with the hash as a key
542 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
544 // Encode it with BASE64
545 $signature = base64_encode($encryptedContent);
552 * Checks whether the signature of given package data is 'valid', here that
553 * means it is the same or not.
555 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
556 * @return $isSignatureValid Whether the signature is valid
557 * @todo Unfinished area, signatures are currently NOT fully supported
559 private function isPackageSignatureValid (array $decodedArray) {
560 // Generate the signature of comparing it
561 $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
564 //$isSignatureValid =
565 die(__METHOD__.': signature='.$signature.chr(10).',decodedArray='.print_r($decodedArray,true));
569 * "Enqueues" raw content into this delivery class by reading the raw content
570 * from given helper's template instance and pushing it on the 'undeclared'
573 * @param $helperInstance An instance of a HelpableHub class
574 * @param $protocol Name of used protocol (TCP/UDP)
577 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, $protocolName) {
578 // Get the raw content ...
579 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
581 // ... and compress it
582 $content = $this->getCompressorInstance()->compressStream($content);
584 // Add magic in front of it and hash behind it, including BASE64 encoding
585 $content = sprintf(self::PACKAGE_MASK,
586 // 1.) Compressor's extension
587 $this->getCompressorInstance()->getCompressorExtension(),
589 self::PACKAGE_MASK_SEPARATOR,
590 // 2.) Raw package content, encoded with BASE64
591 base64_encode($content),
593 self::PACKAGE_MASK_SEPARATOR,
595 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
597 self::PACKAGE_MASK_SEPARATOR,
599 $this->getHashFromContent($content)
602 // Now prepare the temporary array and push it on the 'undeclared' stack
603 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
604 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
605 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
606 self::PACKAGE_DATA_PROTOCOL => $protocolName,
607 self::PACKAGE_DATA_CONTENT => $content,
608 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
609 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
614 * Checks whether a package has been enqueued for delivery.
616 * @return $isEnqueued Whether a package is enqueued
618 public function isPackageEnqueued () {
619 // Check whether the stacker is not empty
620 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
627 * Checks whether a package has been declared
629 * @return $isDeclared Whether a package is declared
631 public function isPackageDeclared () {
632 // Check whether the stacker is not empty
633 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
640 * Checks whether a package should be sent out
642 * @return $isWaitingDelivery Whether a package is waiting for delivery
644 public function isPackageWaitingForDelivery () {
645 // Check whether the stacker is not empty
646 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
649 return $isWaitingDelivery;
653 * Delivers an enqueued package to the stated destination. If a non-session
654 * id is provided, recipient resolver is being asked (and instanced once).
655 * This allows that a single package is being delivered to multiple targets
656 * without enqueueing it for every target. If no target is provided or it
657 * can't be determined a NoTargetException is being thrown.
660 * @throws NoTargetException If no target can't be determined
662 public function declareEnqueuedPackage () {
663 // Make sure this method isn't working if there is no package enqueued
664 if (!$this->isPackageEnqueued()) {
665 // This is not fatal but should be avoided
666 // @TODO Add some logging here
671 * Now there are for sure packages to deliver, so start with the first
674 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
676 // Declare the raw package data for delivery
677 $this->declareRawPackageData($packageData);
679 // And remove it finally
680 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
684 * Delivers the next declared package. Only one package per time will be sent
685 * because this may take time and slows down the whole delivery
690 public function deliverDeclaredPackage () {
691 // Sanity check if we have packages declared
692 if (!$this->isPackageDeclared()) {
693 // This is not fatal but should be avoided
694 $this->debugOutput('PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
699 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
702 // And try to send it
703 $this->deliverRawPackageData($packageData);
705 // And remove it finally
706 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
707 } catch (InvalidStateException $e) {
708 // The state is not excepected (shall be 'connected')
709 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
711 // Mark the package with status failed
712 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
717 * Sends waiting packages out for delivery
721 public function sendWaitingPackage () {
722 // Send any waiting bytes in the back-buffer before sending a new package
723 $this->sendBackBufferBytes();
725 // Sanity check if we have packages waiting for delivery
726 if (!$this->isPackageWaitingForDelivery()) {
727 // This is not fatal but should be avoided
728 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
733 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
736 // Now try to send it
737 $this->sendOutgoingRawPackageData($packageData);
739 // And remove it finally
740 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
741 } catch (InvalidSocketException $e) {
742 // Output exception message
743 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
745 // Mark package as failed
746 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
750 ///////////////////////////////////////////////////////////////////////////
751 // Receiving packages / raw data
752 ///////////////////////////////////////////////////////////////////////////
755 * Checks whether decoded raw data is pending
757 * @return $isPending Whether decoded raw data is pending
759 private function isDecodedDataPending () {
760 // Just return whether the stack is not empty
761 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
768 * Checks whether new raw package data has arrived at a socket
770 * @param $poolInstance An instance of a PoolableListener class
771 * @return $hasArrived Whether new raw package data has arrived for processing
773 public function isNewRawDataPending (PoolableListener $poolInstance) {
774 // Visit the pool. This monitors the pool for incoming raw data.
775 $poolInstance->accept($this->getVisitorInstance());
777 // Check for new data arrival
778 $hasArrived = $this->isDecodedDataPending();
785 * Handles the incoming decoded raw data. This method does not "convert" the
786 * decoded data back into a package array, it just "handles" it and pushs it
791 public function handleIncomingDecodedData () {
793 * This method should only be called if decoded raw data is pending,
796 if (!$this->isDecodedDataPending()) {
797 // This is not fatal but should be avoided
798 // @TODO Add some logging here
802 // Very noisy debug message:
803 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
805 // "Pop" the next entry (the same array again) from the stack
806 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
808 // Make sure both array elements are there
810 (is_array($decodedData)) &&
811 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
812 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
816 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
817 * only want to handle unhandled packages here.
819 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
820 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
822 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
823 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
824 // It is there and should be removed
825 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
828 // This package is "handled" and can be pushed on the next stack
829 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
833 * Adds raw decoded data from the given handler instance to this receiver
835 * @param $handlerInstance An instance of a Networkable class
838 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
840 * Get the decoded data from the handler, this is an array with
841 * 'decoded_data' and 'error_code' as elements.
843 $decodedData = $handlerInstance->getNextDecodedData();
845 // Very noisy debug message:
846 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
848 // And push it on our stack
849 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
853 * Checks whether incoming decoded data is handled.
855 * @return $isHandled Whether incoming decoded data is handled
857 public function isIncomingDecodedDataHandled () {
858 // Determine if the stack is not empty
859 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
866 * Checks whether the assembler has pending data left
868 * @return $isHandled Whether the assembler has pending data left
870 public function ifAssemblerHasPendingDataLeft () {
871 // Determine if the stack is not empty
872 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
879 * Handles the attached assemler's pending data queue to be finally
880 * assembled to the raw package data back.
884 public function handleAssemblerPendingData () {
886 $this->getAssemblerInstance()->handlePendingData();
890 * Assembles incoming decoded data so it will become an abstract network
891 * package again. The assembler does later do it's job by an other task,
892 * not this one to keep best speed possible.
896 public function assembleDecodedDataToPackage () {
897 // Make sure the raw decoded package data is handled
898 assert($this->isIncomingDecodedDataHandled());
900 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
901 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
903 // Start assembling the raw package data array by chunking it
904 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
906 // Remove the package from 'handled_decoded' stack ...
907 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
909 // ... and push it on the 'chunked' stacker
910 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
914 * Accepts the visitor to process the visit "request"
916 * @param $visitorInstance An instance of a Visitor class
919 public function accept (Visitor $visitorInstance) {
921 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
924 $visitorInstance->visitNetworkPackage($this);
927 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
935 public function clearAllStacker () {
936 // Call the init method to force re-initialization
937 $this->initStackers(true);
940 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
944 * Removes the first failed outoging package from the stack to continue
945 * with next one (it will never work until the issue is fixed by you).
948 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
949 * @todo This may be enchanced for outgoing packages?
951 public function removeFirstFailedPackage () {
952 // Get the package again
953 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
955 // Is the package status 'failed'?
956 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
958 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
962 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
966 * "Decode" the package content into the same array when it was sent.
968 * @param $rawPackageContent The raw package content to be "decoded"
969 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
971 public function decodeRawContent ($rawPackageContent) {
972 // Use the separator '#' to "decode" it
973 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
975 // Assert on count (should be always 3)
976 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
978 // Generate the signature of comparing it
980 * @todo Unsupported feature of "signed" messages commented out
981 if (!$this->isPackageSignatureValid($decodedArray)) {
982 // Is not valid, so throw an exception here
983 die('INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
988 * Create 'decodedData' array with all assoziative array elements,
991 $decodedData = array(
992 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
993 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
994 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
995 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED
1003 * Handles decoded data for this node by "decoding" the 'content' part of
1004 * it. Again this method uses explode() for the "decoding" process.
1006 * @param $decodedData An array with decoded raw package data
1008 * @throws InvalidDataChecksumException If the checksum doesn't match
1010 public function handleDecodedData (array $decodedData) {
1012 * "Decode" the package's content by a simple explode() call, for
1013 * details of the array elements, see comments for constant
1016 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1018 // Assert on array count for a very basic validation
1019 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1022 * Convert the indexed array into an associative array. This is much
1023 * better to remember than plain numbers, isn't it?
1025 $decodedContent = array(
1026 // Compressor's extension used to compress the data
1027 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1028 // Package data (aka "message") in BASE64-decoded form but still compressed
1029 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1030 // Tags as an indexed array for "tagging" the message
1031 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1032 // Checksum of the _decoded_ data
1033 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM]
1036 // Is the checksum valid?
1037 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1038 // Is not the same, so throw an exception here
1039 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1043 * The checksum is the same, then it can be decompressed safely. The
1044 * original message is at this point fully decoded.
1046 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1048 // And push it on the next stack
1049 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1053 * Checks whether a new message has arrived
1055 * @return $hasArrived Whether a new message has arrived for processing
1057 public function isNewMessageArrived () {
1058 // Determine if the stack is not empty
1059 $hasArrived = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1066 * Handles newly arrived messages
1069 * @todo Implement verification of all sent tags here?
1071 public function handleNewlyArrivedMessage () {
1072 // Get it from the stacker, it is the full array with the decoded message
1073 $decodedContent = $this->getStackerInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1075 // Now get a filter chain back from factory with given tags array
1076 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1079 * Process the message through all filters, note that all other
1080 * elements from $decodedContent are no longer needed.
1082 $chainInstance->processMessage($decodedContent[self::PACKAGE_CONTENT_MESSAGE], $this);
1086 * Checks whether a processed message is pending for "interpretation"
1088 * @return $isPending Whether a processed message is pending
1090 public function isProcessedMessagePending () {
1092 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1099 * Handle processed messages by "interpreting" the 'message_type' element
1103 public function handleProcessedMessage () {
1104 // Get it from the stacker, it is the full array with the processed message
1105 $messageArray = $this->getStackerInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1107 // Create a handler instance from given message type
1108 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1110 // Handle message data
1111 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1113 die('messageArray='.print_r($messageArray,true));