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';
122 const MESSAGE_ARRAY_SENDER = 'message_sender';
123 const MESSAGE_ARRAY_HASH = 'message_hash';
124 const MESSAGE_ARRAY_TAGS = 'message_tags';
127 * Generic answer status field
133 const PACKAGE_TAGS_SEPARATOR = ';';
136 * Raw package data separator
138 const PACKAGE_DATA_SEPARATOR = '#';
141 * Separator for more than one recipient
143 const PACKAGE_RECIPIENT_SEPARATOR = ':';
146 * Network target (alias): 'upper nodes'
148 const NETWORK_TARGET_UPPER = 'upper';
151 * Network target (alias): 'self'
153 const NETWORK_TARGET_SELF = 'self';
156 * Network target (alias): 'dht'
158 const NETWORK_TARGET_DHT = 'dht';
161 * TCP package size in bytes
163 const TCP_PACKAGE_SIZE = 512;
165 /**************************************************************************
166 * Stacker for out-going packages *
167 **************************************************************************/
170 * Stacker name for "undeclared" packages
172 const STACKER_NAME_UNDECLARED = 'package_undeclared';
175 * Stacker name for "declared" packages (which are ready to send out)
177 const STACKER_NAME_DECLARED = 'package_declared';
180 * Stacker name for "out-going" packages
182 const STACKER_NAME_OUTGOING = 'package_outgoing';
184 /**************************************************************************
185 * Stacker for incoming packages *
186 **************************************************************************/
189 * Stacker name for "incoming" decoded raw data
191 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
194 * Stacker name for handled decoded raw data
196 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
199 * Stacker name for "chunked" decoded raw data
201 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
203 /**************************************************************************
204 * Stacker for incoming messages *
205 **************************************************************************/
208 * Stacker name for new messages
210 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
213 * Stacker name for processed messages
215 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
217 /**************************************************************************
218 * Stacker for raw data handling *
219 **************************************************************************/
222 * Stacker for outgoing data stream
224 const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
227 * Array index for final hash
229 const RAW_FINAL_HASH_INDEX = 'hash';
232 * Array index for encoded data
234 const RAW_ENCODED_DATA_INDEX = 'data';
237 * Array index for sent bytes
239 const RAW_SENT_BYTES_INDEX = 'sent';
242 * Array index for socket resource
244 const RAW_SOCKET_INDEX = 'socket';
247 * Array index for buffer size
249 const RAW_BUFFER_SIZE_INDEX = 'buffer';
252 * Array index for diff between buffer and sent bytes
254 const RAW_DIFF_INDEX = 'diff';
256 /**************************************************************************
258 **************************************************************************/
259 const PROTOCOL_TCP = 'TCP';
260 const PROTOCOL_UDP = 'UDP';
263 * Protected constructor
267 protected function __construct () {
268 // Call parent constructor
269 parent::__construct(__CLASS__);
273 * Creates an instance of this class
275 * @param $compressorInstance A Compressor instance for compressing the content
276 * @return $packageInstance An instance of a Deliverable class
278 public static final function createNetworkPackage (Compressor $compressorInstance) {
280 $packageInstance = new NetworkPackage();
282 // Now set the compressor instance
283 $packageInstance->setCompressorInstance($compressorInstance);
286 * We need to initialize a stack here for our packages even for those
287 * which have no recipient address and stamp... ;-) This stacker will
288 * also be used for incoming raw data to handle it.
290 $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
292 // At last, set it in this class
293 $packageInstance->setStackInstance($stackInstance);
296 $packageInstance->initStacks();
298 // Get a visitor instance for speeding up things and set it
299 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class');
300 $packageInstance->setVisitorInstance($visitorInstance);
302 // Get crypto instance and set it, too
303 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
304 $packageInstance->setCryptoInstance($cryptoInstance);
306 // Get a singleton package assembler instance from factory and set it here, too
307 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
308 $packageInstance->setAssemblerInstance($assemblerInstance);
311 $nodeInstance = NodeObjectFactory::createNodeInstance();
313 // Get pool instance from node
314 $poolInstance = $nodeInstance->getListenerPoolInstance();
317 $packageInstance->setListenerPoolInstance($poolInstance);
319 // Return the prepared instance
320 return $packageInstance;
324 * Initialize all stackers
326 * @param $forceReInit Whether to force reinitialization of all stacks
329 protected function initStacks ($forceReInit = FALSE) {
331 $this->getStackInstance()->initStacks(array(
332 self::STACKER_NAME_UNDECLARED,
333 self::STACKER_NAME_DECLARED,
334 self::STACKER_NAME_OUTGOING,
335 self::STACKER_NAME_DECODED_INCOMING,
336 self::STACKER_NAME_DECODED_HANDLED,
337 self::STACKER_NAME_DECODED_CHUNKED,
338 self::STACKER_NAME_NEW_MESSAGE,
339 self::STACKER_NAME_PROCESSED_MESSAGE,
340 self::STACKER_NAME_OUTGOING_STREAM
345 * Determines private key hash from given session id
347 * @param $decodedData Array with decoded data
348 * @return $hash Private key's hash
350 private function determineSenderPrivateKeyHash (array $decodedData) {
352 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
354 // Ask DHT for session id
355 $senderData = $dhtInstance->findNodeLocalBySessionId($decodedData[self::PACKAGE_CONTENT_SENDER]);
357 // Is an entry found?
358 if (count($senderData) > 0) {
359 // Make sure the element 'private_key_hash' is there
360 /* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderData=' . print_r($senderData, TRUE));
361 assert(isset($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH]));
364 return $senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH];
367 // Make sure the requested element is there
368 //* DEBUG-DIE */ die('decodedData=' . print_r($decodedData, TRUE));
369 assert(isset($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH]));
371 // There is no DHT entry so, accept the hash from decoded data
372 return $decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH];
376 * "Getter" for hash from given content
378 * @param $content Raw package content
379 * @return $hash Hash for given package content
381 private function getHashFromContent ($content) {
383 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
386 // @TODO md5() is very weak, but it needs to be fast
389 self::PACKAGE_CHECKSUM_SEPARATOR .
390 $this->getSessionId() .
391 self::PACKAGE_CHECKSUM_SEPARATOR .
392 $this->getCompressorInstance()->getCompressorExtension()
396 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
403 * Checks whether the checksum (sometimes called "hash") is the same
405 * @param $decodedContent Package raw content
406 * @param $decodedData Whole raw package data array
407 * @return $isChecksumValid Whether the checksum is the same
409 private function isChecksumValid (array $decodedContent, array $decodedData) {
411 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
414 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
417 return $isChecksumValid;
421 * Change the package with given status in given stack
423 * @param $packageData Raw package data in an array
424 * @param $stackerName Name of the stacker
425 * @param $newStatus New status to set
428 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
429 // Skip this for empty stacks
430 if ($this->getStackInstance()->isStackEmpty($stackerName)) {
431 // This avoids an exception after all packages has failed
435 // Pop the entry (it should be it)
436 $nextData = $this->getStackInstance()->popNamed($stackerName);
438 // Compare both hashes
439 assert($nextData[self::PACKAGE_DATA_HASH] == $packageData[self::PACKAGE_DATA_HASH]);
441 // Temporary set the new status
442 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
445 $this->getStackInstance()->pushNamed($stackerName, $packageData);
449 * "Getter" for hash from given content and sender's session id
451 * @param $decodedContent Raw package content
452 * @param $sessionId Session id of the sender
453 * @return $hash Hash for given package content
455 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
457 //* 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]);
460 // @TODO md5() is very weak, but it needs to be fast
462 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
463 self::PACKAGE_CHECKSUM_SEPARATOR .
465 self::PACKAGE_CHECKSUM_SEPARATOR .
466 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
473 ///////////////////////////////////////////////////////////////////////////
474 // Delivering packages / raw data
475 ///////////////////////////////////////////////////////////////////////////
478 * Declares the given raw package data by discovering recipients
480 * @param $packageData Raw package data in an array
483 private function declareRawPackageData (array $packageData) {
484 // Make sure the required field is there
485 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
488 * We need to disover every recipient, just in case we have a
489 * multi-recipient entry like 'upper' is. 'all' may be a not so good
490 * target because it causes an overload on the network and may be
491 * abused for attacking the network with large packages.
493 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
495 // Discover all recipients, this may throw an exception
496 $discoveryInstance->discoverRecipients($packageData);
498 // Now get an iterator
499 $iteratorInstance = $discoveryInstance->getIterator();
501 // Make sure the iterator instance is valid
502 assert($iteratorInstance instanceof Iterator);
504 // Rewind back to the beginning
505 $iteratorInstance->rewind();
507 // ... and begin iteration
508 while ($iteratorInstance->valid()) {
510 $currentRecipient = $iteratorInstance->current();
513 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
516 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
518 // Push the declared package to the next stack.
519 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
522 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
524 // Skip to next entry
525 $iteratorInstance->next();
529 * The recipient list can be cleaned up here because the package which
530 * shall be delivered has already been added for all entries from the
533 $discoveryInstance->clearRecipients();
537 * Delivers raw package data. In short, this will discover the raw socket
538 * resource through a discovery class (which will analyse the receipient of
539 * the package), register the socket with the connection (handler/helper?)
540 * instance and finally push the raw data on our outgoing queue.
542 * @param $packageData Raw package data in an array
545 private function deliverRawPackageData (array $packageData) {
547 * This package may become big, depending on the shared object size or
548 * delivered message size which shouldn't be so long (to save
549 * bandwidth). Because of the nature of the used protocol (TCP) we need
550 * to split it up into smaller pieces to fit it into a TCP frame.
552 * So first we need (again) a discovery class but now a protocol
553 * discovery to choose the right socket resource. The discovery class
554 * should take a look at the raw package data itself and then decide
555 * which (configurable!) protocol should be used for that type of
558 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
560 // Now discover the right protocol
561 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
564 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
567 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
568 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
570 // The socket needs to be put in a special registry that can handle such data
571 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
573 // Get the connection helper from registry
574 $helperInstance = Registry::getRegistry()->getInstance('connection');
576 // And make sure it is valid
577 assert($helperInstance instanceof ConnectionHelper);
579 // Get connection info class
580 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper');
582 // Will the info instance with connection helper data
583 $infoInstance->fillWithConnectionHelperInformation($helperInstance);
586 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($infoInstance, $socketResource))) {
588 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
591 $registryInstance->registerSocket($infoInstance, $socketResource, $packageData);
592 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
593 // Is not connected, then we cannot send
594 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
596 // Shutdown the socket
597 $this->shutdownSocket($socketResource);
601 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
603 // Make sure the connection is up
604 $helperInstance->getStateInstance()->validatePeerStateConnected();
607 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
609 // Enqueue it again on the out-going queue, the connection is up and working at this point
610 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
613 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
617 * Sends waiting packages
619 * @param $packageData Raw package data
622 private function sendOutgoingRawPackageData (array $packageData) {
626 // Get the right connection instance
627 $infoInstance = SocketRegistryFactory::createSocketRegistryInstance()->getInfoInstanceFromPackageData($packageData);
629 // Test helper instance
630 assert($infoInstance instanceof ShareableInfo);
632 // Get helper instance
633 $helperInstance = $infoInstance->getHelperInstance();
635 // Some sanity-checks on the object
636 //* DEBUG-DIE: */ die('[' . __METHOD__ . ':' . __LINE__ . ']: p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE));
637 assert($helperInstance instanceof ConnectionHelper);
638 assert($infoInstance->getProtocolName() == $helperInstance->getProtocolName());
640 // Is this connection still alive?
641 if ($helperInstance->isShuttedDown()) {
642 // This connection is shutting down
643 // @TODO We may want to do somthing more here?
647 // Sent out package data
648 $helperInstance->sendRawPackageData($packageData);
652 * Generates a secure hash for given raw package content and sender id
654 * @param $content Raw package data
655 * @param $senderId Sender id to generate a hash for
656 * @return $hash Hash as hex-encoded string
658 private function generatePackageHash ($content, $senderId) {
660 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: isFeatureAvailable(hubcoin_reward)=' . intval(FrameworkFeature::isFeatureAvailable('hubcoin_reward')) . ' - CALLED!');
662 // Is the feature enabled?
663 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
664 // Feature is not enabled
670 self::PACKAGE_CONTENT_SENDER => $senderId,
671 self::PACKAGE_CONTENT_MESSAGE => $content,
672 self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => ''
675 // Hash content and sender id together, use scrypt
676 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $senderId . ',content()=' . strlen($content));
677 $hash = FrameworkFeature::callFeature('hubcoin_reward', 'generateHash', array($senderId . ':' . $content . ':' . $this->determineSenderPrivateKeyHash($data)));
680 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash . ' - EXIT!');
687 * Checks whether the hash of given package data is 'valid', here that
688 * means it is the same or not.
690 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
691 * @return $isHashValid Whether the hash is valid
692 * @todo Unfinished area, hashes are currently NOT fully supported
694 private function isPackageHashValid (array $decodedArray) {
695 // Is the feature enabled?
696 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
697 // Feature is not enabled, so hashes are always valid
702 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $decodedArray[self::PACKAGE_CONTENT_SENDER] . ',decodedArray=' . print_r($decodedArray, TRUE));
703 //* DEBUG-DIE: */ die(__METHOD__ . ': decodedArray=' . print_r($decodedArray, TRUE));
704 $isHashValid = FrameworkFeature::callFeature('hubcoin_reward', 'checkHash', array($decodedArray[self::PACKAGE_CONTENT_SENDER] . ':' . $decodedArray[self::PACKAGE_CONTENT_MESSAGE] . ':' . $this->determineSenderPrivateKeyHash($decodedArray), $decodedArray[self::PACKAGE_CONTENT_HASH]));
707 //* DEBUG-DIE: */ die(__METHOD__ . ': isHashValid=' . intval($isHashValid) . ',decodedArray=' . print_r($decodedArray, TRUE));
712 * "Enqueues" raw content into this delivery class by reading the raw content
713 * from given helper's template instance and pushing it on the 'undeclared'
716 * @param $helperInstance An instance of a HubHelper class
719 public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
721 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
723 // Get the raw content ...
724 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
725 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
727 // ... and compress it
728 $compressed = $this->getCompressorInstance()->compressStream($content);
730 // Add magic in front of it and hash behind it, including BASE64 encoding
731 $packageContent = sprintf(self::PACKAGE_MASK,
732 // 1.) Compressor's extension
733 $this->getCompressorInstance()->getCompressorExtension(),
735 self::PACKAGE_MASK_SEPARATOR,
736 // 2.) Compressed raw package content, encoded with BASE64
737 base64_encode($compressed),
739 self::PACKAGE_MASK_SEPARATOR,
741 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
743 self::PACKAGE_MASK_SEPARATOR,
745 $this->getHashFromContent($compressed)
749 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
751 // Now prepare the temporary array and push it on the 'undeclared' stack
752 $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
753 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
754 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
755 self::PACKAGE_DATA_CONTENT => $packageContent,
756 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
757 self::PACKAGE_DATA_HASH => $this->generatePackageHash($content, $this->getSessionId()),
758 self::PACKAGE_DATA_PRIVATE_KEY_HASH => $this->getPrivateKeyHash(),
762 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
766 * Checks whether a package has been enqueued for delivery.
768 * @return $isEnqueued Whether a package is enqueued
770 public function isPackageEnqueued () {
771 // Check whether the stacker is not empty
772 $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
779 * Checks whether a package has been declared
781 * @return $isDeclared Whether a package is declared
783 public function isPackageDeclared () {
784 // Check whether the stacker is not empty
785 $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
792 * Checks whether a package should be sent out
794 * @return $isWaitingDelivery Whether a package is waiting for delivery
796 public function isPackageWaitingForDelivery () {
797 // Check whether the stacker is not empty
798 $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
801 return $isWaitingDelivery;
805 * Checks whether encoded (raw) data is pending
807 * @return $isPending Whether encoded data is pending
809 public function isEncodedDataPending () {
810 // Check whether the stacker is not empty
811 $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM)));
818 * Delivers an enqueued package to the stated destination. If a non-session
819 * id is provided, recipient resolver is being asked (and instanced once).
820 * This allows that a single package is being delivered to multiple targets
821 * without enqueueing it for every target. If no target is provided or it
822 * can't be determined a NoTargetException is being thrown.
825 * @throws NoTargetException If no target can't be determined
827 public function declareEnqueuedPackage () {
829 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
831 // Make sure this method isn't working if there is no package enqueued
832 if (!$this->isPackageEnqueued()) {
833 // This is not fatal but should be avoided
834 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
839 * Now there are for sure packages to deliver, so start with the first
842 $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
844 // Declare the raw package data for delivery
845 $this->declareRawPackageData($packageData);
848 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
852 * Delivers the next declared package. Only one package per time will be sent
853 * because this may take time and slows down the whole delivery
858 public function processDeclaredPackage () {
860 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
862 // Sanity check if we have packages declared
863 if (!$this->isPackageDeclared()) {
864 // This is not fatal but should be avoided
865 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
870 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
873 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
875 // Try to deliver the package
877 // And try to send it
878 $this->deliverRawPackageData($packageData);
880 // And remove it finally
881 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
882 } catch (InvalidStateException $e) {
883 // The state is not excepected (shall be 'connected')
884 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
886 // Mark the package with status failed
887 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
891 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
895 * Sends waiting packages out for delivery
899 public function sendWaitingPackage () {
901 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
903 // Sanity check if we have packages waiting for delivery
904 if (!$this->isPackageWaitingForDelivery()) {
905 // This is not fatal but should be avoided
906 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
911 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
914 // Now try to send it
915 $this->sendOutgoingRawPackageData($packageData);
917 // And remove it finally
918 $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING);
919 } catch (InvalidSocketException $e) {
920 // Output exception message
921 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
923 // Mark package as failed
924 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
928 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
932 * Sends out encoded data to a socket
936 public function sendEncodedData () {
938 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
940 // Make sure there is pending encoded data
941 assert($this->isEncodedDataPending());
943 // Pop current data from stack
944 $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
946 // Init in this round sent bytes
950 assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
953 //* 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]);
954 if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) {
955 // Send all out (encodedData is smaller than or equal buffer size)
956 //* 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]))));
957 $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]));
959 // Send buffer size out
960 //* 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])));
961 $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]);
964 // If there was an error, we don't continue here
965 if ($sentBytes === FALSE) {
966 // Handle the error with a faked recipientData array
967 $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0'));
970 throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
971 } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) {
972 // Nothing sent means we are done
973 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
976 // The difference between sent bytes and length of raw data should not go below zero
977 assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0);
979 // Add total sent bytes
980 $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
982 // Cut out the last unsent bytes
983 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...');
984 $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes);
986 // Calculate difference again
987 $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
990 if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) {
991 // Abort here, all sent!
992 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
997 // Push array back in stack
998 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
1001 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
1004 ///////////////////////////////////////////////////////////////////////////
1005 // Receiving packages / raw data
1006 ///////////////////////////////////////////////////////////////////////////
1009 * Checks whether decoded raw data is pending
1011 * @return $isPending Whether decoded raw data is pending
1013 private function isRawDataPending () {
1014 // Just return whether the stack is not empty
1015 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
1017 // Return the status
1022 * Checks whether new raw package data has arrived at a socket
1024 * @return $hasArrived Whether new raw package data has arrived for processing
1026 public function isNewRawDataPending () {
1027 // Visit the pool. This monitors the pool for incoming raw data.
1028 $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
1030 // Check for new data arrival
1031 $hasArrived = $this->isRawDataPending();
1033 // Return the status
1038 * Handles the incoming decoded raw data. This method does not "convert" the
1039 * decoded data back into a package array, it just "handles" it and pushs it
1040 * on the next stack.
1044 public function handleIncomingDecodedData () {
1046 * This method should only be called if decoded raw data is pending,
1047 * so check it again.
1049 if (!$this->isRawDataPending()) {
1050 // This is not fatal but should be avoided
1051 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
1055 // Very noisy debug message:
1056 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
1058 // "Pop" the next entry (the same array again) from the stack
1059 $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
1061 // Make sure both array elements are there
1063 (is_array($decodedData)) &&
1064 (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1065 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1069 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
1070 * only want to handle unhandled packages here.
1072 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
1073 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
1075 // Remove the last chunk SEPARATOR (because there is no need for it)
1076 if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
1077 // It is there and should be removed
1078 $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
1081 // This package is "handled" and can be pushed on the next stack
1082 //* 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 . ' ...');
1083 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
1087 * Adds raw decoded data from the given handler instance to this receiver
1089 * @param $handlerInstance An instance of a Networkable class
1092 public function addRawDataToIncomingStack (Networkable $handlerInstance) {
1094 * Get the decoded data from the handler, this is an array with
1095 * 'raw_data' and 'error_code' as elements.
1097 $decodedData = $handlerInstance->getNextRawData();
1099 // Very noisy debug message:
1100 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
1102 // And push it on our stack
1103 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
1107 * Checks whether incoming decoded data is handled.
1109 * @return $isHandled Whether incoming decoded data is handled
1111 public function isIncomingRawDataHandled () {
1112 // Determine if the stack is not empty
1113 $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
1120 * Checks whether the assembler has pending data left
1122 * @return $isHandled Whether the assembler has pending data left
1124 public function ifAssemblerHasPendingDataLeft () {
1125 // Determine if the stack is not empty
1126 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
1133 * Checks whether the assembler has multiple packages pending
1135 * @return $isPending Whether the assembler has multiple packages pending
1137 public function ifMultipleMessagesPending () {
1138 // Determine if the stack is not empty
1139 $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
1146 * Handles the attached assemler's pending data queue to be finally
1147 * assembled to the raw package data back.
1151 public function handleAssemblerPendingData () {
1153 $this->getAssemblerInstance()->handlePendingData();
1157 * Handles multiple messages.
1161 public function handleMultipleMessages () {
1163 $this->getAssemblerInstance()->handleMultipleMessages();
1167 * Assembles incoming decoded data so it will become an abstract network
1168 * package again. The assembler does later do it's job by an other task,
1169 * not this one to keep best speed possible.
1173 public function assembleDecodedDataToPackage () {
1174 // Make sure the raw decoded package data is handled
1175 assert($this->isIncomingRawDataHandled());
1177 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
1178 $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
1180 // Assert on some elements
1182 (is_array($packageContent)) &&
1183 (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1184 (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1187 // Start assembling the raw package data array by chunking it
1188 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
1190 // Remove the package from 'handled_decoded' stack ...
1191 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
1193 // ... and push it on the 'chunked' stacker
1194 //* 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));
1195 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
1199 * Accepts the visitor to process the visit "request"
1201 * @param $visitorInstance An instance of a Visitor class
1204 public function accept (Visitor $visitorInstance) {
1206 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
1208 // Visit the package
1209 $visitorInstance->visitNetworkPackage($this);
1211 // Then visit the assembler to handle multiple packages
1212 $this->getAssemblerInstance()->accept($visitorInstance);
1215 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
1223 public function clearAllStacks () {
1224 // Call the init method to force re-initialization
1225 $this->initStacks(TRUE);
1228 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
1232 * Removes the first failed outoging package from the stack to continue
1233 * with next one (it will never work until the issue is fixed by you).
1236 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
1237 * @todo This may be enchanced for outgoing packages?
1239 public function removeFirstFailedPackage () {
1240 // Get the package again
1241 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
1243 // Is the package status 'failed'?
1244 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
1246 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
1249 // Remove this entry
1250 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
1254 * "Decode" the package content into the same array when it was sent.
1256 * @param $rawPackageContent The raw package content to be "decoded"
1257 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
1259 public function decodeRawContent ($rawPackageContent) {
1260 // Use the separator '#' to "decode" it
1261 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1263 // Assert on count (should be always 3)
1264 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1267 * Create 'decodedData' array with all assoziative array elements.
1269 $decodedData = array(
1270 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
1271 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1272 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1273 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
1274 self::PACKAGE_DATA_HASH => $decodedArray[self::INDEX_PACKAGE_HASH],
1275 self::PACKAGE_DATA_PRIVATE_KEY_HASH => $decodedArray[self::INDEX_PACKAGE_PRIVATE_KEY_HASH]
1279 return $decodedData;
1283 * Handles decoded data for this node by "decoding" the 'content' part of
1284 * it. Again this method uses explode() for the "decoding" process.
1286 * @param $decodedData An array with decoded raw package data
1288 * @throws InvalidDataChecksumException If the checksum doesn't match
1290 public function handleRawData (array $decodedData) {
1292 * "Decode" the package's content by a simple explode() call, for
1293 * details of the array elements, see comments for constant
1296 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1298 // Assert on array count for a very basic validation
1299 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1302 * Convert the indexed array into an associative array. This is much
1303 * better to remember than plain numbers, isn't it?
1305 $decodedContent = array(
1306 // Compressor's extension used to compress the data
1307 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1308 // Package data (aka "message") in BASE64-decoded form but still compressed
1309 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1310 // Tags as an indexed array for "tagging" the message
1311 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1312 // Checksum of the _decoded_ data
1313 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM],
1315 self::PACKAGE_CONTENT_SENDER => $decodedData[self::PACKAGE_DATA_SENDER],
1316 // Hash from decoded raw data
1317 self::PACKAGE_CONTENT_HASH => $decodedData[self::PACKAGE_DATA_HASH],
1318 // Hash of private key
1319 self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => $decodedData[self::PACKAGE_DATA_PRIVATE_KEY_HASH]
1322 // Is the checksum valid?
1323 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1324 // Is not the same, so throw an exception here
1325 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1329 * The checksum is the same, then it can be decompressed safely. The
1330 * original message is at this point fully decoded.
1332 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1334 // And push it on the next stack
1335 $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1339 * Checks whether a new message has arrived
1341 * @return $hasArrived Whether a new message has arrived for processing
1343 public function isNewMessageArrived () {
1344 // Determine if the stack is not empty
1345 $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1352 * Handles newly arrived messages
1355 * @todo Implement verification of all sent tags here?
1357 public function handleNewlyArrivedMessage () {
1358 // Make sure there is at least one message
1359 assert($this->isNewMessageArrived());
1361 // Get it from the stacker, it is the full array with the decoded message
1362 $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1364 // Generate the hash of comparing it
1365 if (!$this->isPackageHashValid($decodedContent)) {
1366 // Is not valid, so throw an exception here
1367 exit(__METHOD__ . ':INVALID HASH! UNDER CONSTRUCTION!' . chr(10));
1370 // Now get a filter chain back from factory with given tags array
1371 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1374 * Process the message through all filters, note that all other
1375 * elements from $decodedContent are no longer needed.
1377 $chainInstance->processMessage($decodedContent, $this);
1380 * Post-processing of message data (this won't remote the message from
1383 $chainInstance->postProcessMessage($this);
1387 * Checks whether a processed message is pending for "interpretation"
1389 * @return $isPending Whether a processed message is pending
1391 public function isProcessedMessagePending () {
1393 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1400 * Handle processed messages by "interpreting" the 'message_type' element
1404 public function handleProcessedMessage () {
1405 // Get it from the stacker, it is the full array with the processed message
1406 $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1408 // Add type for later easier handling
1409 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1412 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1414 // Create a handler instance from given message type
1415 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1417 // Handle message data
1418 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1420 // Post-handling of message data
1421 $handlerInstance->postHandleMessageData($messageArray, $this);
1425 * Feeds the hash and sender (as recipient for the 'sender' reward) to the
1426 * miner's queue, unless the message is not a "reward claim" message as this
1427 * leads to an endless loop. You may wish to run the miner to get some
1428 * reward ("Hubcoins") for "mining" this hash.
1430 * @param $messageData Array with message data
1434 public function feedHashToMiner (array $messageData) {
1435 // Is the feature enabled?
1436 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
1438 * Feature is not enabled, don't feed the hash to the miner as it
1444 // Make sure the required elements are there
1445 assert(isset($messageData[self::MESSAGE_ARRAY_SENDER]));
1446 assert(isset($messageData[self::MESSAGE_ARRAY_HASH]));
1447 assert(isset($messageData[self::MESSAGE_ARRAY_TAGS]));
1450 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageData=' . print_r($messageData, TRUE));
1452 // Resolve session id ('sender' is a session id) into node id
1453 $nodeId = HubTools::resolveNodeIdBySessionId($messageData[self::MESSAGE_ARRAY_SENDER]);
1455 // Is 'claim_reward' the message type?
1456 if (in_array('claim_reward', $messageData[self::MESSAGE_ARRAY_TAGS])) {
1458 * Then don't feed this message to the miner as this causes an
1459 * endless loop of mining.
1464 $this->partialStub('@TODO nodeId=' . $nodeId . ',messageData=' . print_r($messageData, TRUE));