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;
81 const INDEX_PACKAGE_PRIVATE_KEY_HASH = 5;
84 * Size of the decoded data array
86 const DECODED_DATA_ARRAY_SIZE = 6;
89 * Named array elements for decoded package content
91 const PACKAGE_CONTENT_EXTENSION = 'compressor';
92 const PACKAGE_CONTENT_MESSAGE = 'message';
93 const PACKAGE_CONTENT_TAGS = 'tags';
94 const PACKAGE_CONTENT_CHECKSUM = 'checksum';
95 const PACKAGE_CONTENT_SENDER = 'sender';
96 const PACKAGE_CONTENT_HASH = 'hash';
97 const PACKAGE_CONTENT_PRIVATE_KEY_HASH = 'pkhash';
100 * Named array elements for package data
102 const PACKAGE_DATA_SENDER = 'sender';
103 const PACKAGE_DATA_RECIPIENT = 'recipient';
104 const PACKAGE_DATA_CONTENT = 'content';
105 const PACKAGE_DATA_STATUS = 'status';
106 const PACKAGE_DATA_HASH = 'hash';
107 const PACKAGE_DATA_PRIVATE_KEY_HASH = 'pkhash';
112 const PACKAGE_STATUS_NEW = 'new';
113 const PACKAGE_STATUS_FAILED = 'failed';
114 const PACKAGE_STATUS_DECODED = 'decoded';
115 const PACKAGE_STATUS_FAKED = 'faked';
118 * Constants for message data array
120 const MESSAGE_ARRAY_DATA = 'message_data';
121 const MESSAGE_ARRAY_TYPE = 'message_type';
124 * Generic answer status field
130 const PACKAGE_TAGS_SEPARATOR = ';';
133 * Raw package data separator
135 const PACKAGE_DATA_SEPARATOR = '#';
138 * Separator for more than one recipient
140 const PACKAGE_RECIPIENT_SEPARATOR = ':';
143 * Network target (alias): 'upper nodes'
145 const NETWORK_TARGET_UPPER = 'upper';
148 * Network target (alias): 'self'
150 const NETWORK_TARGET_SELF = 'self';
153 * Network target (alias): 'dht'
155 const NETWORK_TARGET_DHT = 'dht';
158 * TCP package size in bytes
160 const TCP_PACKAGE_SIZE = 512;
162 /**************************************************************************
163 * Stacker for out-going packages *
164 **************************************************************************/
167 * Stacker name for "undeclared" packages
169 const STACKER_NAME_UNDECLARED = 'package_undeclared';
172 * Stacker name for "declared" packages (which are ready to send out)
174 const STACKER_NAME_DECLARED = 'package_declared';
177 * Stacker name for "out-going" packages
179 const STACKER_NAME_OUTGOING = 'package_outgoing';
181 /**************************************************************************
182 * Stacker for incoming packages *
183 **************************************************************************/
186 * Stacker name for "incoming" decoded raw data
188 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
191 * Stacker name for handled decoded raw data
193 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
196 * Stacker name for "chunked" decoded raw data
198 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
200 /**************************************************************************
201 * Stacker for incoming messages *
202 **************************************************************************/
205 * Stacker name for new messages
207 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
210 * Stacker name for processed messages
212 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
214 /**************************************************************************
215 * Stacker for raw data handling *
216 **************************************************************************/
219 * Stacker for outgoing data stream
221 const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
224 * Array index for final hash
226 const RAW_FINAL_HASH_INDEX = 'hash';
229 * Array index for encoded data
231 const RAW_ENCODED_DATA_INDEX = 'data';
234 * Array index for sent bytes
236 const RAW_SENT_BYTES_INDEX = 'sent';
239 * Array index for socket resource
241 const RAW_SOCKET_INDEX = 'socket';
244 * Array index for buffer size
246 const RAW_BUFFER_SIZE_INDEX = 'buffer';
249 * Array index for diff between buffer and sent bytes
251 const RAW_DIFF_INDEX = 'diff';
253 /**************************************************************************
255 **************************************************************************/
256 const PROTOCOL_TCP = 'TCP';
257 const PROTOCOL_UDP = 'UDP';
260 * Protected constructor
264 protected function __construct () {
265 // Call parent constructor
266 parent::__construct(__CLASS__);
270 * Creates an instance of this class
272 * @param $compressorInstance A Compressor instance for compressing the content
273 * @return $packageInstance An instance of a Deliverable class
275 public static final function createNetworkPackage (Compressor $compressorInstance) {
277 $packageInstance = new NetworkPackage();
279 // Now set the compressor instance
280 $packageInstance->setCompressorInstance($compressorInstance);
283 * We need to initialize a stack here for our packages even for those
284 * which have no recipient address and stamp... ;-) This stacker will
285 * also be used for incoming raw data to handle it.
287 $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
289 // At last, set it in this class
290 $packageInstance->setStackInstance($stackInstance);
293 $packageInstance->initStacks();
295 // Get a visitor instance for speeding up things and set it
296 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class');
297 $packageInstance->setVisitorInstance($visitorInstance);
299 // Get crypto instance and set it, too
300 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
301 $packageInstance->setCryptoInstance($cryptoInstance);
303 // Get a singleton package assembler instance from factory and set it here, too
304 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
305 $packageInstance->setAssemblerInstance($assemblerInstance);
308 $nodeInstance = NodeObjectFactory::createNodeInstance();
310 // Get pool instance from node
311 $poolInstance = $nodeInstance->getListenerPoolInstance();
314 $packageInstance->setListenerPoolInstance($poolInstance);
316 // Return the prepared instance
317 return $packageInstance;
321 * Initialize all stackers
323 * @param $forceReInit Whether to force reinitialization of all stacks
326 protected function initStacks ($forceReInit = FALSE) {
328 $this->getStackInstance()->initStacks(array(
329 self::STACKER_NAME_UNDECLARED,
330 self::STACKER_NAME_DECLARED,
331 self::STACKER_NAME_OUTGOING,
332 self::STACKER_NAME_DECODED_INCOMING,
333 self::STACKER_NAME_DECODED_HANDLED,
334 self::STACKER_NAME_DECODED_CHUNKED,
335 self::STACKER_NAME_NEW_MESSAGE,
336 self::STACKER_NAME_PROCESSED_MESSAGE,
337 self::STACKER_NAME_OUTGOING_STREAM
342 * Determines private key hash from given session id
344 * @param $decodedData Array with decoded data
345 * @return $hash Private key's hash
347 private function determineSenderPrivateKeyHash (array $decodedData) {
349 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
351 // Ask DHT for session id
352 $senderData = $dhtInstance->findNodeLocalBySessionId($decodedData[self::PACKAGE_CONTENT_SENDER]);
354 // Is an entry found?
355 if (count($senderData) > 0) {
356 // Make sure the element 'private_key_hash' is there
357 /* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderData=' . print_r($senderData, TRUE));
358 assert(isset($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH]));
361 return $senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH];
364 // Make sure the requested element is there
365 //* DEBUG-DIE */ die('decodedData=' . print_r($decodedData, TRUE));
366 assert(isset($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH]));
368 // There is no DHT entry so, accept the hash from decoded data
369 return $decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH];
373 * "Getter" for hash from given content
375 * @param $content Raw package content
376 * @return $hash Hash for given package content
378 private function getHashFromContent ($content) {
380 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
383 // @TODO md5() is very weak, but it needs to be fast
386 self::PACKAGE_CHECKSUM_SEPARATOR .
387 $this->getSessionId() .
388 self::PACKAGE_CHECKSUM_SEPARATOR .
389 $this->getCompressorInstance()->getCompressorExtension()
393 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
400 * Checks whether the checksum (sometimes called "hash") is the same
402 * @param $decodedContent Package raw content
403 * @param $decodedData Whole raw package data array
404 * @return $isChecksumValid Whether the checksum is the same
406 private function isChecksumValid (array $decodedContent, array $decodedData) {
408 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
411 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
414 return $isChecksumValid;
418 * Change the package with given status in given stack
420 * @param $packageData Raw package data in an array
421 * @param $stackerName Name of the stacker
422 * @param $newStatus New status to set
425 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
426 // Skip this for empty stacks
427 if ($this->getStackInstance()->isStackEmpty($stackerName)) {
428 // This avoids an exception after all packages has failed
432 // Pop the entry (it should be it)
433 $nextData = $this->getStackInstance()->popNamed($stackerName);
435 // Compare both hashes
436 assert($nextData[self::PACKAGE_DATA_HASH] == $packageData[self::PACKAGE_DATA_HASH]);
438 // Temporary set the new status
439 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
442 $this->getStackInstance()->pushNamed($stackerName, $packageData);
446 * "Getter" for hash from given content and sender's session id
448 * @param $decodedContent Raw package content
449 * @param $sessionId Session id of the sender
450 * @return $hash Hash for given package content
452 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
454 //* 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]);
457 // @TODO md5() is very weak, but it needs to be fast
459 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
460 self::PACKAGE_CHECKSUM_SEPARATOR .
462 self::PACKAGE_CHECKSUM_SEPARATOR .
463 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
470 ///////////////////////////////////////////////////////////////////////////
471 // Delivering packages / raw data
472 ///////////////////////////////////////////////////////////////////////////
475 * Declares the given raw package data by discovering recipients
477 * @param $packageData Raw package data in an array
480 private function declareRawPackageData (array $packageData) {
481 // Make sure the required field is there
482 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
485 * We need to disover every recipient, just in case we have a
486 * multi-recipient entry like 'upper' is. 'all' may be a not so good
487 * target because it causes an overload on the network and may be
488 * abused for attacking the network with large packages.
490 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
492 // Discover all recipients, this may throw an exception
493 $discoveryInstance->discoverRecipients($packageData);
495 // Now get an iterator
496 $iteratorInstance = $discoveryInstance->getIterator();
498 // Make sure the iterator instance is valid
499 assert($iteratorInstance instanceof Iterator);
501 // Rewind back to the beginning
502 $iteratorInstance->rewind();
504 // ... and begin iteration
505 while ($iteratorInstance->valid()) {
507 $currentRecipient = $iteratorInstance->current();
510 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
513 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
515 // Push the declared package to the next stack.
516 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
519 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
521 // Skip to next entry
522 $iteratorInstance->next();
526 * The recipient list can be cleaned up here because the package which
527 * shall be delivered has already been added for all entries from the
530 $discoveryInstance->clearRecipients();
534 * Delivers raw package data. In short, this will discover the raw socket
535 * resource through a discovery class (which will analyse the receipient of
536 * the package), register the socket with the connection (handler/helper?)
537 * instance and finally push the raw data on our outgoing queue.
539 * @param $packageData Raw package data in an array
542 private function deliverRawPackageData (array $packageData) {
544 * This package may become big, depending on the shared object size or
545 * delivered message size which shouldn't be so long (to save
546 * bandwidth). Because of the nature of the used protocol (TCP) we need
547 * to split it up into smaller pieces to fit it into a TCP frame.
549 * So first we need (again) a discovery class but now a protocol
550 * discovery to choose the right socket resource. The discovery class
551 * should take a look at the raw package data itself and then decide
552 * which (configurable!) protocol should be used for that type of
555 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
557 // Now discover the right protocol
558 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
561 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
564 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
565 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
567 // The socket needs to be put in a special registry that can handle such data
568 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
570 // Get the connection helper from registry
571 $helperInstance = Registry::getRegistry()->getInstance('connection');
573 // And make sure it is valid
574 assert($helperInstance instanceof ConnectionHelper);
576 // Get connection info class
577 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper');
579 // Will the info instance with connection helper data
580 $infoInstance->fillWithConnectionHelperInformation($helperInstance);
583 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($infoInstance, $socketResource))) {
585 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
588 $registryInstance->registerSocket($infoInstance, $socketResource, $packageData);
589 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
590 // Is not connected, then we cannot send
591 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
593 // Shutdown the socket
594 $this->shutdownSocket($socketResource);
598 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
600 // Make sure the connection is up
601 $helperInstance->getStateInstance()->validatePeerStateConnected();
604 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
606 // Enqueue it again on the out-going queue, the connection is up and working at this point
607 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
610 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
614 * Sends waiting packages
616 * @param $packageData Raw package data
619 private function sendOutgoingRawPackageData (array $packageData) {
623 // Get the right connection instance
624 $infoInstance = SocketRegistryFactory::createSocketRegistryInstance()->getInfoInstanceFromPackageData($packageData);
626 // Test helper instance
627 assert($infoInstance instanceof ShareableInfo);
629 // Get helper instance
630 $helperInstance = $infoInstance->getHelperInstance();
632 // Some sanity-checks on the object
633 //* DEBUG-DIE: */ die('[' . __METHOD__ . ':' . __LINE__ . ']: p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE));
634 assert($helperInstance instanceof ConnectionHelper);
635 assert($infoInstance->getProtocolName() == $helperInstance->getProtocolName());
637 // Is this connection still alive?
638 if ($helperInstance->isShuttedDown()) {
639 // This connection is shutting down
640 // @TODO We may want to do somthing more here?
644 // Sent out package data
645 $helperInstance->sendRawPackageData($packageData);
649 * Generates a secure hash for given raw package content and sender id
651 * @param $content Raw package data
652 * @param $senderId Sender id to generate a hash for
653 * @return $hash Hash as hex-encoded string
655 private function generatePackageHash ($content, $senderId) {
658 self::PACKAGE_CONTENT_SENDER => $senderId,
659 self::PACKAGE_CONTENT_MESSAGE => $content,
660 self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => ''
663 // Hash content and sender id together, use scrypt
664 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $senderId . ',content()=' . strlen($content));
665 $hash = Scrypt::hashScrypt($senderId . ':' . $content . ':' . $this->determineSenderPrivateKeyHash($data));
672 * Checks whether the hash of given package data is 'valid', here that
673 * means it is the same or not.
675 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
676 * @return $isHashValid Whether the hash is valid
677 * @todo Unfinished area, hashes are currently NOT fully supported
679 private function isPackageHashValid (array $decodedArray) {
681 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $decodedArray[self::PACKAGE_CONTENT_SENDER] . ',message()=' . strlen($decodedArray[self::PACKAGE_CONTENT_MESSAGE]));
682 //* DEBUG-DIE: */ die(__METHOD__ . ': decodedArray=' . print_r($decodedArray, TRUE));
683 $isHashValid = Scrypt::checkScrypt($decodedArray[self::PACKAGE_CONTENT_SENDER] . ':' . $decodedArray[self::PACKAGE_CONTENT_MESSAGE] . ':' . $this->determineSenderPrivateKeyHash($decodedArray), $decodedArray[self::PACKAGE_CONTENT_HASH]);
686 //* DEBUG-DIE: */ die(__METHOD__ . ': isHashValid=' . intval($isHashValid) . ',decodedArray=' . print_r($decodedArray, TRUE));
691 * "Enqueues" raw content into this delivery class by reading the raw content
692 * from given helper's template instance and pushing it on the 'undeclared'
695 * @param $helperInstance An instance of a HubHelper class
698 public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
700 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
702 // Get the raw content ...
703 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
704 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
706 // ... and compress it
707 $compressed = $this->getCompressorInstance()->compressStream($content);
709 // Add magic in front of it and hash behind it, including BASE64 encoding
710 $packageContent = sprintf(self::PACKAGE_MASK,
711 // 1.) Compressor's extension
712 $this->getCompressorInstance()->getCompressorExtension(),
714 self::PACKAGE_MASK_SEPARATOR,
715 // 2.) Compressed raw package content, encoded with BASE64
716 base64_encode($compressed),
718 self::PACKAGE_MASK_SEPARATOR,
720 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
722 self::PACKAGE_MASK_SEPARATOR,
724 $this->getHashFromContent($compressed)
728 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
730 // Now prepare the temporary array and push it on the 'undeclared' stack
731 $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
732 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
733 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
734 self::PACKAGE_DATA_CONTENT => $packageContent,
735 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
736 self::PACKAGE_DATA_HASH => $this->generatePackageHash($content, $this->getSessionId()),
737 self::PACKAGE_DATA_PRIVATE_KEY_HASH => $this->getPrivateKeyHash(),
741 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
745 * Checks whether a package has been enqueued for delivery.
747 * @return $isEnqueued Whether a package is enqueued
749 public function isPackageEnqueued () {
750 // Check whether the stacker is not empty
751 $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
758 * Checks whether a package has been declared
760 * @return $isDeclared Whether a package is declared
762 public function isPackageDeclared () {
763 // Check whether the stacker is not empty
764 $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
771 * Checks whether a package should be sent out
773 * @return $isWaitingDelivery Whether a package is waiting for delivery
775 public function isPackageWaitingForDelivery () {
776 // Check whether the stacker is not empty
777 $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
780 return $isWaitingDelivery;
784 * Checks whether encoded (raw) data is pending
786 * @return $isPending Whether encoded data is pending
788 public function isEncodedDataPending () {
789 // Check whether the stacker is not empty
790 $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM)));
797 * Delivers an enqueued package to the stated destination. If a non-session
798 * id is provided, recipient resolver is being asked (and instanced once).
799 * This allows that a single package is being delivered to multiple targets
800 * without enqueueing it for every target. If no target is provided or it
801 * can't be determined a NoTargetException is being thrown.
804 * @throws NoTargetException If no target can't be determined
806 public function declareEnqueuedPackage () {
808 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
810 // Make sure this method isn't working if there is no package enqueued
811 if (!$this->isPackageEnqueued()) {
812 // This is not fatal but should be avoided
813 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
818 * Now there are for sure packages to deliver, so start with the first
821 $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
823 // Declare the raw package data for delivery
824 $this->declareRawPackageData($packageData);
827 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
831 * Delivers the next declared package. Only one package per time will be sent
832 * because this may take time and slows down the whole delivery
837 public function processDeclaredPackage () {
839 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
841 // Sanity check if we have packages declared
842 if (!$this->isPackageDeclared()) {
843 // This is not fatal but should be avoided
844 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
849 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
852 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
854 // Try to deliver the package
856 // And try to send it
857 $this->deliverRawPackageData($packageData);
859 // And remove it finally
860 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
861 } catch (InvalidStateException $e) {
862 // The state is not excepected (shall be 'connected')
863 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
865 // Mark the package with status failed
866 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
870 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
874 * Sends waiting packages out for delivery
878 public function sendWaitingPackage () {
880 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
882 // Sanity check if we have packages waiting for delivery
883 if (!$this->isPackageWaitingForDelivery()) {
884 // This is not fatal but should be avoided
885 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
890 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
893 // Now try to send it
894 $this->sendOutgoingRawPackageData($packageData);
896 // And remove it finally
897 $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING);
898 } catch (InvalidSocketException $e) {
899 // Output exception message
900 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
902 // Mark package as failed
903 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
907 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
911 * Sends out encoded data to a socket
915 public function sendEncodedData () {
917 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
919 // Make sure there is pending encoded data
920 assert($this->isEncodedDataPending());
922 // Pop current data from stack
923 $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
925 // Init in this round sent bytes
929 assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
932 //* 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]);
933 if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) {
934 // Send all out (encodedData is smaller than or equal buffer size)
935 //* 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]))));
936 $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]));
938 // Send buffer size out
939 //* 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])));
940 $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]);
943 // If there was an error, we don't continue here
944 if ($sentBytes === FALSE) {
945 // Handle the error with a faked recipientData array
946 $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0'));
949 throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
950 } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) {
951 // Nothing sent means we are done
952 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
955 // The difference between sent bytes and length of raw data should not go below zero
956 assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0);
958 // Add total sent bytes
959 $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
961 // Cut out the last unsent bytes
962 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...');
963 $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes);
965 // Calculate difference again
966 $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
969 if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) {
970 // Abort here, all sent!
971 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
976 // Push array back in stack
977 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
980 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
983 ///////////////////////////////////////////////////////////////////////////
984 // Receiving packages / raw data
985 ///////////////////////////////////////////////////////////////////////////
988 * Checks whether decoded raw data is pending
990 * @return $isPending Whether decoded raw data is pending
992 private function isRawDataPending () {
993 // Just return whether the stack is not empty
994 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
1001 * Checks whether new raw package data has arrived at a socket
1003 * @return $hasArrived Whether new raw package data has arrived for processing
1005 public function isNewRawDataPending () {
1006 // Visit the pool. This monitors the pool for incoming raw data.
1007 $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
1009 // Check for new data arrival
1010 $hasArrived = $this->isRawDataPending();
1012 // Return the status
1017 * Handles the incoming decoded raw data. This method does not "convert" the
1018 * decoded data back into a package array, it just "handles" it and pushs it
1019 * on the next stack.
1023 public function handleIncomingDecodedData () {
1025 * This method should only be called if decoded raw data is pending,
1026 * so check it again.
1028 if (!$this->isRawDataPending()) {
1029 // This is not fatal but should be avoided
1030 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
1034 // Very noisy debug message:
1035 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
1037 // "Pop" the next entry (the same array again) from the stack
1038 $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
1040 // Make sure both array elements are there
1042 (is_array($decodedData)) &&
1043 (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1044 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1048 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
1049 * only want to handle unhandled packages here.
1051 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
1052 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
1054 // Remove the last chunk SEPARATOR (because there is no need for it)
1055 if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
1056 // It is there and should be removed
1057 $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
1060 // This package is "handled" and can be pushed on the next stack
1061 //* 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 . ' ...');
1062 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
1066 * Adds raw decoded data from the given handler instance to this receiver
1068 * @param $handlerInstance An instance of a Networkable class
1071 public function addRawDataToIncomingStack (Networkable $handlerInstance) {
1073 * Get the decoded data from the handler, this is an array with
1074 * 'raw_data' and 'error_code' as elements.
1076 $decodedData = $handlerInstance->getNextRawData();
1078 // Very noisy debug message:
1079 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
1081 // And push it on our stack
1082 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
1086 * Checks whether incoming decoded data is handled.
1088 * @return $isHandled Whether incoming decoded data is handled
1090 public function isIncomingRawDataHandled () {
1091 // Determine if the stack is not empty
1092 $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
1099 * Checks whether the assembler has pending data left
1101 * @return $isHandled Whether the assembler has pending data left
1103 public function ifAssemblerHasPendingDataLeft () {
1104 // Determine if the stack is not empty
1105 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
1112 * Checks whether the assembler has multiple packages pending
1114 * @return $isPending Whether the assembler has multiple packages pending
1116 public function ifMultipleMessagesPending () {
1117 // Determine if the stack is not empty
1118 $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
1125 * Handles the attached assemler's pending data queue to be finally
1126 * assembled to the raw package data back.
1130 public function handleAssemblerPendingData () {
1132 $this->getAssemblerInstance()->handlePendingData();
1136 * Handles multiple messages.
1140 public function handleMultipleMessages () {
1142 $this->getAssemblerInstance()->handleMultipleMessages();
1146 * Assembles incoming decoded data so it will become an abstract network
1147 * package again. The assembler does later do it's job by an other task,
1148 * not this one to keep best speed possible.
1152 public function assembleDecodedDataToPackage () {
1153 // Make sure the raw decoded package data is handled
1154 assert($this->isIncomingRawDataHandled());
1156 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
1157 $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
1159 // Assert on some elements
1161 (is_array($packageContent)) &&
1162 (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1163 (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1166 // Start assembling the raw package data array by chunking it
1167 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
1169 // Remove the package from 'handled_decoded' stack ...
1170 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
1172 // ... and push it on the 'chunked' stacker
1173 //* 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));
1174 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
1178 * Accepts the visitor to process the visit "request"
1180 * @param $visitorInstance An instance of a Visitor class
1183 public function accept (Visitor $visitorInstance) {
1185 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
1187 // Visit the package
1188 $visitorInstance->visitNetworkPackage($this);
1190 // Then visit the assembler to handle multiple packages
1191 $this->getAssemblerInstance()->accept($visitorInstance);
1194 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
1202 public function clearAllStacks () {
1203 // Call the init method to force re-initialization
1204 $this->initStacks(TRUE);
1207 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
1211 * Removes the first failed outoging package from the stack to continue
1212 * with next one (it will never work until the issue is fixed by you).
1215 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
1216 * @todo This may be enchanced for outgoing packages?
1218 public function removeFirstFailedPackage () {
1219 // Get the package again
1220 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
1222 // Is the package status 'failed'?
1223 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
1225 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
1228 // Remove this entry
1229 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
1233 * "Decode" the package content into the same array when it was sent.
1235 * @param $rawPackageContent The raw package content to be "decoded"
1236 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
1238 public function decodeRawContent ($rawPackageContent) {
1239 // Use the separator '#' to "decode" it
1240 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1242 // Assert on count (should be always 3)
1243 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1246 * Create 'decodedData' array with all assoziative array elements.
1248 $decodedData = array(
1249 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
1250 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1251 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1252 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
1253 self::PACKAGE_DATA_HASH => $decodedArray[self::INDEX_PACKAGE_HASH],
1254 self::PACKAGE_DATA_PRIVATE_KEY_HASH => $decodedArray[self::INDEX_PACKAGE_PRIVATE_KEY_HASH]
1258 return $decodedData;
1262 * Handles decoded data for this node by "decoding" the 'content' part of
1263 * it. Again this method uses explode() for the "decoding" process.
1265 * @param $decodedData An array with decoded raw package data
1267 * @throws InvalidDataChecksumException If the checksum doesn't match
1269 public function handleRawData (array $decodedData) {
1271 * "Decode" the package's content by a simple explode() call, for
1272 * details of the array elements, see comments for constant
1275 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1277 // Assert on array count for a very basic validation
1278 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1281 * Convert the indexed array into an associative array. This is much
1282 * better to remember than plain numbers, isn't it?
1284 $decodedContent = array(
1285 // Compressor's extension used to compress the data
1286 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1287 // Package data (aka "message") in BASE64-decoded form but still compressed
1288 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1289 // Tags as an indexed array for "tagging" the message
1290 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1291 // Checksum of the _decoded_ data
1292 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM],
1294 self::PACKAGE_CONTENT_SENDER => $decodedData[self::PACKAGE_DATA_SENDER],
1295 // Hash from decoded raw data
1296 self::PACKAGE_CONTENT_HASH => $decodedData[self::PACKAGE_DATA_HASH],
1297 // Hash of private key
1298 self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => $decodedData[self::PACKAGE_DATA_PRIVATE_KEY_HASH]
1301 // Is the checksum valid?
1302 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1303 // Is not the same, so throw an exception here
1304 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1308 * The checksum is the same, then it can be decompressed safely. The
1309 * original message is at this point fully decoded.
1311 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1313 // And push it on the next stack
1314 $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1318 * Checks whether a new message has arrived
1320 * @return $hasArrived Whether a new message has arrived for processing
1322 public function isNewMessageArrived () {
1323 // Determine if the stack is not empty
1324 $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1331 * Handles newly arrived messages
1334 * @todo Implement verification of all sent tags here?
1336 public function handleNewlyArrivedMessage () {
1337 // Get it from the stacker, it is the full array with the decoded message
1338 $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1340 // Generate the hash of comparing it
1341 if (!$this->isPackageHashValid($decodedContent)) {
1342 // Is not valid, so throw an exception here
1343 exit(__METHOD__ . ':INVALID HASH! UNDER CONSTRUCTION!' . chr(10));
1346 // Now get a filter chain back from factory with given tags array
1347 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1350 * Process the message through all filters, note that all other
1351 * elements from $decodedContent are no longer needed.
1353 $chainInstance->processMessage($decodedContent, $this);
1357 * Checks whether a processed message is pending for "interpretation"
1359 * @return $isPending Whether a processed message is pending
1361 public function isProcessedMessagePending () {
1363 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1370 * Handle processed messages by "interpreting" the 'message_type' element
1374 public function handleProcessedMessage () {
1375 // Get it from the stacker, it is the full array with the processed message
1376 $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1378 // Add type for later easier handling
1379 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1382 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1384 // Create a handler instance from given message type
1385 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1387 // Handle message data
1388 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1392 * Feeds the hash and sender (as recipient for the 'sender' reward) to the
1393 * miner's queue, unless the message is not a "reward claim" message as this
1394 * leads to an endless loop. You may wish to run the miner to get some
1395 * reward ("HubCoins") for "mining" this hash.
1397 * @param $decodedDataArray Array with decoded message
1401 public function feedHashToMiner (array $decodedDataArray) {
1402 // Make sure the required elements are there
1403 assert(isset($decodedDataArray[self::PACKAGE_CONTENT_SENDER]));
1404 assert(isset($decodedDataArray[self::PACKAGE_CONTENT_HASH]));
1405 assert(isset($decodedDataArray[self::PACKAGE_CONTENT_TAGS]));
1407 // Resolve session id ('sender' is a session id) into node id
1408 $nodeId = HubTools::resolveNodeIdBySessionId($decodedDataArray[self::PACKAGE_CONTENT_SENDER]);
1410 // Is 'claim_reward' the message type?
1411 if (in_array('claim_reward', $decodedDataArray[self::PACKAGE_CONTENT_TAGS])) {
1413 * Then don't feed this message to the miner as this causes and
1414 * endless loop of mining.
1419 $this->partialStub('@TODO nodeId=' . $nodeId . ',decodedDataArray=' . print_r($decodedDataArray, TRUE));