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';
111 const PACKAGE_STATUS_FAKED = 'faked';
114 * Constants for message data array
116 const MESSAGE_ARRAY_DATA = 'message_data';
117 const MESSAGE_ARRAY_TYPE = 'message_type';
122 const PACKAGE_TAGS_SEPARATOR = ';';
125 * Raw package data separator
127 const PACKAGE_DATA_SEPARATOR = '#';
130 * Separator for more than one recipient
132 const PACKAGE_RECIPIENT_SEPARATOR = ':';
135 * Network target (alias): 'upper hubs'
137 const NETWORK_TARGET_UPPER_HUBS = 'upper';
140 * Network target (alias): 'self'
142 const NETWORK_TARGET_SELF = 'self';
145 * TCP package size in bytes
147 const TCP_PACKAGE_SIZE = 512;
149 /**************************************************************************
150 * Stacker for out-going packages *
151 **************************************************************************/
154 * Stacker name for "undeclared" packages
156 const STACKER_NAME_UNDECLARED = 'package_undeclared';
159 * Stacker name for "declared" packages (which are ready to send out)
161 const STACKER_NAME_DECLARED = 'package_declared';
164 * Stacker name for "out-going" packages
166 const STACKER_NAME_OUTGOING = 'package_outgoing';
168 /**************************************************************************
169 * Stacker for incoming packages *
170 **************************************************************************/
173 * Stacker name for "incoming" decoded raw data
175 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
178 * Stacker name for handled decoded raw data
180 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
183 * Stacker name for "chunked" decoded raw data
185 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
187 /**************************************************************************
188 * Stacker for incoming messages *
189 **************************************************************************/
192 * Stacker name for new messages
194 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
197 * Stacker name for processed messages
199 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
201 /**************************************************************************
202 * Stacker for other/internal purposes *
203 **************************************************************************/
206 * Stacker name for "back-buffered" packages
208 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
211 * Protected constructor
215 protected function __construct () {
216 // Call parent constructor
217 parent::__construct(__CLASS__);
221 * Creates an instance of this class
223 * @param $compressorInstance A Compressor instance for compressing the content
224 * @return $packageInstance An instance of a Deliverable class
226 public static final function createNetworkPackage (Compressor $compressorInstance) {
228 $packageInstance = new NetworkPackage();
230 // Now set the compressor instance
231 $packageInstance->setCompressorInstance($compressorInstance);
234 * We need to initialize a stack here for our packages even for those
235 * which have no recipient address and stamp... ;-) This stacker will
236 * also be used for incoming raw data to handle it.
238 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
240 // At last, set it in this class
241 $packageInstance->setStackerInstance($stackerInstance);
244 $packageInstance->initStackers();
246 // Get a visitor instance for speeding up things
247 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
249 // Set it in this package
250 $packageInstance->setVisitorInstance($visitorInstance);
252 // Get crypto instance and set it in this package
253 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
254 $packageInstance->setCryptoInstance($cryptoInstance);
256 // Get a singleton package assembler instance from factory and set it here
257 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
258 $packageInstance->setAssemblerInstance($assemblerInstance);
260 // Return the prepared instance
261 return $packageInstance;
265 * Initialize all stackers
267 * @param $forceReInit Whether to force reinitialization of all stacks
270 protected function initStackers ($forceReInit = false) {
274 self::STACKER_NAME_UNDECLARED,
275 self::STACKER_NAME_DECLARED,
276 self::STACKER_NAME_OUTGOING,
277 self::STACKER_NAME_DECODED_INCOMING,
278 self::STACKER_NAME_DECODED_HANDLED,
279 self::STACKER_NAME_DECODED_CHUNKED,
280 self::STACKER_NAME_NEW_MESSAGE,
281 self::STACKER_NAME_PROCESSED_MESSAGE,
282 self::STACKER_NAME_BACK_BUFFER
285 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
290 * "Getter" for hash from given content
292 * @param $content Raw package content
293 * @return $hash Hash for given package content
295 private function getHashFromContent ($content) {
297 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
300 // @TODO crc32() is very weak, but it needs to be fast
303 self::PACKAGE_CHECKSUM_SEPARATOR .
304 $this->getSessionId() .
305 self::PACKAGE_CHECKSUM_SEPARATOR .
306 $this->getCompressorInstance()->getCompressorExtension()
314 * Checks whether the checksum (sometimes called "hash") is the same
316 * @param $decodedContent Package raw content
317 * @param $decodedData Whole raw package data array
318 * @return $isChecksumValid Whether the checksum is the same
320 private function isChecksumValid (array $decodedContent, array $decodedData) {
322 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
325 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
328 return $isChecksumValid;
332 * Change the package with given status in given stack
334 * @param $packageData Raw package data in an array
335 * @param $stackerName Name of the stacker
336 * @param $newStatus New status to set
339 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
340 // Skip this for empty stacks
341 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
342 // This avoids an exception after all packages has failed
346 // Pop the entry (it should be it)
347 $nextData = $this->getStackerInstance()->popNamed($stackerName);
349 // Compare both signatures
350 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
352 // Temporary set the new status
353 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
356 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
360 * "Getter" for hash from given content and sender's session id
362 * @param $decodedContent Decoded package content
363 * @param $sessionId Session id of the sender
364 * @return $hash Hash for given package content
366 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
368 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
371 // @TODO crc32() is very weak, but it needs to be fast
373 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
374 self::PACKAGE_CHECKSUM_SEPARATOR .
376 self::PACKAGE_CHECKSUM_SEPARATOR .
377 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
384 ///////////////////////////////////////////////////////////////////////////
385 // Delivering packages / raw data
386 ///////////////////////////////////////////////////////////////////////////
389 * Delivers the given raw package data.
391 * @param $packageData Raw package data in an array
394 private function declareRawPackageData (array $packageData) {
396 * We need to disover every recipient, just in case we have a
397 * multi-recipient entry like 'upper' is. 'all' may be a not so good
398 * target because it causes an overload on the network and may be
399 * abused for attacking the network with large packages.
401 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
403 // Discover all recipients, this may throw an exception
404 $discoveryInstance->discoverRecipients($packageData);
406 // Now get an iterator
407 $iteratorInstance = $discoveryInstance->getIterator();
409 // Rewind back to the beginning
410 $iteratorInstance->rewind();
412 // ... and begin iteration
413 while ($iteratorInstance->valid()) {
415 $currentRecipient = $iteratorInstance->current();
418 $this->debugOutput('NETWORK-PACKAGE: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
421 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
423 // And enqueue it to the writer class
424 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
427 $this->debugOutput('NETWORK-PACKAGE: Package declared for recipient ' . $currentRecipient);
429 // Skip to next entry
430 $iteratorInstance->next();
434 * The recipient list can be cleaned up here because the package which
435 * shall be delivered has already been added for all entries from the
438 $discoveryInstance->clearRecipients();
442 * Delivers raw package data. In short, this will discover the raw socket
443 * resource through a discovery class (which will analyse the receipient of
444 * the package), register the socket with the connection (handler/helper?)
445 * instance and finally push the raw data on our outgoing queue.
447 * @param $packageData Raw package data in an array
450 private function deliverRawPackageData (array $packageData) {
452 * This package may become big, depending on the shared object size or
453 * delivered message size which shouldn't be so long (to save
454 * bandwidth). Because of the nature of the used protocol (TCP) we need
455 * to split it up into smaller pieces to fit it into a TCP frame.
457 * So first we need (again) a discovery class but now a protocol
458 * discovery to choose the right socket resource. The discovery class
459 * should take a look at the raw package data itself and then decide
460 * which (configurable!) protocol should be used for that type of
463 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
465 // Now discover the right protocol
466 $socketResource = $discoveryInstance->discoverSocket($packageData);
469 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
471 // We have to put this socket in our registry, so get an instance
472 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
474 // Get the listener from registry
475 $helperInstance = Registry::getRegistry()->getInstance('connection');
478 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
479 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
482 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
484 $this->debugOutput('NETWORK-PACKAGE: Registering socket ' . $socketResource . ' ...');
487 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
488 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
489 // Is not connected, then we cannot send
490 $this->debugOutput('NETWORK-PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
492 // Shutdown the socket
493 $this->shutdownSocket($socketResource);
497 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
499 // Make sure the connection is up
500 $helperInstance->getStateInstance()->validatePeerStateConnected();
503 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
505 // Enqueue it again on the out-going queue, the connection is up and working at this point
506 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
509 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
513 * Sends waiting packages
515 * @param $packageData Raw package data
518 private function sendOutgoingRawPackageData (array $packageData) {
522 // Get the right connection instance
523 $helperInstance = SocketRegistryFactory::createSocketRegistryInstance()->getHandlerInstanceFromPackageData($packageData);
525 // Is this connection still alive?
526 if ($helperInstance->isShuttedDown()) {
527 // This connection is shutting down
528 // @TODO We may want to do somthing more here?
532 // Sent out package data
533 $sentBytes = $helperInstance->sendRawPackageData($packageData);
535 // Remember unsent raw bytes in back-buffer, if any
536 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
540 * Generates a signature for given raw package content and sender id
542 * @param $content Raw package data
543 * @param $senderId Sender id to generate a signature for
544 * @return $signature Signature as BASE64-encoded string
546 private function generatePackageSignature ($content, $senderId) {
547 // ash content and sender id together, use md5() as last algo
548 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getNodeId(), false));
550 // Encrypt the content again with the hash as a key
551 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
553 // Encode it with BASE64
554 $signature = base64_encode($encryptedContent);
561 * Checks whether the signature of given package data is 'valid', here that
562 * means it is the same or not.
564 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
565 * @return $isSignatureValid Whether the signature is valid
566 * @todo Unfinished area, signatures are currently NOT fully supported
568 private function isPackageSignatureValid (array $decodedArray) {
569 // Generate the signature of comparing it
570 $signature = $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER]);
573 //$isSignatureValid =
574 die(__METHOD__.': signature='.$signature.chr(10).',decodedArray='.print_r($decodedArray,true));
578 * "Enqueues" raw content into this delivery class by reading the raw content
579 * from given helper's template instance and pushing it on the 'undeclared'
582 * @param $helperInstance An instance of a HelpableHub class
583 * @param $protocol Name of used protocol (TCP/UDP)
586 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, $protocolName) {
587 // Get the raw content ...
588 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
590 // ... and compress it
591 $content = $this->getCompressorInstance()->compressStream($content);
593 // Add magic in front of it and hash behind it, including BASE64 encoding
594 $content = sprintf(self::PACKAGE_MASK,
595 // 1.) Compressor's extension
596 $this->getCompressorInstance()->getCompressorExtension(),
598 self::PACKAGE_MASK_SEPARATOR,
599 // 2.) Raw package content, encoded with BASE64
600 base64_encode($content),
602 self::PACKAGE_MASK_SEPARATOR,
604 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
606 self::PACKAGE_MASK_SEPARATOR,
608 $this->getHashFromContent($content)
611 // Now prepare the temporary array and push it on the 'undeclared' stack
612 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
613 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
614 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
615 self::PACKAGE_DATA_PROTOCOL => $protocolName,
616 self::PACKAGE_DATA_CONTENT => $content,
617 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
618 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
623 * Checks whether a package has been enqueued for delivery.
625 * @return $isEnqueued Whether a package is enqueued
627 public function isPackageEnqueued () {
628 // Check whether the stacker is not empty
629 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
636 * Checks whether a package has been declared
638 * @return $isDeclared Whether a package is declared
640 public function isPackageDeclared () {
641 // Check whether the stacker is not empty
642 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
649 * Checks whether a package should be sent out
651 * @return $isWaitingDelivery Whether a package is waiting for delivery
653 public function isPackageWaitingForDelivery () {
654 // Check whether the stacker is not empty
655 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
658 return $isWaitingDelivery;
662 * Delivers an enqueued package to the stated destination. If a non-session
663 * id is provided, recipient resolver is being asked (and instanced once).
664 * This allows that a single package is being delivered to multiple targets
665 * without enqueueing it for every target. If no target is provided or it
666 * can't be determined a NoTargetException is being thrown.
669 * @throws NoTargetException If no target can't be determined
671 public function declareEnqueuedPackage () {
672 // Make sure this method isn't working if there is no package enqueued
673 if (!$this->isPackageEnqueued()) {
674 // This is not fatal but should be avoided
675 // @TODO Add some logging here
680 * Now there are for sure packages to deliver, so start with the first
683 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
685 // Declare the raw package data for delivery
686 $this->declareRawPackageData($packageData);
688 // And remove it finally
689 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
693 * Delivers the next declared package. Only one package per time will be sent
694 * because this may take time and slows down the whole delivery
699 public function deliverDeclaredPackage () {
700 // Sanity check if we have packages declared
701 if (!$this->isPackageDeclared()) {
702 // This is not fatal but should be avoided
703 $this->debugOutput('NETWORK-PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
708 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
711 // And try to send it
712 $this->deliverRawPackageData($packageData);
714 // And remove it finally
715 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
716 } catch (InvalidStateException $e) {
717 // The state is not excepected (shall be 'connected')
718 $this->debugOutput('NETWORK-PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
720 // Mark the package with status failed
721 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
726 * Sends waiting packages out for delivery
730 public function sendWaitingPackage () {
731 // Send any waiting bytes in the back-buffer before sending a new package
732 $this->sendBackBufferBytes();
734 // Sanity check if we have packages waiting for delivery
735 if (!$this->isPackageWaitingForDelivery()) {
736 // This is not fatal but should be avoided
737 $this->debugOutput('NETWORK-PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
742 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
745 // Now try to send it
746 $this->sendOutgoingRawPackageData($packageData);
748 // And remove it finally
749 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
750 } catch (InvalidSocketException $e) {
751 // Output exception message
752 $this->debugOutput('NETWORK-PACKAGE: Package was not delivered: ' . $e->getMessage());
754 // Mark package as failed
755 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
759 ///////////////////////////////////////////////////////////////////////////
760 // Receiving packages / raw data
761 ///////////////////////////////////////////////////////////////////////////
764 * Checks whether decoded raw data is pending
766 * @return $isPending Whether decoded raw data is pending
768 private function isDecodedDataPending () {
769 // Just return whether the stack is not empty
770 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
777 * Checks whether new raw package data has arrived at a socket
779 * @param $poolInstance An instance of a PoolableListener class
780 * @return $hasArrived Whether new raw package data has arrived for processing
782 public function isNewRawDataPending (PoolableListener $poolInstance) {
783 // Visit the pool. This monitors the pool for incoming raw data.
784 $poolInstance->accept($this->getVisitorInstance());
786 // Check for new data arrival
787 $hasArrived = $this->isDecodedDataPending();
794 * Handles the incoming decoded raw data. This method does not "convert" the
795 * decoded data back into a package array, it just "handles" it and pushs it
800 public function handleIncomingDecodedData () {
802 * This method should only be called if decoded raw data is pending,
805 if (!$this->isDecodedDataPending()) {
806 // This is not fatal but should be avoided
807 // @TODO Add some logging here
811 // Very noisy debug message:
812 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
814 // "Pop" the next entry (the same array again) from the stack
815 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
817 // Make sure both array elements are there
819 (is_array($decodedData)) &&
820 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
821 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
825 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
826 * only want to handle unhandled packages here.
828 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
829 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
831 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
832 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
833 // It is there and should be removed
834 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
837 // This package is "handled" and can be pushed on the next stack
838 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
842 * Adds raw decoded data from the given handler instance to this receiver
844 * @param $handlerInstance An instance of a Networkable class
847 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
849 * Get the decoded data from the handler, this is an array with
850 * 'decoded_data' and 'error_code' as elements.
852 $decodedData = $handlerInstance->getNextDecodedData();
854 // Very noisy debug message:
855 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
857 // And push it on our stack
858 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
862 * Checks whether incoming decoded data is handled.
864 * @return $isHandled Whether incoming decoded data is handled
866 public function isIncomingDecodedDataHandled () {
867 // Determine if the stack is not empty
868 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
875 * Checks whether the assembler has pending data left
877 * @return $isHandled Whether the assembler has pending data left
879 public function ifAssemblerHasPendingDataLeft () {
880 // Determine if the stack is not empty
881 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
888 * Handles the attached assemler's pending data queue to be finally
889 * assembled to the raw package data back.
893 public function handleAssemblerPendingData () {
895 $this->getAssemblerInstance()->handlePendingData();
899 * Assembles incoming decoded data so it will become an abstract network
900 * package again. The assembler does later do it's job by an other task,
901 * not this one to keep best speed possible.
905 public function assembleDecodedDataToPackage () {
906 // Make sure the raw decoded package data is handled
907 assert($this->isIncomingDecodedDataHandled());
909 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
910 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
912 // Start assembling the raw package data array by chunking it
913 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
915 // Remove the package from 'handled_decoded' stack ...
916 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
918 // ... and push it on the 'chunked' stacker
919 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
923 * Accepts the visitor to process the visit "request"
925 * @param $visitorInstance An instance of a Visitor class
928 public function accept (Visitor $visitorInstance) {
930 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
933 $visitorInstance->visitNetworkPackage($this);
936 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
944 public function clearAllStacker () {
945 // Call the init method to force re-initialization
946 $this->initStackers(true);
949 /* DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: All stacker have been re-initialized.');
953 * Removes the first failed outoging package from the stack to continue
954 * with next one (it will never work until the issue is fixed by you).
957 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
958 * @todo This may be enchanced for outgoing packages?
960 public function removeFirstFailedPackage () {
961 // Get the package again
962 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
964 // Is the package status 'failed'?
965 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
967 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
971 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
975 * "Decode" the package content into the same array when it was sent.
977 * @param $rawPackageContent The raw package content to be "decoded"
978 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
980 public function decodeRawContent ($rawPackageContent) {
981 // Use the separator '#' to "decode" it
982 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
984 // Assert on count (should be always 3)
985 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
987 // Generate the signature of comparing it
989 * @todo Unsupported feature of "signed" messages commented out
990 if (!$this->isPackageSignatureValid($decodedArray)) {
991 // Is not valid, so throw an exception here
992 die(__METHOD__ . ':INVALID SIG! UNDER CONSTRUCTION!' . chr(10));
997 * Create 'decodedData' array with all assoziative array elements,
1000 $decodedData = array(
1001 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
1002 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1003 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1004 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED
1008 return $decodedData;
1012 * Handles decoded data for this node by "decoding" the 'content' part of
1013 * it. Again this method uses explode() for the "decoding" process.
1015 * @param $decodedData An array with decoded raw package data
1017 * @throws InvalidDataChecksumException If the checksum doesn't match
1019 public function handleDecodedData (array $decodedData) {
1021 * "Decode" the package's content by a simple explode() call, for
1022 * details of the array elements, see comments for constant
1025 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1027 // Assert on array count for a very basic validation
1028 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1031 * Convert the indexed array into an associative array. This is much
1032 * better to remember than plain numbers, isn't it?
1034 $decodedContent = array(
1035 // Compressor's extension used to compress the data
1036 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1037 // Package data (aka "message") in BASE64-decoded form but still compressed
1038 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1039 // Tags as an indexed array for "tagging" the message
1040 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1041 // Checksum of the _decoded_ data
1042 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM]
1045 // Is the checksum valid?
1046 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1047 // Is not the same, so throw an exception here
1048 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1052 * The checksum is the same, then it can be decompressed safely. The
1053 * original message is at this point fully decoded.
1055 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1057 // And push it on the next stack
1058 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1062 * Checks whether a new message has arrived
1064 * @return $hasArrived Whether a new message has arrived for processing
1066 public function isNewMessageArrived () {
1067 // Determine if the stack is not empty
1068 $hasArrived = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1075 * Handles newly arrived messages
1078 * @todo Implement verification of all sent tags here?
1080 public function handleNewlyArrivedMessage () {
1081 // Get it from the stacker, it is the full array with the decoded message
1082 $decodedContent = $this->getStackerInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1084 // Now get a filter chain back from factory with given tags array
1085 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1088 * Process the message through all filters, note that all other
1089 * elements from $decodedContent are no longer needed.
1091 $chainInstance->processMessage($decodedContent[self::PACKAGE_CONTENT_MESSAGE], $this);
1095 * Checks whether a processed message is pending for "interpretation"
1097 * @return $isPending Whether a processed message is pending
1099 public function isProcessedMessagePending () {
1101 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1108 * Handle processed messages by "interpreting" the 'message_type' element
1112 public function handleProcessedMessage () {
1113 // Get it from the stacker, it is the full array with the processed message
1114 $messageArray = $this->getStackerInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1116 // Create a handler instance from given message type
1117 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1119 // Handle message data
1120 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);