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@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Hub Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.shipsimu.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_HASH = 4;
83 * Size of the decoded data array
85 const DECODED_DATA_ARRAY_SIZE = 5;
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';
94 const PACKAGE_CONTENT_SENDER = 'sender';
95 const PACKAGE_CONTENT_HASH = 'hash';
98 * Named array elements for package data
100 const PACKAGE_DATA_SENDER = 'sender';
101 const PACKAGE_DATA_RECIPIENT = 'recipient';
102 const PACKAGE_DATA_CONTENT = 'content';
103 const PACKAGE_DATA_STATUS = 'status';
104 const PACKAGE_DATA_HASH = 'hash';
109 const PACKAGE_STATUS_NEW = 'new';
110 const PACKAGE_STATUS_FAILED = 'failed';
111 const PACKAGE_STATUS_DECODED = 'decoded';
112 const PACKAGE_STATUS_FAKED = 'faked';
115 * Constants for message data array
117 const MESSAGE_ARRAY_DATA = 'message_data';
118 const MESSAGE_ARRAY_TYPE = 'message_type';
121 * Generic answer status field
127 const PACKAGE_TAGS_SEPARATOR = ';';
130 * Raw package data separator
132 const PACKAGE_DATA_SEPARATOR = '#';
135 * Separator for more than one recipient
137 const PACKAGE_RECIPIENT_SEPARATOR = ':';
140 * Network target (alias): 'upper nodes'
142 const NETWORK_TARGET_UPPER = 'upper';
145 * Network target (alias): 'self'
147 const NETWORK_TARGET_SELF = 'self';
150 * Network target (alias): 'dht'
152 const NETWORK_TARGET_DHT = 'dht';
155 * TCP package size in bytes
157 const TCP_PACKAGE_SIZE = 512;
159 /**************************************************************************
160 * Stacker for out-going packages *
161 **************************************************************************/
164 * Stacker name for "undeclared" packages
166 const STACKER_NAME_UNDECLARED = 'package_undeclared';
169 * Stacker name for "declared" packages (which are ready to send out)
171 const STACKER_NAME_DECLARED = 'package_declared';
174 * Stacker name for "out-going" packages
176 const STACKER_NAME_OUTGOING = 'package_outgoing';
178 /**************************************************************************
179 * Stacker for incoming packages *
180 **************************************************************************/
183 * Stacker name for "incoming" decoded raw data
185 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
188 * Stacker name for handled decoded raw data
190 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
193 * Stacker name for "chunked" decoded raw data
195 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
197 /**************************************************************************
198 * Stacker for incoming messages *
199 **************************************************************************/
202 * Stacker name for new messages
204 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
207 * Stacker name for processed messages
209 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
211 /**************************************************************************
212 * Stacker for raw data handling *
213 **************************************************************************/
216 * Stacker for outgoing data stream
218 const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
221 * Array index for final hash
223 const RAW_FINAL_HASH_INDEX = 'hash';
226 * Array index for encoded data
228 const RAW_ENCODED_DATA_INDEX = 'data';
231 * Array index for sent bytes
233 const RAW_SENT_BYTES_INDEX = 'sent';
236 * Array index for socket resource
238 const RAW_SOCKET_INDEX = 'socket';
241 * Array index for buffer size
243 const RAW_BUFFER_SIZE_INDEX = 'buffer';
246 * Array index for diff between buffer and sent bytes
248 const RAW_DIFF_INDEX = 'diff';
250 /**************************************************************************
252 **************************************************************************/
253 const PROTOCOL_TCP = 'TCP';
254 const PROTOCOL_UDP = 'UDP';
257 * Protected constructor
261 protected function __construct () {
262 // Call parent constructor
263 parent::__construct(__CLASS__);
267 * Creates an instance of this class
269 * @param $compressorInstance A Compressor instance for compressing the content
270 * @return $packageInstance An instance of a Deliverable class
272 public static final function createNetworkPackage (Compressor $compressorInstance) {
274 $packageInstance = new NetworkPackage();
276 // Now set the compressor instance
277 $packageInstance->setCompressorInstance($compressorInstance);
280 * We need to initialize a stack here for our packages even for those
281 * which have no recipient address and stamp... ;-) This stacker will
282 * also be used for incoming raw data to handle it.
284 $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
286 // At last, set it in this class
287 $packageInstance->setStackInstance($stackInstance);
290 $packageInstance->initStacks();
292 // Get a visitor instance for speeding up things and set it
293 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class');
294 $packageInstance->setVisitorInstance($visitorInstance);
296 // Get crypto instance and set it, too
297 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
298 $packageInstance->setCryptoInstance($cryptoInstance);
300 // Get a singleton package assembler instance from factory and set it here, too
301 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
302 $packageInstance->setAssemblerInstance($assemblerInstance);
305 $nodeInstance = NodeObjectFactory::createNodeInstance();
307 // Get pool instance from node
308 $poolInstance = $nodeInstance->getListenerPoolInstance();
311 $packageInstance->setListenerPoolInstance($poolInstance);
313 // Return the prepared instance
314 return $packageInstance;
318 * Initialize all stackers
320 * @param $forceReInit Whether to force reinitialization of all stacks
323 protected function initStacks ($forceReInit = FALSE) {
325 $this->getStackInstance()->initStacks(array(
326 self::STACKER_NAME_UNDECLARED,
327 self::STACKER_NAME_DECLARED,
328 self::STACKER_NAME_OUTGOING,
329 self::STACKER_NAME_DECODED_INCOMING,
330 self::STACKER_NAME_DECODED_HANDLED,
331 self::STACKER_NAME_DECODED_CHUNKED,
332 self::STACKER_NAME_NEW_MESSAGE,
333 self::STACKER_NAME_PROCESSED_MESSAGE,
334 self::STACKER_NAME_OUTGOING_STREAM
339 * Determines private key hash from given session id
341 * @param $decodedData Array with decoded data
342 * @return $hash Private key's hash
344 private function determineSenderPrivateKeyHash (array $decodedData) {
346 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
348 // Ask DHT for session id
349 $senderData = $dhtInstance->findNodeLocalBySessionId($decodedData[self::INDEX_PACKAGE_SENDER]);
351 // Is an entry found?
352 if (count($senderData) > 0) {
353 // Make sure the element 'private_key_hash' is there
354 /* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderData=' . print_r($senderData, TRUE));
355 assert(isset($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH]));
358 return $senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH];
361 // Make sure the requested element is there
362 assert(isset($decodedData[self::INDEX_PACKAGE_HASH]));
364 // There is no DHT entry so, accept the hash from decoded data
365 return $decodedData[self::INDEX_PACKAGE_HASH];
369 * "Getter" for hash from given content
371 * @param $content Raw package content
372 * @return $hash Hash for given package content
374 private function getHashFromContent ($content) {
376 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
379 // @TODO md5() is very weak, but it needs to be fast
382 self::PACKAGE_CHECKSUM_SEPARATOR .
383 $this->getSessionId() .
384 self::PACKAGE_CHECKSUM_SEPARATOR .
385 $this->getCompressorInstance()->getCompressorExtension()
389 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
396 * Checks whether the checksum (sometimes called "hash") is the same
398 * @param $decodedContent Package raw content
399 * @param $decodedData Whole raw package data array
400 * @return $isChecksumValid Whether the checksum is the same
402 private function isChecksumValid (array $decodedContent, array $decodedData) {
404 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
407 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
410 return $isChecksumValid;
414 * Change the package with given status in given stack
416 * @param $packageData Raw package data in an array
417 * @param $stackerName Name of the stacker
418 * @param $newStatus New status to set
421 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
422 // Skip this for empty stacks
423 if ($this->getStackInstance()->isStackEmpty($stackerName)) {
424 // This avoids an exception after all packages has failed
428 // Pop the entry (it should be it)
429 $nextData = $this->getStackInstance()->popNamed($stackerName);
431 // Compare both hashes
432 assert($nextData[self::PACKAGE_DATA_HASH] == $packageData[self::PACKAGE_DATA_HASH]);
434 // Temporary set the new status
435 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
438 $this->getStackInstance()->pushNamed($stackerName, $packageData);
442 * "Getter" for hash from given content and sender's session id
444 * @param $decodedContent Raw package content
445 * @param $sessionId Session id of the sender
446 * @return $hash Hash for given package content
448 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
450 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
453 // @TODO md5() is very weak, but it needs to be fast
455 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
456 self::PACKAGE_CHECKSUM_SEPARATOR .
458 self::PACKAGE_CHECKSUM_SEPARATOR .
459 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
466 ///////////////////////////////////////////////////////////////////////////
467 // Delivering packages / raw data
468 ///////////////////////////////////////////////////////////////////////////
471 * Declares the given raw package data by discovering recipients
473 * @param $packageData Raw package data in an array
476 private function declareRawPackageData (array $packageData) {
477 // Make sure the required field is there
478 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
481 * We need to disover every recipient, just in case we have a
482 * multi-recipient entry like 'upper' is. 'all' may be a not so good
483 * target because it causes an overload on the network and may be
484 * abused for attacking the network with large packages.
486 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
488 // Discover all recipients, this may throw an exception
489 $discoveryInstance->discoverRecipients($packageData);
491 // Now get an iterator
492 $iteratorInstance = $discoveryInstance->getIterator();
494 // Make sure the iterator instance is valid
495 assert($iteratorInstance instanceof Iterator);
497 // Rewind back to the beginning
498 $iteratorInstance->rewind();
500 // ... and begin iteration
501 while ($iteratorInstance->valid()) {
503 $currentRecipient = $iteratorInstance->current();
506 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
509 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
511 // Push the declared package to the next stack.
512 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
515 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
517 // Skip to next entry
518 $iteratorInstance->next();
522 * The recipient list can be cleaned up here because the package which
523 * shall be delivered has already been added for all entries from the
526 $discoveryInstance->clearRecipients();
530 * Delivers raw package data. In short, this will discover the raw socket
531 * resource through a discovery class (which will analyse the receipient of
532 * the package), register the socket with the connection (handler/helper?)
533 * instance and finally push the raw data on our outgoing queue.
535 * @param $packageData Raw package data in an array
538 private function deliverRawPackageData (array $packageData) {
540 * This package may become big, depending on the shared object size or
541 * delivered message size which shouldn't be so long (to save
542 * bandwidth). Because of the nature of the used protocol (TCP) we need
543 * to split it up into smaller pieces to fit it into a TCP frame.
545 * So first we need (again) a discovery class but now a protocol
546 * discovery to choose the right socket resource. The discovery class
547 * should take a look at the raw package data itself and then decide
548 * which (configurable!) protocol should be used for that type of
551 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
553 // Now discover the right protocol
554 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
557 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
560 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
561 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
563 // The socket needs to be put in a special registry that can handle such data
564 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
566 // Get the connection helper from registry
567 $helperInstance = Registry::getRegistry()->getInstance('connection');
569 // And make sure it is valid
570 assert($helperInstance instanceof ConnectionHelper);
572 // Get connection info class
573 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper');
575 // Will the info instance with connection helper data
576 $infoInstance->fillWithConnectionHelperInformation($helperInstance);
579 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($infoInstance, $socketResource))) {
581 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
584 $registryInstance->registerSocket($infoInstance, $socketResource, $packageData);
585 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
586 // Is not connected, then we cannot send
587 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
589 // Shutdown the socket
590 $this->shutdownSocket($socketResource);
594 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
596 // Make sure the connection is up
597 $helperInstance->getStateInstance()->validatePeerStateConnected();
600 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
602 // Enqueue it again on the out-going queue, the connection is up and working at this point
603 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
606 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
610 * Sends waiting packages
612 * @param $packageData Raw package data
615 private function sendOutgoingRawPackageData (array $packageData) {
619 // Get the right connection instance
620 $infoInstance = SocketRegistryFactory::createSocketRegistryInstance()->getInfoInstanceFromPackageData($packageData);
622 // Test helper instance
623 assert($infoInstance instanceof ShareableInfo);
625 // Get helper instance
626 $helperInstance = $infoInstance->getHelperInstance();
628 // Some sanity-checks on the object
629 //* DEBUG-DIE: */ die('[' . __METHOD__ . ':' . __LINE__ . ']: p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE));
630 assert($helperInstance instanceof ConnectionHelper);
631 assert($infoInstance->getProtocolName() == $helperInstance->getProtocolName());
633 // Is this connection still alive?
634 if ($helperInstance->isShuttedDown()) {
635 // This connection is shutting down
636 // @TODO We may want to do somthing more here?
640 // Sent out package data
641 $helperInstance->sendRawPackageData($packageData);
645 * Generates a secure hash for given raw package content and sender id
647 * @param $content Raw package data
648 * @param $senderId Sender id to generate a hash for
649 * @return $hash Hash as hex-encoded string
651 private function generatePackageHash ($content, $senderId) {
654 self::INDEX_PACKAGE_SENDER => $senderId,
655 self::INDEX_PACKAGE_CONTENT => $content,
656 self::INDEX_PACKAGE_HASH => ''
659 // Hash content and sender id together, use scrypt
660 $hash = Scrypt::hashScrypt($senderId . ':' . $content . ':' . $this->determineSenderPrivateKeyHash($data));
667 * Checks whether the hash of given package data is 'valid', here that
668 * means it is the same or not.
670 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
671 * @return $isHashValid Whether the hash is valid
672 * @todo Unfinished area, hashes are currently NOT fully supported
674 private function isPackageHashValid (array $decodedArray) {
676 $isHashValid = Scrypt::checkScrypt($decodedArray[self::INDEX_PACKAGE_SENDER] . ':' . $decodedArray[self::INDEX_PACKAGE_CONTENT] . ':' . $this->determineSenderPrivateKeyHash($decodedArray);
679 //* DEBUG-DIE: */ die(__METHOD__ . ': isHashValid=' . intval($isHashValid) . chr(10) . ',decodedArray=' . print_r($decodedArray, TRUE));
684 * "Enqueues" raw content into this delivery class by reading the raw content
685 * from given helper's template instance and pushing it on the 'undeclared'
688 * @param $helperInstance An instance of a HubHelper class
691 public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
693 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
695 // Get the raw content ...
696 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
697 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
699 // ... and compress it
700 $content = $this->getCompressorInstance()->compressStream($content);
702 // Add magic in front of it and hash behind it, including BASE64 encoding
703 $packageContent = sprintf(self::PACKAGE_MASK,
704 // 1.) Compressor's extension
705 $this->getCompressorInstance()->getCompressorExtension(),
707 self::PACKAGE_MASK_SEPARATOR,
708 // 2.) Raw package content, encoded with BASE64
709 base64_encode($content),
711 self::PACKAGE_MASK_SEPARATOR,
713 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
715 self::PACKAGE_MASK_SEPARATOR,
717 $this->getHashFromContent($content)
721 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
723 // Now prepare the temporary array and push it on the 'undeclared' stack
724 $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
725 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
726 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
727 self::PACKAGE_DATA_CONTENT => $packageContent,
728 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
729 self::PACKAGE_DATA_HASH => $this->generatePackageHash($packageContent, $this->getSessionId())
733 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
737 * Checks whether a package has been enqueued for delivery.
739 * @return $isEnqueued Whether a package is enqueued
741 public function isPackageEnqueued () {
742 // Check whether the stacker is not empty
743 $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
750 * Checks whether a package has been declared
752 * @return $isDeclared Whether a package is declared
754 public function isPackageDeclared () {
755 // Check whether the stacker is not empty
756 $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
763 * Checks whether a package should be sent out
765 * @return $isWaitingDelivery Whether a package is waiting for delivery
767 public function isPackageWaitingForDelivery () {
768 // Check whether the stacker is not empty
769 $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
772 return $isWaitingDelivery;
776 * Checks whether encoded (raw) data is pending
778 * @return $isPending Whether encoded data is pending
780 public function isEncodedDataPending () {
781 // Check whether the stacker is not empty
782 $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM)));
789 * Delivers an enqueued package to the stated destination. If a non-session
790 * id is provided, recipient resolver is being asked (and instanced once).
791 * This allows that a single package is being delivered to multiple targets
792 * without enqueueing it for every target. If no target is provided or it
793 * can't be determined a NoTargetException is being thrown.
796 * @throws NoTargetException If no target can't be determined
798 public function declareEnqueuedPackage () {
800 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
802 // Make sure this method isn't working if there is no package enqueued
803 if (!$this->isPackageEnqueued()) {
804 // This is not fatal but should be avoided
805 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
810 * Now there are for sure packages to deliver, so start with the first
813 $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
815 // Declare the raw package data for delivery
816 $this->declareRawPackageData($packageData);
819 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
823 * Delivers the next declared package. Only one package per time will be sent
824 * because this may take time and slows down the whole delivery
829 public function processDeclaredPackage () {
831 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
833 // Sanity check if we have packages declared
834 if (!$this->isPackageDeclared()) {
835 // This is not fatal but should be avoided
836 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
841 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
844 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
846 // Try to deliver the package
848 // And try to send it
849 $this->deliverRawPackageData($packageData);
851 // And remove it finally
852 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
853 } catch (InvalidStateException $e) {
854 // The state is not excepected (shall be 'connected')
855 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
857 // Mark the package with status failed
858 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
862 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
866 * Sends waiting packages out for delivery
870 public function sendWaitingPackage () {
872 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
874 // Sanity check if we have packages waiting for delivery
875 if (!$this->isPackageWaitingForDelivery()) {
876 // This is not fatal but should be avoided
877 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
882 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
885 // Now try to send it
886 $this->sendOutgoingRawPackageData($packageData);
888 // And remove it finally
889 $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING);
890 } catch (InvalidSocketException $e) {
891 // Output exception message
892 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
894 // Mark package as failed
895 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
899 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
903 * Sends out encoded data to a socket
907 public function sendEncodedData () {
909 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
911 // Make sure there is pending encoded data
912 assert($this->isEncodedDataPending());
914 // Pop current data from stack
915 $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
917 // Init in this round sent bytes
921 assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
924 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sending out ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes,rawBufferSize=' . $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] . ',diff=' . $encodedDataArray[self::RAW_DIFF_INDEX]);
925 if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) {
926 // Send all out (encodedData is smaller than or equal buffer size)
927 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX]))));
928 $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX]));
930 // Send buffer size out
931 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX])));
932 $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]);
935 // If there was an error, we don't continue here
936 if ($sentBytes === FALSE) {
937 // Handle the error with a faked recipientData array
938 $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0'));
941 throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
942 } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) {
943 // Nothing sent means we are done
944 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
947 // The difference between sent bytes and length of raw data should not go below zero
948 assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0);
950 // Add total sent bytes
951 $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
953 // Cut out the last unsent bytes
954 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...');
955 $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes);
957 // Calculate difference again
958 $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
961 if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) {
962 // Abort here, all sent!
963 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
968 // Push array back in stack
969 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
972 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
975 ///////////////////////////////////////////////////////////////////////////
976 // Receiving packages / raw data
977 ///////////////////////////////////////////////////////////////////////////
980 * Checks whether decoded raw data is pending
982 * @return $isPending Whether decoded raw data is pending
984 private function isRawDataPending () {
985 // Just return whether the stack is not empty
986 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
993 * Checks whether new raw package data has arrived at a socket
995 * @return $hasArrived Whether new raw package data has arrived for processing
997 public function isNewRawDataPending () {
998 // Visit the pool. This monitors the pool for incoming raw data.
999 $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
1001 // Check for new data arrival
1002 $hasArrived = $this->isRawDataPending();
1004 // Return the status
1009 * Handles the incoming decoded raw data. This method does not "convert" the
1010 * decoded data back into a package array, it just "handles" it and pushs it
1011 * on the next stack.
1015 public function handleIncomingDecodedData () {
1017 * This method should only be called if decoded raw data is pending,
1018 * so check it again.
1020 if (!$this->isRawDataPending()) {
1021 // This is not fatal but should be avoided
1022 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
1026 // Very noisy debug message:
1027 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
1029 // "Pop" the next entry (the same array again) from the stack
1030 $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
1032 // Make sure both array elements are there
1034 (is_array($decodedData)) &&
1035 (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1036 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1040 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
1041 * only want to handle unhandled packages here.
1043 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
1044 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
1046 // Remove the last chunk SEPARATOR (because there is no need for it)
1047 if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
1048 // It is there and should be removed
1049 $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
1052 // This package is "handled" and can be pushed on the next stack
1053 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes to stack ' . self::STACKER_NAME_DECODED_HANDLED . ' ...');
1054 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
1058 * Adds raw decoded data from the given handler instance to this receiver
1060 * @param $handlerInstance An instance of a Networkable class
1063 public function addRawDataToIncomingStack (Networkable $handlerInstance) {
1065 * Get the decoded data from the handler, this is an array with
1066 * 'raw_data' and 'error_code' as elements.
1068 $decodedData = $handlerInstance->getNextRawData();
1070 // Very noisy debug message:
1071 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
1073 // And push it on our stack
1074 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
1078 * Checks whether incoming decoded data is handled.
1080 * @return $isHandled Whether incoming decoded data is handled
1082 public function isIncomingRawDataHandled () {
1083 // Determine if the stack is not empty
1084 $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
1091 * Checks whether the assembler has pending data left
1093 * @return $isHandled Whether the assembler has pending data left
1095 public function ifAssemblerHasPendingDataLeft () {
1096 // Determine if the stack is not empty
1097 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
1104 * Checks whether the assembler has multiple packages pending
1106 * @return $isPending Whether the assembler has multiple packages pending
1108 public function ifMultipleMessagesPending () {
1109 // Determine if the stack is not empty
1110 $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
1117 * Handles the attached assemler's pending data queue to be finally
1118 * assembled to the raw package data back.
1122 public function handleAssemblerPendingData () {
1124 $this->getAssemblerInstance()->handlePendingData();
1128 * Handles multiple messages.
1132 public function handleMultipleMessages () {
1134 $this->getAssemblerInstance()->handleMultipleMessages();
1138 * Assembles incoming decoded data so it will become an abstract network
1139 * package again. The assembler does later do it's job by an other task,
1140 * not this one to keep best speed possible.
1144 public function assembleDecodedDataToPackage () {
1145 // Make sure the raw decoded package data is handled
1146 assert($this->isIncomingRawDataHandled());
1148 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
1149 $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
1151 // Assert on some elements
1153 (is_array($packageContent)) &&
1154 (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1155 (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1158 // Start assembling the raw package data array by chunking it
1159 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
1161 // Remove the package from 'handled_decoded' stack ...
1162 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
1164 // ... and push it on the 'chunked' stacker
1165 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes on stack ' . self::STACKER_NAME_DECODED_CHUNKED . ',packageContent=' . print_r($packageContent, TRUE));
1166 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
1170 * Accepts the visitor to process the visit "request"
1172 * @param $visitorInstance An instance of a Visitor class
1175 public function accept (Visitor $visitorInstance) {
1177 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
1179 // Visit the package
1180 $visitorInstance->visitNetworkPackage($this);
1182 // Then visit the assembler to handle multiple packages
1183 $this->getAssemblerInstance()->accept($visitorInstance);
1186 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
1194 public function clearAllStacks () {
1195 // Call the init method to force re-initialization
1196 $this->initStacks(TRUE);
1199 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
1203 * Removes the first failed outoging package from the stack to continue
1204 * with next one (it will never work until the issue is fixed by you).
1207 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
1208 * @todo This may be enchanced for outgoing packages?
1210 public function removeFirstFailedPackage () {
1211 // Get the package again
1212 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
1214 // Is the package status 'failed'?
1215 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
1217 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
1220 // Remove this entry
1221 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
1225 * "Decode" the package content into the same array when it was sent.
1227 * @param $rawPackageContent The raw package content to be "decoded"
1228 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
1230 public function decodeRawContent ($rawPackageContent) {
1231 // Use the separator '#' to "decode" it
1232 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1234 // Assert on count (should be always 3)
1235 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1237 // Generate the hash of comparing it
1238 if (!$this->isPackageHashValid($decodedArray)) {
1239 // Is not valid, so throw an exception here
1240 exit(__METHOD__ . ':INVALID HASH! UNDER CONSTRUCTION!' . chr(10));
1244 * Create 'decodedData' array with all assoziative array elements.
1246 $decodedData = array(
1247 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
1248 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1249 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1250 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
1251 self::PACKAGE_DATA_HASH => $decodedArray[self::INDEX_PACKAGE_HASH]
1255 return $decodedData;
1259 * Handles decoded data for this node by "decoding" the 'content' part of
1260 * it. Again this method uses explode() for the "decoding" process.
1262 * @param $decodedData An array with decoded raw package data
1264 * @throws InvalidDataChecksumException If the checksum doesn't match
1266 public function handleRawData (array $decodedData) {
1268 * "Decode" the package's content by a simple explode() call, for
1269 * details of the array elements, see comments for constant
1272 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1274 // Assert on array count for a very basic validation
1275 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1278 * Convert the indexed array into an associative array. This is much
1279 * better to remember than plain numbers, isn't it?
1281 $decodedContent = array(
1282 // Compressor's extension used to compress the data
1283 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1284 // Package data (aka "message") in BASE64-decoded form but still compressed
1285 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1286 // Tags as an indexed array for "tagging" the message
1287 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1288 // Checksum of the _decoded_ data
1289 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM],
1291 self::PACKAGE_CONTENT_SENDER => $decodedData[self::PACKAGE_DATA_SENDER],
1292 // Hash from decoded raw data
1293 self::PACKAGE_CONTENT_HASH => $decodedData[self::PACKAGE_DATA_HASH]
1296 // Is the checksum valid?
1297 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1298 // Is not the same, so throw an exception here
1299 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1303 * The checksum is the same, then it can be decompressed safely. The
1304 * original message is at this point fully decoded.
1306 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1308 // And push it on the next stack
1309 $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1313 * Checks whether a new message has arrived
1315 * @return $hasArrived Whether a new message has arrived for processing
1317 public function isNewMessageArrived () {
1318 // Determine if the stack is not empty
1319 $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1326 * Handles newly arrived messages
1329 * @todo Implement verification of all sent tags here?
1331 public function handleNewlyArrivedMessage () {
1332 // Get it from the stacker, it is the full array with the decoded message
1333 $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1335 // Now get a filter chain back from factory with given tags array
1336 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1339 * Process the message through all filters, note that all other
1340 * elements from $decodedContent are no longer needed.
1342 $chainInstance->processMessage($decodedContent, $this);
1346 * Checks whether a processed message is pending for "interpretation"
1348 * @return $isPending Whether a processed message is pending
1350 public function isProcessedMessagePending () {
1352 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1359 * Handle processed messages by "interpreting" the 'message_type' element
1363 public function handleProcessedMessage () {
1364 // Get it from the stacker, it is the full array with the processed message
1365 $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1367 // Add type for later easier handling
1368 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1371 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1373 // Create a handler instance from given message type
1374 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1376 // Handle message data
1377 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1381 * Feeds the hash and sender (as recipient for the 'sender' reward) to the
1382 * miner's queue, unless the message is not a "reward claim" message as this
1383 * leads to an endless loop. You may wish to run the miner to get some
1384 * reward ("HubCoins") for "mining" this hash.
1386 * @param $decodedDataArray Array with decoded message
1390 public function feedHashToMiner (array $decodedDataArray) {
1391 // Make sure the required elements are there
1392 assert(isset($decodedDataArray[self::PACKAGE_CONTENT_SENDER]));
1393 assert(isset($decodedDataArray[self::PACKAGE_CONTENT_HASH]));
1394 assert(isset($decodedDataArray[self::PACKAGE_CONTENT_TAGS]));
1396 // Resolve session id ('sender' is a session id) into node id
1397 $nodeId = HubTools::resolveNodeIdBySessionId($decodedDataArray[self::PACKAGE_CONTENT_SENDER]);
1399 // Is 'claim_reward' the message type?
1400 if (in_array('claim_reward', $decodedDataArray[self::PACKAGE_CONTENT_TAGS])) {
1402 * Then don't feed this message to the miner as this causes and
1403 * endless loop of mining.
1408 $this->partialStub('@TODO nodeId=' . $nodeId . ',decodedDataArray=' . print_r($decodedDataArray, TRUE));