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_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';
112 * Constants for message data array
114 const MESSAGE_ARRAY_DATA = 'message_data';
115 const MESSAGE_ARRAY_TYPE = 'message_type';
120 const PACKAGE_TAGS_SEPARATOR = ';';
123 * Raw package data separator
125 const PACKAGE_DATA_SEPARATOR = '#';
128 * Network target (alias): 'upper hubs'
130 const NETWORK_TARGET_UPPER_HUBS = 'upper';
133 * Network target (alias): 'self'
135 const NETWORK_TARGET_SELF = 'self';
138 * TCP package size in bytes
140 const TCP_PACKAGE_SIZE = 512;
142 /**************************************************************************
143 * Stacker for out-going packages *
144 **************************************************************************/
147 * Stacker name for "undeclared" packages
149 const STACKER_NAME_UNDECLARED = 'package_undeclared';
152 * Stacker name for "declared" packages (which are ready to send out)
154 const STACKER_NAME_DECLARED = 'package_declared';
157 * Stacker name for "out-going" packages
159 const STACKER_NAME_OUTGOING = 'package_outgoing';
161 /**************************************************************************
162 * Stacker for incoming packages *
163 **************************************************************************/
166 * Stacker name for "incoming" decoded raw data
168 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
171 * Stacker name for handled decoded raw data
173 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
176 * Stacker name for "chunked" decoded raw data
178 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
180 /**************************************************************************
181 * Stacker for incoming messages *
182 **************************************************************************/
185 * Stacker name for new messages
187 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
190 * Stacker name for processed messages
192 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
194 /**************************************************************************
195 * Stacker for other/internal purposes *
196 **************************************************************************/
199 * Stacker name for "back-buffered" packages
201 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
204 * Protected constructor
208 protected function __construct () {
209 // Call parent constructor
210 parent::__construct(__CLASS__);
214 * Creates an instance of this class
216 * @param $compressorInstance A Compressor instance for compressing the content
217 * @return $packageInstance An instance of a Deliverable class
219 public static final function createNetworkPackage (Compressor $compressorInstance) {
221 $packageInstance = new NetworkPackage();
223 // Now set the compressor instance
224 $packageInstance->setCompressorInstance($compressorInstance);
227 * We need to initialize a stack here for our packages even for those
228 * which have no recipient address and stamp... ;-) This stacker will
229 * also be used for incoming raw data to handle it.
231 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
233 // At last, set it in this class
234 $packageInstance->setStackerInstance($stackerInstance);
237 $packageInstance->initStackers();
239 // Get a visitor instance for speeding up things
240 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
242 // Set it in this package
243 $packageInstance->setVisitorInstance($visitorInstance);
245 // Get crypto instance and set it in this package
246 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
247 $packageInstance->setCryptoInstance($cryptoInstance);
249 // Get a singleton package assembler instance from factory and set it here
250 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
251 $packageInstance->setAssemblerInstance($assemblerInstance);
253 // Return the prepared instance
254 return $packageInstance;
258 * Initialize all stackers
260 * @param $forceReInit Whether to force reinitialization of all stacks
263 protected function initStackers ($forceReInit = false) {
267 self::STACKER_NAME_UNDECLARED,
268 self::STACKER_NAME_DECLARED,
269 self::STACKER_NAME_OUTGOING,
270 self::STACKER_NAME_DECODED_INCOMING,
271 self::STACKER_NAME_DECODED_HANDLED,
272 self::STACKER_NAME_DECODED_CHUNKED,
273 self::STACKER_NAME_NEW_MESSAGE,
274 self::STACKER_NAME_PROCESSED_MESSAGE,
275 self::STACKER_NAME_BACK_BUFFER
278 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
283 * "Getter" for hash from given content
285 * @param $content Raw package content
286 * @return $hash Hash for given package content
288 private function getHashFromContent ($content) {
290 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
293 // @TODO crc32() is very weak, but it needs to be fast
296 self::PACKAGE_CHECKSUM_SEPARATOR .
297 $this->getSessionId() .
298 self::PACKAGE_CHECKSUM_SEPARATOR .
299 $this->getCompressorInstance()->getCompressorExtension()
307 * Checks whether the checksum (sometimes called "hash") is the same
309 * @param $decodedContent Package raw content
310 * @param $decodedData Whole raw package data array
311 * @return $isChecksumValid Whether the checksum is the same
313 private function isChecksumValid (array $decodedContent, array $decodedData) {
315 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
318 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
321 return $isChecksumValid;
325 * Change the package with given status in given stack
327 * @param $packageData Raw package data in an array
328 * @param $stackerName Name of the stacker
329 * @param $newStatus New status to set
332 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
333 // Skip this for empty stacks
334 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
335 // This avoids an exception after all packages has failed
339 // Pop the entry (it should be it)
340 $nextData = $this->getStackerInstance()->popNamed($stackerName);
342 // Compare both signatures
343 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
345 // Temporary set the new status
346 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
349 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
353 * "Getter" for hash from given content and sender's session id
355 * @param $decodedContent Decoded package content
356 * @param $sessionId Session id of the sender
357 * @return $hash Hash for given package content
359 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
361 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
364 // @TODO crc32() is very weak, but it needs to be fast
366 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
367 self::PACKAGE_CHECKSUM_SEPARATOR .
369 self::PACKAGE_CHECKSUM_SEPARATOR .
370 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
377 ///////////////////////////////////////////////////////////////////////////
378 // Delivering packages / raw data
379 ///////////////////////////////////////////////////////////////////////////
382 * Delivers the given raw package data.
384 * @param $packageData Raw package data in an array
387 private function declareRawPackageData (array $packageData) {
389 * We need to disover every recipient, just in case we have a
390 * multi-recipient entry like 'upper' is. 'all' may be a not so good
391 * target because it causes an overload on the network and may be
392 * abused for attacking the network with large packages.
394 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
396 // Discover all recipients, this may throw an exception
397 $discoveryInstance->discoverRecipients($packageData);
399 // Now get an iterator
400 $iteratorInstance = $discoveryInstance->getIterator();
402 // Rewind back to the beginning
403 $iteratorInstance->rewind();
405 // ... and begin iteration
406 while ($iteratorInstance->valid()) {
408 $currentRecipient = $iteratorInstance->current();
411 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
413 // And enqueue it to the writer class
414 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
417 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
419 // Skip to next entry
420 $iteratorInstance->next();
424 * The recipient list can be cleaned up here because the package which
425 * shall be delivered has already been added for all entries from the
428 $discoveryInstance->clearRecipients();
432 * Delivers raw package data. In short, this will discover the raw socket
433 * resource through a discovery class (which will analyse the receipient of
434 * the package), register the socket with the connection (handler/helper?)
435 * instance and finally push the raw data on our outgoing queue.
437 * @param $packageData Raw package data in an array
440 private function deliverRawPackageData (array $packageData) {
442 * This package may become big, depending on the shared object size or
443 * delivered message size which shouldn't be so long (to save
444 * bandwidth). Because of the nature of the used protocol (TCP) we need
445 * to split it up into smaller pieces to fit it into a TCP frame.
447 * So first we need (again) a discovery class but now a protocol
448 * discovery to choose the right socket resource. The discovery class
449 * should take a look at the raw package data itself and then decide
450 * which (configurable!) protocol should be used for that type of
453 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
455 // Now discover the right protocol
456 $socketResource = $discoveryInstance->discoverSocket($packageData);
459 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
461 // We have to put this socket in our registry, so get an instance
462 $registryInstance = SocketRegistry::createSocketRegistry();
464 // Get the listener from registry
465 $helperInstance = Registry::getRegistry()->getInstance('connection');
468 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
469 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
472 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
474 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
477 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
478 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
479 // Is not connected, then we cannot send
480 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
482 // Shutdown the socket
483 $this->shutdownSocket($socketResource);
487 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
489 // Make sure the connection is up
490 $helperInstance->getStateInstance()->validatePeerStateConnected();
493 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
495 // Enqueue it again on the out-going queue, the connection is up and working at this point
496 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
499 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
503 * Sends waiting packages
505 * @param $packageData Raw package data
508 private function sendOutgoingRawPackageData (array $packageData) {
512 // Get the right connection instance
513 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
515 // Is this connection still alive?
516 if ($helperInstance->isShuttedDown()) {
517 // This connection is shutting down
518 // @TODO We may want to do somthing more here?
522 // Sent out package data
523 $sentBytes = $helperInstance->sendRawPackageData($packageData);
525 // Remember unsent raw bytes in back-buffer, if any
526 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
530 * Generates a signature for given raw package content and sender id
532 * @param $content Raw package data
533 * @param $senderId Sender id to generate a signature for
534 * @return $signature Signature as BASE64-encoded string
536 private function generatePackageSignature ($content, $senderId) {
537 // ash content and sender id together, use md5() as last algo
538 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getNodeId(), false));
540 // Encrypt the content again with the hash as a key
541 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
543 // Encode it with BASE64
544 $signature = base64_encode($encryptedContent);
551 * Checks whether the signature of given package data is 'valid', here that
552 * means it is the same or not.
554 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
555 * @return $isSignatureValid Whether the signature is valid
556 * @todo Unfinished area, signatures are currently NOT fully supported
558 private function isPackageSignatureValid (array $decodedArray) {
559 // Generate the signature of comparing it
560 $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
563 //$isSignatureValid =
564 die(__METHOD__.': signature='.$signature.chr(10).',decodedArray='.print_r($decodedArray,true));
568 * "Enqueues" raw content into this delivery class by reading the raw content
569 * from given helper's template instance and pushing it on the 'undeclared'
572 * @param $helperInstance An instance of a HelpableHub class
575 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance) {
576 // Get the raw content ...
577 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
579 // ... and compress it
580 $content = $this->getCompressorInstance()->compressStream($content);
582 // Add magic in front of it and hash behind it, including BASE64 encoding
583 $content = sprintf(self::PACKAGE_MASK,
584 // 1.) Compressor's extension
585 $this->getCompressorInstance()->getCompressorExtension(),
587 self::PACKAGE_MASK_SEPARATOR,
588 // 2.) Raw package content, encoded with BASE64
589 base64_encode($content),
591 self::PACKAGE_MASK_SEPARATOR,
593 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
595 self::PACKAGE_MASK_SEPARATOR,
597 $this->getHashFromContent($content)
600 // Now prepare the temporary array and push it on the 'undeclared' stack
601 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
602 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
603 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
604 self::PACKAGE_DATA_CONTENT => $content,
605 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
606 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
611 * Checks whether a package has been enqueued for delivery.
613 * @return $isEnqueued Whether a package is enqueued
615 public function isPackageEnqueued () {
616 // Check whether the stacker is not empty
617 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
624 * Checks whether a package has been declared
626 * @return $isDeclared Whether a package is declared
628 public function isPackageDeclared () {
629 // Check whether the stacker is not empty
630 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
637 * Checks whether a package should be sent out
639 * @return $isWaitingDelivery Whether a package is waiting for delivery
641 public function isPackageWaitingForDelivery () {
642 // Check whether the stacker is not empty
643 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
646 return $isWaitingDelivery;
650 * Delivers an enqueued package to the stated destination. If a non-session
651 * id is provided, recipient resolver is being asked (and instanced once).
652 * This allows that a single package is being delivered to multiple targets
653 * without enqueueing it for every target. If no target is provided or it
654 * can't be determined a NoTargetException is being thrown.
657 * @throws NoTargetException If no target can't be determined
659 public function declareEnqueuedPackage () {
660 // Make sure this method isn't working if there is no package enqueued
661 if (!$this->isPackageEnqueued()) {
662 // This is not fatal but should be avoided
663 // @TODO Add some logging here
668 * Now there are for sure packages to deliver, so start with the first
671 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
673 // Declare the raw package data for delivery
674 $this->declareRawPackageData($packageData);
676 // And remove it finally
677 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
681 * Delivers the next declared package. Only one package per time will be sent
682 * because this may take time and slows down the whole delivery
687 public function deliverDeclaredPackage () {
688 // Sanity check if we have packages declared
689 if (!$this->isPackageDeclared()) {
690 // This is not fatal but should be avoided
691 $this->debugOutput('PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
696 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
699 // And try to send it
700 $this->deliverRawPackageData($packageData);
702 // And remove it finally
703 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
704 } catch (InvalidStateException $e) {
705 // The state is not excepected (shall be 'connected')
706 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
708 // Mark the package with status failed
709 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
714 * Sends waiting packages out for delivery
718 public function sendWaitingPackage () {
719 // Send any waiting bytes in the back-buffer before sending a new package
720 $this->sendBackBufferBytes();
722 // Sanity check if we have packages waiting for delivery
723 if (!$this->isPackageWaitingForDelivery()) {
724 // This is not fatal but should be avoided
725 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
730 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
733 // Now try to send it
734 $this->sendOutgoingRawPackageData($packageData);
736 // And remove it finally
737 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
738 } catch (InvalidSocketException $e) {
739 // Output exception message
740 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
742 // Mark package as failed
743 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
747 ///////////////////////////////////////////////////////////////////////////
748 // Receiving packages / raw data
749 ///////////////////////////////////////////////////////////////////////////
752 * Checks whether decoded raw data is pending
754 * @return $isPending Whether decoded raw data is pending
756 private function isDecodedDataPending () {
757 // Just return whether the stack is not empty
758 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
765 * Checks whether new raw package data has arrived at a socket
767 * @param $poolInstance An instance of a PoolableListener class
768 * @return $hasArrived Whether new raw package data has arrived for processing
770 public function isNewRawDataPending (PoolableListener $poolInstance) {
771 // Visit the pool. This monitors the pool for incoming raw data.
772 $poolInstance->accept($this->getVisitorInstance());
774 // Check for new data arrival
775 $hasArrived = $this->isDecodedDataPending();
782 * Handles the incoming decoded raw data. This method does not "convert" the
783 * decoded data back into a package array, it just "handles" it and pushs it
788 public function handleIncomingDecodedData () {
790 * This method should only be called if decoded raw data is pending,
793 if (!$this->isDecodedDataPending()) {
794 // This is not fatal but should be avoided
795 // @TODO Add some logging here
799 // Very noisy debug message:
800 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
802 // "Pop" the next entry (the same array again) from the stack
803 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
805 // Make sure both array elements are there
807 (is_array($decodedData)) &&
808 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
809 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
813 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
814 * only want to handle unhandled packages here.
816 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
817 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
819 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
820 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
821 // It is there and should be removed
822 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
825 // This package is "handled" and can be pushed on the next stack
826 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
830 * Adds raw decoded data from the given handler instance to this receiver
832 * @param $handlerInstance An instance of a Networkable class
835 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
837 * Get the decoded data from the handler, this is an array with
838 * 'decoded_data' and 'error_code' as elements.
840 $decodedData = $handlerInstance->getNextDecodedData();
842 // Very noisy debug message:
843 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
845 // And push it on our stack
846 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
850 * Checks whether incoming decoded data is handled.
852 * @return $isHandled Whether incoming decoded data is handled
854 public function isIncomingDecodedDataHandled () {
855 // Determine if the stack is not empty
856 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
863 * Checks whether the assembler has pending data left
865 * @return $isHandled Whether the assembler has pending data left
867 public function ifAssemblerHasPendingDataLeft () {
868 // Determine if the stack is not empty
869 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
876 * Handles the attached assemler's pending data queue to be finally
877 * assembled to the raw package data back.
881 public function handleAssemblerPendingData () {
883 $this->getAssemblerInstance()->handlePendingData();
887 * Assembles incoming decoded data so it will become an abstract network
888 * package again. The assembler does later do it's job by an other task,
889 * not this one to keep best speed possible.
893 public function assembleDecodedDataToPackage () {
894 // Make sure the raw decoded package data is handled
895 assert($this->isIncomingDecodedDataHandled());
897 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
898 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
900 // Start assembling the raw package data array by chunking it
901 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
903 // Remove the package from 'handled_decoded' stack ...
904 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
906 // ... and push it on the 'chunked' stacker
907 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
911 * Accepts the visitor to process the visit "request"
913 * @param $visitorInstance An instance of a Visitor class
916 public function accept (Visitor $visitorInstance) {
918 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
921 $visitorInstance->visitNetworkPackage($this);
924 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
932 public function clearAllStacker () {
933 // Call the init method to force re-initialization
934 $this->initStackers(true);
937 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
941 * Removes the first failed outoging package from the stack to continue
942 * with next one (it will never work until the issue is fixed by you).
945 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
946 * @todo This may be enchanced for outgoing packages?
948 public function removeFirstFailedPackage () {
949 // Get the package again
950 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
952 // Is the package status 'failed'?
953 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
955 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
959 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
963 * "Decode" the package content into the same array when it was sent.
965 * @param $rawPackageContent The raw package content to be "decoded"
966 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
968 public function decodeRawContent ($rawPackageContent) {
969 // Use the separator '#' to "decode" it
970 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
972 // Assert on count (should be always 3)
973 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
975 // Generate the signature of comparing it
977 * @todo Unsupported feature of "signed" messages commented out
978 if (!$this->isPackageSignatureValid($decodedArray)) {
979 // Is not valid, so throw an exception here
980 die('INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
985 * Create 'decodedData' array with all assoziative array elements,
988 $decodedData = array(
989 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
990 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
991 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
992 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED
1000 * Handles decoded data for this node by "decoding" the 'content' part of
1001 * it. Again this method uses explode() for the "decoding" process.
1003 * @param $decodedData An array with decoded raw package data
1005 * @throws InvalidDataChecksumException If the checksum doesn't match
1007 public function handleDecodedData (array $decodedData) {
1009 * "Decode" the package's content by a simple explode() call, for
1010 * details of the array elements, see comments for constant
1013 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1015 // Assert on array count for a very basic validation
1016 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1019 * Convert the indexed array into an associative array. This is much
1020 * better to remember than plain numbers, isn't it?
1022 $decodedContent = array(
1023 // Compressor's extension used to compress the data
1024 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1025 // Package data (aka "message") in BASE64-decoded form but still compressed
1026 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1027 // Tags as an indexed array for "tagging" the message
1028 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1029 // Checksum of the _decoded_ data
1030 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM]
1033 // Is the checksum valid?
1034 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1035 // Is not the same, so throw an exception here
1036 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1040 * The checksum is the same, then it can be decompressed safely. The
1041 * original message is at this point fully decoded.
1043 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1045 // And push it on the next stack
1046 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1050 * Checks whether a new message has arrived
1052 * @return $hasArrived Whether a new message has arrived for processing
1054 public function isNewMessageArrived () {
1055 // Determine if the stack is not empty
1056 $hasArrived = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1063 * Handles newly arrived messages
1066 * @todo Implement verification of all sent tags here?
1068 public function handleNewlyArrivedMessage () {
1069 // Get it from the stacker, it is the full array with the decoded message
1070 $decodedContent = $this->getStackerInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1072 // Now get a filter chain back from factory with given tags array
1073 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1076 * Process the message through all filters, note that all other
1077 * elements from $decodedContent are no longer needed.
1079 $chainInstance->processMessage($decodedContent[self::PACKAGE_CONTENT_MESSAGE], $this);
1083 * Checks whether a processed message is pending for "interpretation"
1085 * @return $isPending Whether a processed message is pending
1087 public function isProcessedMessagePending () {
1089 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1096 * Handle processed messages by "interpreting" the 'message_type' element
1100 public function handleProcessedMessage () {
1101 // Get it from the stacker, it is the full array with the processed message
1102 $messageArray = $this->getStackerInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1104 // Create a handler instance from given message type
1105 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1107 // Handle message data
1108 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1110 die('messageArray='.print_r($messageArray,true));