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 * Network target (alias): 'other'
141 const NETWORK_TARGET_OTHER = 'other';
144 * TCP package size in bytes
146 const TCP_PACKAGE_SIZE = 512;
148 /**************************************************************************
149 * Stacker for out-going packages *
150 **************************************************************************/
153 * Stacker name for "undeclared" packages
155 const STACKER_NAME_UNDECLARED = 'package_undeclared';
158 * Stacker name for "declared" packages (which are ready to send out)
160 const STACKER_NAME_DECLARED = 'package_declared';
163 * Stacker name for "out-going" packages
165 const STACKER_NAME_OUTGOING = 'package_outgoing';
167 /**************************************************************************
168 * Stacker for incoming packages *
169 **************************************************************************/
172 * Stacker name for "incoming" decoded raw data
174 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
177 * Stacker name for handled decoded raw data
179 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
182 * Stacker name for "chunked" decoded raw data
184 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
186 /**************************************************************************
187 * Stacker for incoming messages *
188 **************************************************************************/
191 * Stacker name for new messages
193 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
196 * Stacker name for processed messages
198 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
200 /**************************************************************************
201 * Stacker for other/internal purposes *
202 **************************************************************************/
205 * Stacker name for "back-buffered" packages
207 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
210 * Protected constructor
214 protected function __construct () {
215 // Call parent constructor
216 parent::__construct(__CLASS__);
220 * Creates an instance of this class
222 * @param $compressorInstance A Compressor instance for compressing the content
223 * @return $packageInstance An instance of a Deliverable class
225 public static final function createNetworkPackage (Compressor $compressorInstance) {
227 $packageInstance = new NetworkPackage();
229 // Now set the compressor instance
230 $packageInstance->setCompressorInstance($compressorInstance);
233 * We need to initialize a stack here for our packages even for those
234 * which have no recipient address and stamp... ;-) This stacker will
235 * also be used for incoming raw data to handle it.
237 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
239 // At last, set it in this class
240 $packageInstance->setStackerInstance($stackerInstance);
243 $packageInstance->initStackers();
245 // Get a visitor instance for speeding up things
246 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
248 // Set it in this package
249 $packageInstance->setVisitorInstance($visitorInstance);
251 // Get crypto instance and set it in this package
252 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
253 $packageInstance->setCryptoInstance($cryptoInstance);
255 // Get a singleton package assembler instance from factory and set it here
256 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
257 $packageInstance->setAssemblerInstance($assemblerInstance);
259 // Return the prepared instance
260 return $packageInstance;
264 * Initialize all stackers
266 * @param $forceReInit Whether to force reinitialization of all stacks
269 protected function initStackers ($forceReInit = false) {
273 self::STACKER_NAME_UNDECLARED,
274 self::STACKER_NAME_DECLARED,
275 self::STACKER_NAME_OUTGOING,
276 self::STACKER_NAME_DECODED_INCOMING,
277 self::STACKER_NAME_DECODED_HANDLED,
278 self::STACKER_NAME_DECODED_CHUNKED,
279 self::STACKER_NAME_NEW_MESSAGE,
280 self::STACKER_NAME_PROCESSED_MESSAGE,
281 self::STACKER_NAME_BACK_BUFFER
284 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
289 * "Getter" for hash from given content
291 * @param $content Raw package content
292 * @return $hash Hash for given package content
294 private function getHashFromContent ($content) {
296 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
299 // @TODO crc32() is very weak, but it needs to be fast
302 self::PACKAGE_CHECKSUM_SEPARATOR .
303 $this->getSessionId() .
304 self::PACKAGE_CHECKSUM_SEPARATOR .
305 $this->getCompressorInstance()->getCompressorExtension()
313 * Checks whether the checksum (sometimes called "hash") is the same
315 * @param $decodedContent Package raw content
316 * @param $decodedData Whole raw package data array
317 * @return $isChecksumValid Whether the checksum is the same
319 private function isChecksumValid (array $decodedContent, array $decodedData) {
321 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
324 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
327 return $isChecksumValid;
331 * Change the package with given status in given stack
333 * @param $packageData Raw package data in an array
334 * @param $stackerName Name of the stacker
335 * @param $newStatus New status to set
338 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
339 // Skip this for empty stacks
340 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
341 // This avoids an exception after all packages has failed
345 // Pop the entry (it should be it)
346 $nextData = $this->getStackerInstance()->popNamed($stackerName);
348 // Compare both signatures
349 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
351 // Temporary set the new status
352 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
355 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
359 * "Getter" for hash from given content and sender's session id
361 * @param $decodedContent Decoded package content
362 * @param $sessionId Session id of the sender
363 * @return $hash Hash for given package content
365 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
367 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
370 // @TODO crc32() is very weak, but it needs to be fast
372 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
373 self::PACKAGE_CHECKSUM_SEPARATOR .
375 self::PACKAGE_CHECKSUM_SEPARATOR .
376 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
383 ///////////////////////////////////////////////////////////////////////////
384 // Delivering packages / raw data
385 ///////////////////////////////////////////////////////////////////////////
388 * Delivers the given raw package data.
390 * @param $packageData Raw package data in an array
393 private function declareRawPackageData (array $packageData) {
395 * We need to disover every recipient, just in case we have a
396 * multi-recipient entry like 'upper' is. 'all' may be a not so good
397 * target because it causes an overload on the network and may be
398 * abused for attacking the network with large packages.
400 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
402 // Discover all recipients, this may throw an exception
403 $discoveryInstance->discoverRecipients($packageData);
405 // Now get an iterator
406 $iteratorInstance = $discoveryInstance->getIterator();
408 // Rewind back to the beginning
409 $iteratorInstance->rewind();
411 // ... and begin iteration
412 while ($iteratorInstance->valid()) {
414 $currentRecipient = $iteratorInstance->current();
417 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
419 // And enqueue it to the writer class
420 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
423 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
425 // Skip to next entry
426 $iteratorInstance->next();
430 * The recipient list can be cleaned up here because the package which
431 * shall be delivered has already been added for all entries from the
434 $discoveryInstance->clearRecipients();
438 * Delivers raw package data. In short, this will discover the raw socket
439 * resource through a discovery class (which will analyse the receipient of
440 * the package), register the socket with the connection (handler/helper?)
441 * instance and finally push the raw data on our outgoing queue.
443 * @param $packageData Raw package data in an array
446 private function deliverRawPackageData (array $packageData) {
448 * This package may become big, depending on the shared object size or
449 * delivered message size which shouldn't be so long (to save
450 * bandwidth). Because of the nature of the used protocol (TCP) we need
451 * to split it up into smaller pieces to fit it into a TCP frame.
453 * So first we need (again) a discovery class but now a protocol
454 * discovery to choose the right socket resource. The discovery class
455 * should take a look at the raw package data itself and then decide
456 * which (configurable!) protocol should be used for that type of
459 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
461 // Now discover the right protocol
462 $socketResource = $discoveryInstance->discoverSocket($packageData);
465 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
467 // We have to put this socket in our registry, so get an instance
468 $registryInstance = SocketRegistry::createSocketRegistry();
470 // Get the listener from registry
471 $helperInstance = Registry::getRegistry()->getInstance('connection');
474 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
475 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
478 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
480 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
483 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
484 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
485 // Is not connected, then we cannot send
486 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
488 // Shutdown the socket
489 $this->shutdownSocket($socketResource);
493 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
495 // Make sure the connection is up
496 $helperInstance->getStateInstance()->validatePeerStateConnected();
499 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
501 // Enqueue it again on the out-going queue, the connection is up and working at this point
502 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
505 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
509 * Sends waiting packages
511 * @param $packageData Raw package data
514 private function sendOutgoingRawPackageData (array $packageData) {
518 // Get the right connection instance
519 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
521 // Is this connection still alive?
522 if ($helperInstance->isShuttedDown()) {
523 // This connection is shutting down
524 // @TODO We may want to do somthing more here?
528 // Sent out package data
529 $sentBytes = $helperInstance->sendRawPackageData($packageData);
531 // Remember unsent raw bytes in back-buffer, if any
532 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
536 * Generates a signature for given raw package content and sender id
538 * @param $content Raw package data
539 * @param $senderId Sender id to generate a signature for
540 * @return $signature Signature as BASE64-encoded string
542 private function generatePackageSignature ($content, $senderId) {
543 // ash content and sender id together, use md5() as last algo
544 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getNodeId(), false));
546 // Encrypt the content again with the hash as a key
547 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
549 // Encode it with BASE64
550 $signature = base64_encode($encryptedContent);
557 * Checks whether the signature of given package data is 'valid', here that
558 * means it is the same or not.
560 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
561 * @return $isSignatureValid Whether the signature is valid
562 * @todo Unfinished area, signatures are currently NOT fully supported
564 private function isPackageSignatureValid (array $decodedArray) {
565 // Generate the signature of comparing it
566 $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
569 //$isSignatureValid =
570 die(__METHOD__.': signature='.$signature.chr(10).',decodedArray='.print_r($decodedArray,true));
574 * "Enqueues" raw content into this delivery class by reading the raw content
575 * from given helper's template instance and pushing it on the 'undeclared'
578 * @param $helperInstance An instance of a HelpableHub class
579 * @param $protocol Name of used protocol (TCP/UDP)
582 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, $protocolName) {
583 // Get the raw content ...
584 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
586 // ... and compress it
587 $content = $this->getCompressorInstance()->compressStream($content);
589 // Add magic in front of it and hash behind it, including BASE64 encoding
590 $content = sprintf(self::PACKAGE_MASK,
591 // 1.) Compressor's extension
592 $this->getCompressorInstance()->getCompressorExtension(),
594 self::PACKAGE_MASK_SEPARATOR,
595 // 2.) Raw package content, encoded with BASE64
596 base64_encode($content),
598 self::PACKAGE_MASK_SEPARATOR,
600 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
602 self::PACKAGE_MASK_SEPARATOR,
604 $this->getHashFromContent($content)
607 // Now prepare the temporary array and push it on the 'undeclared' stack
608 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
609 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
610 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
611 self::PACKAGE_DATA_PROTOCOL => $protocolName,
612 self::PACKAGE_DATA_CONTENT => $content,
613 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
614 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
619 * Checks whether a package has been enqueued for delivery.
621 * @return $isEnqueued Whether a package is enqueued
623 public function isPackageEnqueued () {
624 // Check whether the stacker is not empty
625 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
632 * Checks whether a package has been declared
634 * @return $isDeclared Whether a package is declared
636 public function isPackageDeclared () {
637 // Check whether the stacker is not empty
638 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
645 * Checks whether a package should be sent out
647 * @return $isWaitingDelivery Whether a package is waiting for delivery
649 public function isPackageWaitingForDelivery () {
650 // Check whether the stacker is not empty
651 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
654 return $isWaitingDelivery;
658 * Delivers an enqueued package to the stated destination. If a non-session
659 * id is provided, recipient resolver is being asked (and instanced once).
660 * This allows that a single package is being delivered to multiple targets
661 * without enqueueing it for every target. If no target is provided or it
662 * can't be determined a NoTargetException is being thrown.
665 * @throws NoTargetException If no target can't be determined
667 public function declareEnqueuedPackage () {
668 // Make sure this method isn't working if there is no package enqueued
669 if (!$this->isPackageEnqueued()) {
670 // This is not fatal but should be avoided
671 // @TODO Add some logging here
676 * Now there are for sure packages to deliver, so start with the first
679 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
681 // Declare the raw package data for delivery
682 $this->declareRawPackageData($packageData);
684 // And remove it finally
685 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
689 * Delivers the next declared package. Only one package per time will be sent
690 * because this may take time and slows down the whole delivery
695 public function deliverDeclaredPackage () {
696 // Sanity check if we have packages declared
697 if (!$this->isPackageDeclared()) {
698 // This is not fatal but should be avoided
699 $this->debugOutput('PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
704 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
707 // And try to send it
708 $this->deliverRawPackageData($packageData);
710 // And remove it finally
711 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
712 } catch (InvalidStateException $e) {
713 // The state is not excepected (shall be 'connected')
714 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
716 // Mark the package with status failed
717 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
722 * Sends waiting packages out for delivery
726 public function sendWaitingPackage () {
727 // Send any waiting bytes in the back-buffer before sending a new package
728 $this->sendBackBufferBytes();
730 // Sanity check if we have packages waiting for delivery
731 if (!$this->isPackageWaitingForDelivery()) {
732 // This is not fatal but should be avoided
733 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
738 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
741 // Now try to send it
742 $this->sendOutgoingRawPackageData($packageData);
744 // And remove it finally
745 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
746 } catch (InvalidSocketException $e) {
747 // Output exception message
748 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
750 // Mark package as failed
751 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
755 ///////////////////////////////////////////////////////////////////////////
756 // Receiving packages / raw data
757 ///////////////////////////////////////////////////////////////////////////
760 * Checks whether decoded raw data is pending
762 * @return $isPending Whether decoded raw data is pending
764 private function isDecodedDataPending () {
765 // Just return whether the stack is not empty
766 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
773 * Checks whether new raw package data has arrived at a socket
775 * @param $poolInstance An instance of a PoolableListener class
776 * @return $hasArrived Whether new raw package data has arrived for processing
778 public function isNewRawDataPending (PoolableListener $poolInstance) {
779 // Visit the pool. This monitors the pool for incoming raw data.
780 $poolInstance->accept($this->getVisitorInstance());
782 // Check for new data arrival
783 $hasArrived = $this->isDecodedDataPending();
790 * Handles the incoming decoded raw data. This method does not "convert" the
791 * decoded data back into a package array, it just "handles" it and pushs it
796 public function handleIncomingDecodedData () {
798 * This method should only be called if decoded raw data is pending,
801 if (!$this->isDecodedDataPending()) {
802 // This is not fatal but should be avoided
803 // @TODO Add some logging here
807 // Very noisy debug message:
808 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
810 // "Pop" the next entry (the same array again) from the stack
811 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
813 // Make sure both array elements are there
815 (is_array($decodedData)) &&
816 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
817 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
821 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
822 * only want to handle unhandled packages here.
824 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
825 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
827 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
828 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
829 // It is there and should be removed
830 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
833 // This package is "handled" and can be pushed on the next stack
834 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
838 * Adds raw decoded data from the given handler instance to this receiver
840 * @param $handlerInstance An instance of a Networkable class
843 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
845 * Get the decoded data from the handler, this is an array with
846 * 'decoded_data' and 'error_code' as elements.
848 $decodedData = $handlerInstance->getNextDecodedData();
850 // Very noisy debug message:
851 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
853 // And push it on our stack
854 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
858 * Checks whether incoming decoded data is handled.
860 * @return $isHandled Whether incoming decoded data is handled
862 public function isIncomingDecodedDataHandled () {
863 // Determine if the stack is not empty
864 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
871 * Checks whether the assembler has pending data left
873 * @return $isHandled Whether the assembler has pending data left
875 public function ifAssemblerHasPendingDataLeft () {
876 // Determine if the stack is not empty
877 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
884 * Handles the attached assemler's pending data queue to be finally
885 * assembled to the raw package data back.
889 public function handleAssemblerPendingData () {
891 $this->getAssemblerInstance()->handlePendingData();
895 * Assembles incoming decoded data so it will become an abstract network
896 * package again. The assembler does later do it's job by an other task,
897 * not this one to keep best speed possible.
901 public function assembleDecodedDataToPackage () {
902 // Make sure the raw decoded package data is handled
903 assert($this->isIncomingDecodedDataHandled());
905 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
906 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
908 // Start assembling the raw package data array by chunking it
909 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
911 // Remove the package from 'handled_decoded' stack ...
912 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
914 // ... and push it on the 'chunked' stacker
915 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
919 * Accepts the visitor to process the visit "request"
921 * @param $visitorInstance An instance of a Visitor class
924 public function accept (Visitor $visitorInstance) {
926 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
929 $visitorInstance->visitNetworkPackage($this);
932 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
940 public function clearAllStacker () {
941 // Call the init method to force re-initialization
942 $this->initStackers(true);
945 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
949 * Removes the first failed outoging package from the stack to continue
950 * with next one (it will never work until the issue is fixed by you).
953 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
954 * @todo This may be enchanced for outgoing packages?
956 public function removeFirstFailedPackage () {
957 // Get the package again
958 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
960 // Is the package status 'failed'?
961 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
963 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
967 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
971 * "Decode" the package content into the same array when it was sent.
973 * @param $rawPackageContent The raw package content to be "decoded"
974 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
976 public function decodeRawContent ($rawPackageContent) {
977 // Use the separator '#' to "decode" it
978 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
980 // Assert on count (should be always 3)
981 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
983 // Generate the signature of comparing it
985 * @todo Unsupported feature of "signed" messages commented out
986 if (!$this->isPackageSignatureValid($decodedArray)) {
987 // Is not valid, so throw an exception here
988 die(__METHOD__ . ':INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
993 * Create 'decodedData' array with all assoziative array elements,
996 $decodedData = array(
997 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
998 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
999 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1000 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED
1004 return $decodedData;
1008 * Handles decoded data for this node by "decoding" the 'content' part of
1009 * it. Again this method uses explode() for the "decoding" process.
1011 * @param $decodedData An array with decoded raw package data
1013 * @throws InvalidDataChecksumException If the checksum doesn't match
1015 public function handleDecodedData (array $decodedData) {
1017 * "Decode" the package's content by a simple explode() call, for
1018 * details of the array elements, see comments for constant
1021 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1023 // Assert on array count for a very basic validation
1024 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1027 * Convert the indexed array into an associative array. This is much
1028 * better to remember than plain numbers, isn't it?
1030 $decodedContent = array(
1031 // Compressor's extension used to compress the data
1032 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1033 // Package data (aka "message") in BASE64-decoded form but still compressed
1034 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1035 // Tags as an indexed array for "tagging" the message
1036 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1037 // Checksum of the _decoded_ data
1038 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM]
1041 // Is the checksum valid?
1042 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1043 // Is not the same, so throw an exception here
1044 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1048 * The checksum is the same, then it can be decompressed safely. The
1049 * original message is at this point fully decoded.
1051 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1053 // And push it on the next stack
1054 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1058 * Checks whether a new message has arrived
1060 * @return $hasArrived Whether a new message has arrived for processing
1062 public function isNewMessageArrived () {
1063 // Determine if the stack is not empty
1064 $hasArrived = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1071 * Handles newly arrived messages
1074 * @todo Implement verification of all sent tags here?
1076 public function handleNewlyArrivedMessage () {
1077 // Get it from the stacker, it is the full array with the decoded message
1078 $decodedContent = $this->getStackerInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1080 // Now get a filter chain back from factory with given tags array
1081 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1084 * Process the message through all filters, note that all other
1085 * elements from $decodedContent are no longer needed.
1087 $chainInstance->processMessage($decodedContent[self::PACKAGE_CONTENT_MESSAGE], $this);
1091 * Checks whether a processed message is pending for "interpretation"
1093 * @return $isPending Whether a processed message is pending
1095 public function isProcessedMessagePending () {
1097 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1104 * Handle processed messages by "interpreting" the 'message_type' element
1108 public function handleProcessedMessage () {
1109 // Get it from the stacker, it is the full array with the processed message
1110 $messageArray = $this->getStackerInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1112 // Create a handler instance from given message type
1113 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1115 // Handle message data
1116 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1118 die(__METHOD__ . ':messageArray='.print_r($messageArray,true));