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';
125 const MESSAGE_ARRAY_DATA_NODE_ID = 'node-id';
128 * Generic answer status field
134 const PACKAGE_TAGS_SEPARATOR = ';';
137 * Raw package data separator
139 const PACKAGE_DATA_SEPARATOR = '#';
142 * Separator for more than one recipient
144 const PACKAGE_RECIPIENT_SEPARATOR = ':';
147 * Network target (alias): 'upper nodes'
149 const NETWORK_TARGET_UPPER = 'upper';
152 * Network target (alias): 'self'
154 const NETWORK_TARGET_SELF = 'self';
157 * Network target (alias): 'dht'
159 const NETWORK_TARGET_DHT = 'dht';
162 * TCP package size in bytes
164 const TCP_PACKAGE_SIZE = 512;
166 /**************************************************************************
167 * Stacker for out-going packages *
168 **************************************************************************/
171 * Stacker name for "undeclared" packages
173 const STACKER_NAME_UNDECLARED = 'package_undeclared';
176 * Stacker name for "declared" packages (which are ready to send out)
178 const STACKER_NAME_DECLARED = 'package_declared';
181 * Stacker name for "out-going" packages
183 const STACKER_NAME_OUTGOING = 'package_outgoing';
185 /**************************************************************************
186 * Stacker for incoming packages *
187 **************************************************************************/
190 * Stacker name for "incoming" decoded raw data
192 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
195 * Stacker name for handled decoded raw data
197 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
200 * Stacker name for "chunked" decoded raw data
202 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
204 /**************************************************************************
205 * Stacker for incoming messages *
206 **************************************************************************/
209 * Stacker name for new messages
211 const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
214 * Stacker name for processed messages
216 const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
218 /**************************************************************************
219 * Stacker for raw data handling *
220 **************************************************************************/
223 * Stacker for outgoing data stream
225 const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
228 * Array index for final hash
230 const RAW_FINAL_HASH_INDEX = 'hash';
233 * Array index for encoded data
235 const RAW_ENCODED_DATA_INDEX = 'data';
238 * Array index for sent bytes
240 const RAW_SENT_BYTES_INDEX = 'sent';
243 * Array index for socket resource
245 const RAW_SOCKET_INDEX = 'socket';
248 * Array index for buffer size
250 const RAW_BUFFER_SIZE_INDEX = 'buffer';
253 * Array index for diff between buffer and sent bytes
255 const RAW_DIFF_INDEX = 'diff';
257 /**************************************************************************
259 **************************************************************************/
260 const PROTOCOL_TCP = 'TCP';
261 const PROTOCOL_UDP = 'UDP';
264 * Protected constructor
268 protected function __construct () {
269 // Call parent constructor
270 parent::__construct(__CLASS__);
274 * Creates an instance of this class
276 * @param $compressorInstance A Compressor instance for compressing the content
277 * @return $packageInstance An instance of a Deliverable class
279 public static final function createNetworkPackage (Compressor $compressorInstance) {
281 $packageInstance = new NetworkPackage();
283 // Now set the compressor instance
284 $packageInstance->setCompressorInstance($compressorInstance);
287 * We need to initialize a stack here for our packages even for those
288 * which have no recipient address and stamp... ;-) This stacker will
289 * also be used for incoming raw data to handle it.
291 $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
293 // At last, set it in this class
294 $packageInstance->setStackInstance($stackInstance);
297 $packageInstance->initStacks();
299 // Get a visitor instance for speeding up things and set it
300 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class');
301 $packageInstance->setVisitorInstance($visitorInstance);
303 // Get crypto instance and set it, too
304 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
305 $packageInstance->setCryptoInstance($cryptoInstance);
307 // Get a singleton package assembler instance from factory and set it here, too
308 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
309 $packageInstance->setAssemblerInstance($assemblerInstance);
312 $nodeInstance = NodeObjectFactory::createNodeInstance();
314 // Get pool instance from node
315 $poolInstance = $nodeInstance->getListenerPoolInstance();
318 $packageInstance->setListenerPoolInstance($poolInstance);
320 // Return the prepared instance
321 return $packageInstance;
325 * Initialize all stackers
327 * @param $forceReInit Whether to force reinitialization of all stacks
330 protected function initStacks ($forceReInit = FALSE) {
332 $this->getStackInstance()->initStacks(array(
333 self::STACKER_NAME_UNDECLARED,
334 self::STACKER_NAME_DECLARED,
335 self::STACKER_NAME_OUTGOING,
336 self::STACKER_NAME_DECODED_INCOMING,
337 self::STACKER_NAME_DECODED_HANDLED,
338 self::STACKER_NAME_DECODED_CHUNKED,
339 self::STACKER_NAME_NEW_MESSAGE,
340 self::STACKER_NAME_PROCESSED_MESSAGE,
341 self::STACKER_NAME_OUTGOING_STREAM
346 * Determines private key hash from given session id
348 * @param $decodedData Array with decoded data
349 * @return $hash Private key's hash
350 * @throws InvalidPrivateKeyHashException If the private key's hash is not valid
352 private function determineSenderPrivateKeyHash (array $decodedData) {
354 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
356 // Ask DHT for session id
357 $senderData = $dhtInstance->findNodeLocalBySessionId($decodedData[self::PACKAGE_CONTENT_SENDER]);
359 // Is an entry found?
360 if (count($senderData) > 0) {
361 // Make sure the element 'private_key_hash' is there
362 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderData=' . print_r($senderData, TRUE));
363 assert(isset($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH]));
365 // Don't accept empty hashes
366 if (empty($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH])) {
368 throw new InvalidPrivateKeyHashException(array($this, $senderData, 'empty hash in senderData'), self::EXCEPTION_INVALID_PRIVATE_KEY_HASH);
372 return $senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH];
375 // Make sure the requested element is there
376 //* DEBUG-DIE */ die('decodedData=' . print_r($decodedData, TRUE));
377 assert(isset($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH]));
379 // Don't accept empty keys
380 if (empty($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH])) {
382 throw new InvalidPrivateKeyHashException(array($this, $senderData, 'empty hash in decodedData'), self::EXCEPTION_INVALID_PRIVATE_KEY_HASH);
385 // There is no DHT entry so, accept the hash from decoded data
386 return $decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH];
390 * "Getter" for hash from given content
392 * @param $content Raw package content
393 * @return $hash Hash for given package content
395 private function getHashFromContent ($content) {
397 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
400 // @TODO md5() is very weak, but it needs to be fast
403 self::PACKAGE_CHECKSUM_SEPARATOR .
404 $this->getSessionId() .
405 self::PACKAGE_CHECKSUM_SEPARATOR .
406 $this->getCompressorInstance()->getCompressorExtension()
410 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
417 * Checks whether the checksum (sometimes called "hash") is the same
419 * @param $decodedContent Package raw content
420 * @param $decodedData Whole raw package data array
421 * @return $isChecksumValid Whether the checksum is the same
423 private function isChecksumValid (array $decodedContent, array $decodedData) {
425 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
428 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
431 return $isChecksumValid;
435 * Change the package with given status in given stack
437 * @param $packageData Raw package data in an array
438 * @param $stackerName Name of the stacker
439 * @param $newStatus New status to set
442 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
443 // Skip this for empty stacks
444 if ($this->getStackInstance()->isStackEmpty($stackerName)) {
445 // This avoids an exception after all packages has failed
449 // Pop the entry (it should be it)
450 $nextData = $this->getStackInstance()->popNamed($stackerName);
452 // Compare both hashes
453 assert($nextData[self::PACKAGE_DATA_HASH] == $packageData[self::PACKAGE_DATA_HASH]);
455 // Temporary set the new status
456 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
459 $this->getStackInstance()->pushNamed($stackerName, $packageData);
463 * "Getter" for hash from given content and sender's session id
465 * @param $decodedContent Raw package content
466 * @param $sessionId Session id of the sender
467 * @return $hash Hash for given package content
469 public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
471 //* 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]);
474 // @TODO md5() is very weak, but it needs to be fast
476 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
477 self::PACKAGE_CHECKSUM_SEPARATOR .
479 self::PACKAGE_CHECKSUM_SEPARATOR .
480 $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
487 ///////////////////////////////////////////////////////////////////////////
488 // Delivering packages / raw data
489 ///////////////////////////////////////////////////////////////////////////
492 * Declares the given raw package data by discovering recipients
494 * @param $packageData Raw package data in an array
497 private function declareRawPackageData (array $packageData) {
498 // Make sure the required field is there
499 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
502 * We need to disover every recipient, just in case we have a
503 * multi-recipient entry like 'upper' is. 'all' may be a not so good
504 * target because it causes an overload on the network and may be
505 * abused for attacking the network with large packages.
507 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
509 // Discover all recipients, this may throw an exception
510 $discoveryInstance->discoverRecipients($packageData);
512 // Now get an iterator
513 $iteratorInstance = $discoveryInstance->getIterator();
515 // Make sure the iterator instance is valid
516 assert($iteratorInstance instanceof Iterator);
518 // Rewind back to the beginning
519 $iteratorInstance->rewind();
521 // ... and begin iteration
522 while ($iteratorInstance->valid()) {
524 $currentRecipient = $iteratorInstance->current();
527 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
530 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
532 // Push the declared package to the next stack.
533 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
536 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
538 // Skip to next entry
539 $iteratorInstance->next();
543 * The recipient list can be cleaned up here because the package which
544 * shall be delivered has already been added for all entries from the
547 $discoveryInstance->clearRecipients();
551 * Delivers raw package data. In short, this will discover the raw socket
552 * resource through a discovery class (which will analyse the receipient of
553 * the package), register the socket with the connection (handler/helper?)
554 * instance and finally push the raw data on our outgoing queue.
556 * @param $packageData Raw package data in an array
559 private function deliverRawPackageData (array $packageData) {
561 * This package may become big, depending on the shared object size or
562 * delivered message size which shouldn't be so long (to save
563 * bandwidth). Because of the nature of the used protocol (TCP) we need
564 * to split it up into smaller pieces to fit it into a TCP frame.
566 * So first we need (again) a discovery class but now a protocol
567 * discovery to choose the right socket resource. The discovery class
568 * should take a look at the raw package data itself and then decide
569 * which (configurable!) protocol should be used for that type of
572 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
574 // Now discover the right protocol
575 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
578 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
581 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
582 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
584 // The socket needs to be put in a special registry that can handle such data
585 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
587 // Get the connection helper from registry
588 $helperInstance = Registry::getRegistry()->getInstance('connection');
590 // And make sure it is valid
591 assert($helperInstance instanceof ConnectionHelper);
593 // Get connection info class
594 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper');
596 // Will the info instance with connection helper data
597 $infoInstance->fillWithConnectionHelperInformation($helperInstance);
600 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($infoInstance, $socketResource))) {
602 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
605 $registryInstance->registerSocket($infoInstance, $socketResource, $packageData);
606 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
607 // Is not connected, then we cannot send
608 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
610 // Shutdown the socket
611 $this->shutdownSocket($socketResource);
615 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
617 // Make sure the connection is up
618 $helperInstance->getStateInstance()->validatePeerStateConnected();
621 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
623 // Enqueue it again on the out-going queue, the connection is up and working at this point
624 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
627 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
631 * Sends waiting packages
633 * @param $packageData Raw package data
636 private function sendOutgoingRawPackageData (array $packageData) {
640 // Get the right connection instance
641 $infoInstance = SocketRegistryFactory::createSocketRegistryInstance()->getInfoInstanceFromPackageData($packageData);
643 // Test helper instance
644 assert($infoInstance instanceof ShareableInfo);
646 // Get helper instance
647 $helperInstance = $infoInstance->getHelperInstance();
649 // Some sanity-checks on the object
650 //* DEBUG-DIE: */ die('[' . __METHOD__ . ':' . __LINE__ . ']: p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE));
651 assert($helperInstance instanceof ConnectionHelper);
652 assert($infoInstance->getProtocolName() == $helperInstance->getProtocolName());
654 // Is this connection still alive?
655 if ($helperInstance->isShuttedDown()) {
656 // This connection is shutting down
657 // @TODO We may want to do somthing more here?
661 // Sent out package data
662 $helperInstance->sendRawPackageData($packageData);
666 * Generates a secure hash for given raw package content and sender id
668 * @param $content Raw package data
669 * @param $senderId Sender id to generate a hash for
670 * @return $hash Hash as hex-encoded string
672 private function generatePackageHash ($content, $senderId) {
674 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content()=' . strlen($content) . ',senderId=' . $senderId . ' - CALLED!');
676 // Is the feature enabled?
677 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
678 // Feature is not enabled
679 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Feature "hubcoin_reward" not available, not generating package hash. Returning NULL ...');
685 self::PACKAGE_CONTENT_SENDER => $senderId,
686 self::PACKAGE_CONTENT_MESSAGE => $content,
687 self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => ''
690 // Hash content and sender id together, use scrypt
691 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $senderId . ',content()=' . strlen($content));
692 $hash = FrameworkFeature::callFeature('hubcoin_reward', 'generateHash', array($senderId . ':' . $content . ':' . $this->determineSenderPrivateKeyHash($data)));
695 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash . ' - EXIT!');
702 * Checks whether the hash of given package data is 'valid', here that
703 * means it is the same or not.
705 * @param $decodedArray An array with 'decoded' (explode() was mostly called) data
706 * @return $isHashValid Whether the hash is valid
707 * @todo Unfinished area, hashes are currently NOT fully supported
709 private function isPackageHashValid (array $decodedArray) {
711 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedArray=' . print_r($decodedArray, TRUE) . ' - CALLED!');
713 // Make sure the required array elements are there
714 assert(isset($decodedArray[self::PACKAGE_CONTENT_SENDER]));
715 assert(isset($decodedArray[self::PACKAGE_CONTENT_MESSAGE]));
716 assert(isset($decodedArray[self::PACKAGE_CONTENT_HASH]));
717 assert(isset($decodedArray[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH]));
719 // Is the feature enabled?
720 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
721 // Feature is not enabled, so hashes are always valid
722 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Feature "hubcoin_reward" not available, not checking hash. Returning TRUE ...');
727 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $decodedArray[self::PACKAGE_CONTENT_SENDER] . ',message()=' . strlen($decodedArray[self::PACKAGE_CONTENT_MESSAGE]) . ',hash=' . $decodedArray[self::PACKAGE_CONTENT_HASH]);
728 //* DEBUG-DIE: */ die(__METHOD__ . ': decodedArray=' . print_r($decodedArray, TRUE));
729 $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]));
732 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: isHashValid=' . intval($isHashValid) . ' - EXIT!');
737 * "Enqueues" raw content into this delivery class by reading the raw content
738 * from given helper's template instance and pushing it on the 'undeclared'
741 * @param $helperInstance An instance of a HubHelper class
744 public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
746 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
748 // Get the raw content ...
749 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
750 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
752 // ... and compress it
753 $compressed = $this->getCompressorInstance()->compressStream($content);
755 // Add magic in front of it and hash behind it, including BASE64 encoding
756 $packageContent = sprintf(self::PACKAGE_MASK,
757 // 1.) Compressor's extension
758 $this->getCompressorInstance()->getCompressorExtension(),
760 self::PACKAGE_MASK_SEPARATOR,
761 // 2.) Compressed raw package content, encoded with BASE64
762 base64_encode($compressed),
764 self::PACKAGE_MASK_SEPARATOR,
766 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
768 self::PACKAGE_MASK_SEPARATOR,
770 $this->getHashFromContent($compressed)
774 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
776 // Now prepare the temporary array and push it on the 'undeclared' stack
777 $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
778 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
779 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
780 self::PACKAGE_DATA_CONTENT => $packageContent,
781 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
782 self::PACKAGE_DATA_HASH => $this->generatePackageHash($content, $this->getSessionId()),
783 self::PACKAGE_DATA_PRIVATE_KEY_HASH => $this->getPrivateKeyHash(),
787 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
791 * Checks whether a package has been enqueued for delivery.
793 * @return $isEnqueued Whether a package is enqueued
795 public function isPackageEnqueued () {
796 // Check whether the stacker is not empty
797 $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
804 * Checks whether a package has been declared
806 * @return $isDeclared Whether a package is declared
808 public function isPackageDeclared () {
809 // Check whether the stacker is not empty
810 $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
817 * Checks whether a package should be sent out
819 * @return $isWaitingDelivery Whether a package is waiting for delivery
821 public function isPackageWaitingForDelivery () {
822 // Check whether the stacker is not empty
823 $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
826 return $isWaitingDelivery;
830 * Checks whether encoded (raw) data is pending
832 * @return $isPending Whether encoded data is pending
834 public function isEncodedDataPending () {
835 // Check whether the stacker is not empty
836 $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM)));
843 * Delivers an enqueued package to the stated destination. If a non-session
844 * id is provided, recipient resolver is being asked (and instanced once).
845 * This allows that a single package is being delivered to multiple targets
846 * without enqueueing it for every target. If no target is provided or it
847 * can't be determined a NoTargetException is being thrown.
850 * @throws NoTargetException If no target can't be determined
852 public function declareEnqueuedPackage () {
854 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
856 // Make sure this method isn't working if there is no package enqueued
857 if (!$this->isPackageEnqueued()) {
858 // This is not fatal but should be avoided
859 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
864 * Now there are for sure packages to deliver, so start with the first
867 $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
869 // Declare the raw package data for delivery
870 $this->declareRawPackageData($packageData);
873 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
877 * Delivers the next declared package. Only one package per time will be sent
878 * because this may take time and slows down the whole delivery
883 public function processDeclaredPackage () {
885 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
887 // Sanity check if we have packages declared
888 if (!$this->isPackageDeclared()) {
889 // This is not fatal but should be avoided
890 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
895 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
898 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
900 // Try to deliver the package
902 // And try to send it
903 $this->deliverRawPackageData($packageData);
905 // And remove it finally
906 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
907 } catch (UnexpectedStateException $e) {
908 // The state is not excepected (shall be 'connected')
909 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
911 // Mark the package with status failed
912 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
916 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
920 * Sends waiting packages out for delivery
924 public function sendWaitingPackage () {
926 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
928 // Sanity check if we have packages waiting for delivery
929 if (!$this->isPackageWaitingForDelivery()) {
930 // This is not fatal but should be avoided
931 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
936 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
939 // Now try to send it
940 $this->sendOutgoingRawPackageData($packageData);
942 // And remove it finally
943 $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING);
944 } catch (InvalidSocketException $e) {
945 // Output exception message
946 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
948 // Mark package as failed
949 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
953 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
957 * Sends out encoded data to a socket
961 public function sendEncodedData () {
963 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
965 // Make sure there is pending encoded data
966 assert($this->isEncodedDataPending());
968 // Pop current data from stack
969 $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
971 // Init in this round sent bytes
975 assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
978 //* 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]);
979 if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) {
980 // Send all out (encodedData is smaller than or equal buffer size)
981 //* 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]))));
982 $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]));
984 // Send buffer size out
985 //* 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])));
986 $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]);
989 // If there was an error, we don't continue here
990 if ($sentBytes === FALSE) {
991 // Handle the error with a faked recipientData array
992 $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0'));
995 throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
996 } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) {
997 // Nothing sent means we are done
998 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
1001 // The difference between sent bytes and length of raw data should not go below zero
1002 assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0);
1004 // Add total sent bytes
1005 $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
1007 // Cut out the last unsent bytes
1008 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...');
1009 $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes);
1011 // Calculate difference again
1012 $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
1015 if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) {
1016 // Abort here, all sent!
1017 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
1022 // Push array back in stack
1023 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
1026 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
1029 ///////////////////////////////////////////////////////////////////////////
1030 // Receiving packages / raw data
1031 ///////////////////////////////////////////////////////////////////////////
1034 * Checks whether decoded raw data is pending
1036 * @return $isPending Whether decoded raw data is pending
1038 private function isRawDataPending () {
1039 // Just return whether the stack is not empty
1040 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
1042 // Return the status
1047 * Checks whether new raw package data has arrived at a socket
1049 * @return $hasArrived Whether new raw package data has arrived for processing
1051 public function isNewRawDataPending () {
1052 // Visit the pool. This monitors the pool for incoming raw data.
1053 $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
1055 // Check for new data arrival
1056 $hasArrived = $this->isRawDataPending();
1058 // Return the status
1063 * Handles the incoming decoded raw data. This method does not "convert" the
1064 * decoded data back into a package array, it just "handles" it and pushs it
1065 * on the next stack.
1069 public function handleIncomingDecodedData () {
1071 * This method should only be called if decoded raw data is pending,
1072 * so check it again.
1074 if (!$this->isRawDataPending()) {
1075 // This is not fatal but should be avoided
1076 self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
1080 // Very noisy debug message:
1081 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
1083 // "Pop" the next entry (the same array again) from the stack
1084 $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
1086 // Make sure both array elements are there
1088 (is_array($decodedData)) &&
1089 (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1090 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1094 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
1095 * only want to handle unhandled packages here.
1097 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
1098 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
1100 // Remove the last chunk SEPARATOR (because there is no need for it)
1101 if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
1102 // It is there and should be removed
1103 $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
1106 // This package is "handled" and can be pushed on the next stack
1107 //* 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 . ' ...');
1108 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
1112 * Adds raw decoded data from the given handler instance to this receiver
1114 * @param $handlerInstance An instance of a Networkable class
1117 public function addRawDataToIncomingStack (Networkable $handlerInstance) {
1119 * Get the decoded data from the handler, this is an array with
1120 * 'raw_data' and 'error_code' as elements.
1122 $decodedData = $handlerInstance->getNextRawData();
1124 // Very noisy debug message:
1125 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
1127 // And push it on our stack
1128 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
1132 * Checks whether incoming decoded data is handled.
1134 * @return $isHandled Whether incoming decoded data is handled
1136 public function isIncomingRawDataHandled () {
1137 // Determine if the stack is not empty
1138 $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
1145 * Checks whether the assembler has pending data left
1147 * @return $isHandled Whether the assembler has pending data left
1149 public function ifAssemblerHasPendingDataLeft () {
1150 // Determine if the stack is not empty
1151 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
1158 * Checks whether the assembler has multiple packages pending
1160 * @return $isPending Whether the assembler has multiple packages pending
1162 public function ifMultipleMessagesPending () {
1163 // Determine if the stack is not empty
1164 $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
1171 * Handles the attached assemler's pending data queue to be finally
1172 * assembled to the raw package data back.
1176 public function handleAssemblerPendingData () {
1178 $this->getAssemblerInstance()->handlePendingData();
1182 * Handles multiple messages.
1186 public function handleMultipleMessages () {
1188 $this->getAssemblerInstance()->handleMultipleMessages();
1192 * Assembles incoming decoded data so it will become an abstract network
1193 * package again. The assembler does later do it's job by an other task,
1194 * not this one to keep best speed possible.
1198 public function assembleDecodedDataToPackage () {
1199 // Make sure the raw decoded package data is handled
1200 assert($this->isIncomingRawDataHandled());
1202 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
1203 $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
1205 // Assert on some elements
1207 (is_array($packageContent)) &&
1208 (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1209 (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1212 // Start assembling the raw package data array by chunking it
1213 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
1215 // Remove the package from 'handled_decoded' stack ...
1216 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
1218 // ... and push it on the 'chunked' stacker
1219 //* 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));
1220 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
1224 * Accepts the visitor to process the visit "request"
1226 * @param $visitorInstance An instance of a Visitor class
1229 public function accept (Visitor $visitorInstance) {
1231 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
1233 // Visit the package
1234 $visitorInstance->visitNetworkPackage($this);
1236 // Then visit the assembler to handle multiple packages
1237 $this->getAssemblerInstance()->accept($visitorInstance);
1240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
1248 public function clearAllStacks () {
1249 // Call the init method to force re-initialization
1250 $this->initStacks(TRUE);
1253 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
1257 * Removes the first failed outoging package from the stack to continue
1258 * with next one (it will never work until the issue is fixed by you).
1261 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
1262 * @todo This may be enchanced for outgoing packages?
1264 public function removeFirstFailedPackage () {
1265 // Get the package again
1266 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
1268 // Is the package status 'failed'?
1269 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
1271 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
1274 // Remove this entry
1275 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
1279 * "Decode" the package content into the same array when it was sent.
1281 * @param $rawPackageContent The raw package content to be "decoded"
1282 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
1284 public function decodeRawContent ($rawPackageContent) {
1285 // Use the separator '#' to "decode" it
1286 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1288 // Assert on count (should be always 3)
1289 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1292 * Create 'decodedData' array with all assoziative array elements.
1294 $decodedData = array(
1295 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
1296 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1297 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1298 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
1299 self::PACKAGE_DATA_HASH => $decodedArray[self::INDEX_PACKAGE_HASH],
1300 self::PACKAGE_DATA_PRIVATE_KEY_HASH => $decodedArray[self::INDEX_PACKAGE_PRIVATE_KEY_HASH]
1304 return $decodedData;
1308 * Handles decoded data for this node by "decoding" the 'content' part of
1309 * it. Again this method uses explode() for the "decoding" process.
1311 * @param $decodedData An array with decoded raw package data
1313 * @throws InvalidDataChecksumException If the checksum doesn't match
1315 public function handleRawData (array $decodedData) {
1317 * "Decode" the package's content by a simple explode() call, for
1318 * details of the array elements, see comments for constant
1321 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1323 // Assert on array count for a very basic validation
1324 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1327 * Convert the indexed array into an associative array. This is much
1328 * better to remember than plain numbers, isn't it?
1330 $decodedContent = array(
1331 // Compressor's extension used to compress the data
1332 self::PACKAGE_CONTENT_EXTENSION => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1333 // Package data (aka "message") in BASE64-decoded form but still compressed
1334 self::PACKAGE_CONTENT_MESSAGE => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1335 // Tags as an indexed array for "tagging" the message
1336 self::PACKAGE_CONTENT_TAGS => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1337 // Checksum of the _decoded_ data
1338 self::PACKAGE_CONTENT_CHECKSUM => $decodedContent[self::INDEX_CHECKSUM],
1340 self::PACKAGE_CONTENT_SENDER => $decodedData[self::PACKAGE_DATA_SENDER],
1341 // Hash from decoded raw data
1342 self::PACKAGE_CONTENT_HASH => $decodedData[self::PACKAGE_DATA_HASH],
1343 // Hash of private key
1344 self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => $decodedData[self::PACKAGE_DATA_PRIVATE_KEY_HASH]
1347 // Is the checksum valid?
1348 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1349 // Is not the same, so throw an exception here
1350 throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1354 * The checksum is the same, then it can be decompressed safely. The
1355 * original message is at this point fully decoded.
1357 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1359 // And push it on the next stack
1360 $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1364 * Checks whether a new message has arrived
1366 * @return $hasArrived Whether a new message has arrived for processing
1368 public function isNewMessageArrived () {
1369 // Determine if the stack is not empty
1370 $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1377 * Handles newly arrived messages
1380 * @todo Implement verification of all sent tags here?
1382 public function handleNewlyArrivedMessage () {
1383 // Make sure there is at least one message
1384 assert($this->isNewMessageArrived());
1386 // Get it from the stacker, it is the full array with the decoded message
1387 $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1389 // Generate the hash of comparing it
1390 if (!$this->isPackageHashValid($decodedContent)) {
1391 // Is not valid, so throw an exception here
1392 exit(__METHOD__ . ':INVALID HASH! UNDER CONSTRUCTION!' . chr(10));
1395 // Now get a filter chain back from factory with given tags array
1396 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1399 * Process the message through all filters, note that all other
1400 * elements from $decodedContent are no longer needed.
1402 $chainInstance->processMessage($decodedContent, $this);
1405 * Post-processing of message data (this won't remove the message from
1408 $chainInstance->postProcessMessage($this);
1412 * Checks whether a processed message is pending for "interpretation"
1414 * @return $isPending Whether a processed message is pending
1416 public function isProcessedMessagePending () {
1418 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1425 * Handle processed messages by "interpreting" the 'message_type' element
1429 public function handleProcessedMessage () {
1430 // Get it from the stacker, it is the full array with the processed message
1431 $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1433 // Add type for later easier handling
1434 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1437 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1439 // Create a handler instance from given message type
1440 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1442 // Handle message data
1443 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1445 // Post-handling of message data
1446 $handlerInstance->postHandleMessageData($messageArray, $this);
1450 * Feeds the hash and sender (as recipient for the 'sender' reward) to the
1451 * miner's queue, unless the message is not a "reward claim" message as this
1452 * leads to an endless loop. You may wish to run the miner to get some
1453 * reward ("Hubcoins") for "mining" this hash.
1455 * @param $messageData Array with message data
1459 public function feedHashToMiner (array $messageData) {
1460 // Is the feature enabled?
1461 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
1463 * Feature is not enabled, don't feed the hash to the miner as it
1469 // Make sure the required elements are there
1470 assert(isset($messageData[self::MESSAGE_ARRAY_SENDER]));
1471 assert(isset($messageData[self::MESSAGE_ARRAY_HASH]));
1472 assert(isset($messageData[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_DATA_NODE_ID]));
1475 $messageData[self::MESSAGE_ARRAY_DATA_NODE_ID] = $messageData[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_DATA_NODE_ID];
1477 // Let's get rid of some fields that is not needed by the miner:
1478 unset($messageData[self::MESSAGE_ARRAY_TYPE]);
1479 unset($messageData[self::MESSAGE_ARRAY_DATA]);
1482 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageData=' . print_r($messageData, TRUE));
1484 // Resolve session id ('sender' is a session id) into node id
1485 $nodeId = HubTools::resolveNodeIdBySessionId($messageData[self::MESSAGE_ARRAY_SENDER]);
1487 // Is 'claim_reward' the message type?
1488 if (in_array(BaseTag::TAG_CLAIM_MINING_REWARD, $messageData[self::MESSAGE_ARRAY_TAGS])) {
1490 * Then don't feed this message to the miner as this causes an
1491 * endless loop of mining.
1496 // Also remove tags as the miner don't need this.
1497 unset($messageData[self::MESSAGE_ARRAY_TAGS]);
1499 $this->partialStub('@TODO nodeId=' . $nodeId . ',messageData=' . print_r($messageData, TRUE));