abf479254dd98e86a4f5b9748c6d51536fb25ab4
[hub.git] / application / hub / classes / package / class_NetworkPackage.php
1 <?php
2 /**
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
7  * packages.
8  *
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
13  * Internet.
14  *
15  * For performance reasons, this class should only be instanciated once and then
16  * used as a "pipe-through" class.
17  *
18  * @author              Roland Haeder <webmaster@shipsimu.org>
19  * @version             0.0.0
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
24  *
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.
29  *
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.
34  *
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/>.
37  */
38 class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, Registerable, Visitable {
39         /**
40          * Package mask for compressing package data:
41          * 0: Compressor extension
42          * 1: Raw package data
43          * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
44          * 3: Checksum
45          *                     0  1  2  3
46          */
47         const PACKAGE_MASK = '%s%s%s%s%s%s%s';
48
49         /**
50          * Separator for the above mask
51          */
52         const PACKAGE_MASK_SEPARATOR = '^';
53
54         /**
55          * Size of an array created by invoking
56          * explode(NetworkPackage::PACKAGE_MASK_SEPARATOR, $content).
57          */
58         const PACKAGE_CONTENT_ARRAY_SIZE = 4;
59
60         /**
61          * Separator for checksum
62          */
63         const PACKAGE_CHECKSUM_SEPARATOR = '_';
64
65         /**
66          * Array indexes for above mask, start with zero
67          */
68         const INDEX_COMPRESSOR_EXTENSION = 0;
69         const INDEX_PACKAGE_DATA         = 1;
70         const INDEX_TAGS                 = 2;
71         const INDEX_CHECKSUM             = 3;
72
73         /**
74          * Array indexes for raw package array
75          */
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;
82
83         /**
84          * Size of the decoded data array
85          */
86         const DECODED_DATA_ARRAY_SIZE = 6;
87
88         /**
89          * Named array elements for decoded package content
90          */
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';
98
99         /**
100          * Named array elements for package data
101          */
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';
108
109         /**
110          * All package status
111          */
112         const PACKAGE_STATUS_NEW     = 'new';
113         const PACKAGE_STATUS_FAILED  = 'failed';
114         const PACKAGE_STATUS_DECODED = 'decoded';
115         const PACKAGE_STATUS_FAKED   = 'faked';
116
117         /**
118          * Constants for message data array
119          */
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
126         /**
127          * Generic answer status field
128          */
129
130         /**
131          * Tags separator
132          */
133         const PACKAGE_TAGS_SEPARATOR = ';';
134
135         /**
136          * Raw package data separator
137          */
138         const PACKAGE_DATA_SEPARATOR = '#';
139
140         /**
141          * Separator for more than one recipient
142          */
143         const PACKAGE_RECIPIENT_SEPARATOR = ':';
144
145         /**
146          * Network target (alias): 'upper nodes'
147          */
148         const NETWORK_TARGET_UPPER = 'upper';
149
150         /**
151          * Network target (alias): 'self'
152          */
153         const NETWORK_TARGET_SELF = 'self';
154
155         /**
156          * Network target (alias): 'dht'
157          */
158         const NETWORK_TARGET_DHT = 'dht';
159
160         /**
161          * TCP package size in bytes
162          */
163         const TCP_PACKAGE_SIZE = 512;
164
165         /**************************************************************************
166          *                    Stacker for out-going packages                      *
167          **************************************************************************/
168
169         /**
170          * Stacker name for "undeclared" packages
171          */
172         const STACKER_NAME_UNDECLARED = 'package_undeclared';
173
174         /**
175          * Stacker name for "declared" packages (which are ready to send out)
176          */
177         const STACKER_NAME_DECLARED = 'package_declared';
178
179         /**
180          * Stacker name for "out-going" packages
181          */
182         const STACKER_NAME_OUTGOING = 'package_outgoing';
183
184         /**************************************************************************
185          *                     Stacker for incoming packages                      *
186          **************************************************************************/
187
188         /**
189          * Stacker name for "incoming" decoded raw data
190          */
191         const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
192
193         /**
194          * Stacker name for handled decoded raw data
195          */
196         const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
197
198         /**
199          * Stacker name for "chunked" decoded raw data
200          */
201         const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
202
203         /**************************************************************************
204          *                     Stacker for incoming messages                      *
205          **************************************************************************/
206
207         /**
208          * Stacker name for new messages
209          */
210         const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
211
212         /**
213          * Stacker name for processed messages
214          */
215         const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
216
217         /**************************************************************************
218          *                      Stacker for raw data handling                     *
219          **************************************************************************/
220
221         /**
222          * Stacker for outgoing data stream
223          */
224         const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
225
226         /**
227          * Array index for final hash
228          */
229         const RAW_FINAL_HASH_INDEX = 'hash';
230
231         /**
232          * Array index for encoded data
233          */
234         const RAW_ENCODED_DATA_INDEX = 'data';
235
236         /**
237          * Array index for sent bytes
238          */
239         const RAW_SENT_BYTES_INDEX = 'sent';
240
241         /**
242          * Array index for socket resource
243          */
244         const RAW_SOCKET_INDEX = 'socket';
245
246         /**
247          * Array index for buffer size
248          */
249         const RAW_BUFFER_SIZE_INDEX = 'buffer';
250
251         /**
252          * Array index for diff between buffer and sent bytes
253          */
254         const RAW_DIFF_INDEX = 'diff';
255
256         /**************************************************************************
257          *                            Protocol names                              *
258          **************************************************************************/
259         const PROTOCOL_TCP = 'TCP';
260         const PROTOCOL_UDP = 'UDP';
261
262         /**
263          * Protected constructor
264          *
265          * @return      void
266          */
267         protected function __construct () {
268                 // Call parent constructor
269                 parent::__construct(__CLASS__);
270         }
271
272         /**
273          * Creates an instance of this class
274          *
275          * @param       $compressorInstance             A Compressor instance for compressing the content
276          * @return      $packageInstance                An instance of a Deliverable class
277          */
278         public static final function createNetworkPackage (Compressor $compressorInstance) {
279                 // Get new instance
280                 $packageInstance = new NetworkPackage();
281
282                 // Now set the compressor instance
283                 $packageInstance->setCompressorInstance($compressorInstance);
284
285                 /*
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.
289                  */
290                 $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
291
292                 // At last, set it in this class
293                 $packageInstance->setStackInstance($stackInstance);
294
295                 // Init all stacker
296                 $packageInstance->initStacks();
297
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);
301
302                 // Get crypto instance and set it, too
303                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
304                 $packageInstance->setCryptoInstance($cryptoInstance);
305
306                 // Get a singleton package assembler instance from factory and set it here, too
307                 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
308                 $packageInstance->setAssemblerInstance($assemblerInstance);
309
310                 // Get node instance
311                 $nodeInstance = NodeObjectFactory::createNodeInstance();
312
313                 // Get pool instance from node
314                 $poolInstance = $nodeInstance->getListenerPoolInstance();
315
316                 // And set it here
317                 $packageInstance->setListenerPoolInstance($poolInstance);
318
319                 // Return the prepared instance
320                 return $packageInstance;
321         }
322
323         /**
324          * Initialize all stackers
325          *
326          * @param       $forceReInit    Whether to force reinitialization of all stacks
327          * @return      void
328          */
329         protected function initStacks ($forceReInit = FALSE) {
330                 // Initialize all
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
341                 ), $forceReInit);
342         }
343
344         /**
345          * Determines private key hash from given session id
346          *
347          * @param       $decodedData    Array with decoded data
348          * @return      $hash                   Private key's hash
349          * @throws      InvalidPrivateKeyHashException  If the private key's hash is not valid
350          */
351         private function determineSenderPrivateKeyHash (array $decodedData) {
352                 // Get DHT instance
353                 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
354
355                 // Ask DHT for session id
356                 $senderData = $dhtInstance->findNodeLocalBySessionId($decodedData[self::PACKAGE_CONTENT_SENDER]);
357
358                 // Is an entry found?
359                 if (count($senderData) > 0) {
360                         // Make sure the element 'private_key_hash' is there
361                         //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderData=' . print_r($senderData, TRUE));
362                         assert(isset($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH]));
363
364                         // Don't accept empty hashes
365                         if (empty($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH])) {
366                                 // Don't accept
367                                 throw new InvalidPrivateKeyHashException(array($this, $senderData, 'empty hash in senderData'));
368                         } // END - if
369
370                         // Return it
371                         return $senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH];
372                 } // END - if
373
374                 // Make sure the requested element is there
375                 //* DEBUG-DIE */ die('decodedData=' . print_r($decodedData, TRUE));
376                 assert(isset($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH]));
377
378                 // Don't accept empty keys
379                 if (empty($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH])) {
380                         // This needs fixing
381                         throw new InvalidPrivateKeyHashException(array($this, $senderData, 'empty hash in decodedData'));
382                 } // END - if
383
384                 // There is no DHT entry so, accept the hash from decoded data
385                 return $decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH];
386         }
387
388         /**
389          * "Getter" for hash from given content
390          *
391          * @param       $content        Raw package content
392          * @return      $hash           Hash for given package content
393          */
394         private function getHashFromContent ($content) {
395                 // Debug message
396                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
397
398                 // Create the hash
399                 // @TODO md5() is very weak, but it needs to be fast
400                 $hash = md5(
401                         $content .
402                         self::PACKAGE_CHECKSUM_SEPARATOR .
403                         $this->getSessionId() .
404                         self::PACKAGE_CHECKSUM_SEPARATOR .
405                         $this->getCompressorInstance()->getCompressorExtension()
406                 );
407
408                 // Debug message
409                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
410
411                 // And return it
412                 return $hash;
413         }
414
415         /**
416          * Checks whether the checksum (sometimes called "hash") is the same
417          *
418          * @param       $decodedContent         Package raw content
419          * @param       $decodedData            Whole raw package data array
420          * @return      $isChecksumValid        Whether the checksum is the same
421          */
422         private function isChecksumValid (array $decodedContent, array $decodedData) {
423                 // Get checksum
424                 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
425
426                 // Is it the same?
427                 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
428
429                 // Return it
430                 return $isChecksumValid;
431         }
432
433         /**
434          * Change the package with given status in given stack
435          *
436          * @param       $packageData    Raw package data in an array
437          * @param       $stackerName    Name of the stacker
438          * @param       $newStatus              New status to set
439          * @return      void
440          */
441         private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
442                 // Skip this for empty stacks
443                 if ($this->getStackInstance()->isStackEmpty($stackerName)) {
444                         // This avoids an exception after all packages has failed
445                         return;
446                 } // END - if
447
448                 // Pop the entry (it should be it)
449                 $nextData = $this->getStackInstance()->popNamed($stackerName);
450
451                 // Compare both hashes
452                 assert($nextData[self::PACKAGE_DATA_HASH] == $packageData[self::PACKAGE_DATA_HASH]);
453
454                 // Temporary set the new status
455                 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
456
457                 // And push it again
458                 $this->getStackInstance()->pushNamed($stackerName, $packageData);
459         }
460
461         /**
462          * "Getter" for hash from given content and sender's session id
463          *
464          * @param       $decodedContent         Raw package content
465          * @param       $sessionId                      Session id of the sender
466          * @return      $hash                           Hash for given package content
467          */
468         public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
469                 // Debug message
470                 //* 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]);
471
472                 // Create the hash
473                 // @TODO md5() is very weak, but it needs to be fast
474                 $hash = md5(
475                         $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
476                         self::PACKAGE_CHECKSUM_SEPARATOR .
477                         $sessionId .
478                         self::PACKAGE_CHECKSUM_SEPARATOR .
479                         $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
480                 );
481
482                 // And return it
483                 return $hash;
484         }
485
486         ///////////////////////////////////////////////////////////////////////////
487         //                   Delivering packages / raw data
488         ///////////////////////////////////////////////////////////////////////////
489
490         /**
491          * Declares the given raw package data by discovering recipients
492          *
493          * @param       $packageData    Raw package data in an array
494          * @return      void
495          */
496         private function declareRawPackageData (array $packageData) {
497                 // Make sure the required field is there
498                 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
499
500                 /*
501                  * We need to disover every recipient, just in case we have a
502                  * multi-recipient entry like 'upper' is. 'all' may be a not so good
503                  * target because it causes an overload on the network and may be
504                  * abused for attacking the network with large packages.
505                  */
506                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
507
508                 // Discover all recipients, this may throw an exception
509                 $discoveryInstance->discoverRecipients($packageData);
510
511                 // Now get an iterator
512                 $iteratorInstance = $discoveryInstance->getIterator();
513
514                 // Make sure the iterator instance is valid
515                 assert($iteratorInstance instanceof Iterator);
516
517                 // Rewind back to the beginning
518                 $iteratorInstance->rewind();
519
520                 // ... and begin iteration
521                 while ($iteratorInstance->valid()) {
522                         // Get current entry
523                         $currentRecipient = $iteratorInstance->current();
524
525                         // Debug message
526                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
527
528                         // Set the recipient
529                         $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
530
531                         // Push the declared package to the next stack.
532                         $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
533
534                         // Debug message
535                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
536
537                         // Skip to next entry
538                         $iteratorInstance->next();
539                 } // END - while
540
541                 /*
542                  * The recipient list can be cleaned up here because the package which
543                  * shall be delivered has already been added for all entries from the
544                  * list.
545                  */
546                 $discoveryInstance->clearRecipients();
547         }
548
549         /**
550          * Delivers raw package data. In short, this will discover the raw socket
551          * resource through a discovery class (which will analyse the receipient of
552          * the package), register the socket with the connection (handler/helper?)
553          * instance and finally push the raw data on our outgoing queue.
554          *
555          * @param       $packageData    Raw package data in an array
556          * @return      void
557          */
558         private function deliverRawPackageData (array $packageData) {
559                 /*
560                  * This package may become big, depending on the shared object size or
561                  * delivered message size which shouldn't be so long (to save
562                  * bandwidth). Because of the nature of the used protocol (TCP) we need
563                  * to split it up into smaller pieces to fit it into a TCP frame.
564                  *
565                  * So first we need (again) a discovery class but now a protocol
566                  * discovery to choose the right socket resource. The discovery class
567                  * should take a look at the raw package data itself and then decide
568                  * which (configurable!) protocol should be used for that type of
569                  * package.
570                  */
571                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
572
573                 // Now discover the right protocol
574                 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
575
576                 // Debug message
577                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
578
579                 // Debug message
580                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
581                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
582
583                 // The socket needs to be put in a special registry that can handle such data
584                 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
585
586                 // Get the connection helper from registry
587                 $helperInstance = Registry::getRegistry()->getInstance('connection');
588
589                 // And make sure it is valid
590                 assert($helperInstance instanceof ConnectionHelper);
591
592                 // Get connection info class
593                 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper');
594
595                 // Will the info instance with connection helper data
596                 $infoInstance->fillWithConnectionHelperInformation($helperInstance);
597
598                 // Is it not there?
599                 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($infoInstance, $socketResource))) {
600                         // Debug message
601                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
602
603                         // Then register it
604                         $registryInstance->registerSocket($infoInstance, $socketResource, $packageData);
605                 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
606                         // Is not connected, then we cannot send
607                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
608
609                         // Shutdown the socket
610                         $this->shutdownSocket($socketResource);
611                 }
612
613                 // Debug message
614                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
615
616                 // Make sure the connection is up
617                 $helperInstance->getStateInstance()->validatePeerStateConnected();
618
619                 // Debug message
620                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
621
622                 // Enqueue it again on the out-going queue, the connection is up and working at this point
623                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
624
625                 // Debug message
626                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
627         }
628
629         /**
630          * Sends waiting packages
631          *
632          * @param       $packageData    Raw package data
633          * @return      void
634          */
635         private function sendOutgoingRawPackageData (array $packageData) {
636                 // Init sent bytes
637                 $sentBytes = 0;
638
639                 // Get the right connection instance
640                 $infoInstance = SocketRegistryFactory::createSocketRegistryInstance()->getInfoInstanceFromPackageData($packageData);
641
642                 // Test helper instance
643                 assert($infoInstance instanceof ShareableInfo);
644
645                 // Get helper instance
646                 $helperInstance = $infoInstance->getHelperInstance();
647
648                 // Some sanity-checks on the object
649                 //* DEBUG-DIE: */ die('[' . __METHOD__ . ':' . __LINE__ . ']: p1=' . $infoInstance->getProtocolName() . ',p2=' . $helperInstance->getProtocolName() . ',infoInstance=' . print_r($infoInstance, TRUE));
650                 assert($helperInstance instanceof ConnectionHelper);
651                 assert($infoInstance->getProtocolName() == $helperInstance->getProtocolName());
652
653                 // Is this connection still alive?
654                 if ($helperInstance->isShuttedDown()) {
655                         // This connection is shutting down
656                         // @TODO We may want to do somthing more here?
657                         return;
658                 } // END - if
659
660                 // Sent out package data
661                 $helperInstance->sendRawPackageData($packageData);
662         }
663
664         /**
665          * Generates a secure hash for given raw package content and sender id
666          *
667          * @param       $content        Raw package data
668          * @param       $senderId       Sender id to generate a hash for
669          * @return      $hash           Hash as hex-encoded string
670          */
671         private function generatePackageHash ($content, $senderId) {
672                 // Debug message
673                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content()=' . strlen($content) . ',senderId=' . $senderId . ' - CALLED!');
674
675                 // Is the feature enabled?
676                 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
677                         // Feature is not enabled
678                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Feature "hubcoin_reward" not available, not generating package hash. Returning NULL ...');
679                         return NULL;
680                 } // END - if
681
682                 // Fake array
683                 $data = array(
684                         self::PACKAGE_CONTENT_SENDER           => $senderId,
685                         self::PACKAGE_CONTENT_MESSAGE          => $content,
686                         self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => ''
687                 );
688         
689                 // Hash content and sender id together, use scrypt
690                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: senderId=' . $senderId . ',content()=' . strlen($content));
691                 $hash = FrameworkFeature::callFeature('hubcoin_reward', 'generateHash', array($senderId . ':' . $content . ':' . $this->determineSenderPrivateKeyHash($data)));
692
693                 // Debug message
694                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash . ' - EXIT!');
695
696                 // Return it
697                 return $hash;
698         }
699
700         /**
701          * Checks whether the hash of given package data is 'valid', here that
702          * means it is the same or not.
703          *
704          * @param       $decodedArray           An array with 'decoded' (explode() was mostly called) data
705          * @return      $isHashValid    Whether the hash is valid
706          * @todo        Unfinished area, hashes are currently NOT fully supported
707          */
708         private function isPackageHashValid (array $decodedArray) {
709                 // Debug message
710                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedArray=' . print_r($decodedArray, TRUE) . ' - CALLED!');
711
712                 // Make sure the required array elements are there
713                 assert(isset($decodedArray[self::PACKAGE_CONTENT_SENDER]));
714                 assert(isset($decodedArray[self::PACKAGE_CONTENT_MESSAGE]));
715                 assert(isset($decodedArray[self::PACKAGE_CONTENT_HASH]));
716                 assert(isset($decodedArray[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH]));
717
718                 // Is the feature enabled?
719                 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
720                         // Feature is not enabled, so hashes are always valid
721                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Feature "hubcoin_reward" not available, not checking hash. Returning TRUE ...');
722                         return TRUE;
723                 } // END - if
724
725                 // Check validity
726                 //* 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]);
727                 //* DEBUG-DIE: */ die(__METHOD__ . ': decodedArray=' . print_r($decodedArray, TRUE));
728                 $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]));
729
730                 // Return it
731                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: isHashValid=' . intval($isHashValid) . ' - EXIT!');
732                 return $isHashValid;
733         }
734
735         /**
736          * "Enqueues" raw content into this delivery class by reading the raw content
737          * from given helper's template instance and pushing it on the 'undeclared'
738          * stack.
739          *
740          * @param       $helperInstance         An instance of a HubHelper class
741          * @return      void
742          */
743         public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
744                 // Debug message
745                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
746
747                 // Get the raw content ...
748                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
749                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
750
751                 // ... and compress it
752                 $compressed = $this->getCompressorInstance()->compressStream($content);
753
754                 // Add magic in front of it and hash behind it, including BASE64 encoding
755                 $packageContent = sprintf(self::PACKAGE_MASK,
756                         // 1.) Compressor's extension
757                         $this->getCompressorInstance()->getCompressorExtension(),
758                         // - separator
759                         self::PACKAGE_MASK_SEPARATOR,
760                         // 2.) Compressed raw package content, encoded with BASE64
761                         base64_encode($compressed),
762                         // - separator
763                         self::PACKAGE_MASK_SEPARATOR,
764                         // 3.) Tags
765                         implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
766                         // - separator
767                         self::PACKAGE_MASK_SEPARATOR,
768                         // 4.) Checksum
769                         $this->getHashFromContent($compressed)
770                 );
771
772                 // Debug message
773                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
774
775                 // Now prepare the temporary array and push it on the 'undeclared' stack
776                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
777                         self::PACKAGE_DATA_SENDER           => $this->getSessionId(),
778                         self::PACKAGE_DATA_RECIPIENT        => $helperInstance->getRecipientType(),
779                         self::PACKAGE_DATA_CONTENT          => $packageContent,
780                         self::PACKAGE_DATA_STATUS           => self::PACKAGE_STATUS_NEW,
781                         self::PACKAGE_DATA_HASH             => $this->generatePackageHash($content, $this->getSessionId()),
782                         self::PACKAGE_DATA_PRIVATE_KEY_HASH => $this->getPrivateKeyHash(),
783                 ));
784
785                 // Debug message
786                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
787         }
788
789         /**
790          * Checks whether a package has been enqueued for delivery.
791          *
792          * @return      $isEnqueued             Whether a package is enqueued
793          */
794         public function isPackageEnqueued () {
795                 // Check whether the stacker is not empty
796                 $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
797
798                 // Return the result
799                 return $isEnqueued;
800         }
801
802         /**
803          * Checks whether a package has been declared
804          *
805          * @return      $isDeclared             Whether a package is declared
806          */
807         public function isPackageDeclared () {
808                 // Check whether the stacker is not empty
809                 $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
810
811                 // Return the result
812                 return $isDeclared;
813         }
814
815         /**
816          * Checks whether a package should be sent out
817          *
818          * @return      $isWaitingDelivery      Whether a package is waiting for delivery
819          */
820         public function isPackageWaitingForDelivery () {
821                 // Check whether the stacker is not empty
822                 $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
823
824                 // Return the result
825                 return $isWaitingDelivery;
826         }
827
828         /**
829          * Checks whether encoded (raw) data is pending
830          *
831          * @return      $isPending              Whether encoded data is pending
832          */
833         public function isEncodedDataPending () {
834                 // Check whether the stacker is not empty
835                 $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM)));
836
837                 // Return the result
838                 return $isPending;
839         }
840
841         /**
842          * Delivers an enqueued package to the stated destination. If a non-session
843          * id is provided, recipient resolver is being asked (and instanced once).
844          * This allows that a single package is being delivered to multiple targets
845          * without enqueueing it for every target. If no target is provided or it
846          * can't be determined a NoTargetException is being thrown.
847          *
848          * @return      void
849          * @throws      NoTargetException       If no target can't be determined
850          */
851         public function declareEnqueuedPackage () {
852                 // Debug message
853                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
854
855                 // Make sure this method isn't working if there is no package enqueued
856                 if (!$this->isPackageEnqueued()) {
857                         // This is not fatal but should be avoided
858                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!');
859                         return;
860                 } // END - if
861
862                 /*
863                  * Now there are for sure packages to deliver, so start with the first
864                  * one.
865                  */
866                 $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
867
868                 // Declare the raw package data for delivery
869                 $this->declareRawPackageData($packageData);
870
871                 // Debug message
872                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
873         }
874
875         /**
876          * Delivers the next declared package. Only one package per time will be sent
877          * because this may take time and slows down the whole delivery
878          * infrastructure.
879          *
880          * @return      void
881          */
882         public function processDeclaredPackage () {
883                 // Debug message
884                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
885
886                 // Sanity check if we have packages declared
887                 if (!$this->isPackageDeclared()) {
888                         // This is not fatal but should be avoided
889                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
890                         return;
891                 } // END - if
892
893                 // Get the package
894                 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
895
896                 // Assert on it
897                 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
898
899                 // Try to deliver the package
900                 try {
901                         // And try to send it
902                         $this->deliverRawPackageData($packageData);
903
904                         // And remove it finally
905                         $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
906                 } catch (UnexpectedStateException $e) {
907                         // The state is not excepected (shall be 'connected')
908                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
909
910                         // Mark the package with status failed
911                         $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
912                 }
913
914                 // Debug message
915                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
916         }
917
918         /**
919          * Sends waiting packages out for delivery
920          *
921          * @return      void
922          */
923         public function sendWaitingPackage () {
924                 // Debug message
925                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
926
927                 // Sanity check if we have packages waiting for delivery
928                 if (!$this->isPackageWaitingForDelivery()) {
929                         // This is not fatal but should be avoided
930                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
931                         return;
932                 } // END - if
933
934                 // Get the package
935                 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
936
937                 try {
938                         // Now try to send it
939                         $this->sendOutgoingRawPackageData($packageData);
940
941                         // And remove it finally
942                         $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING);
943                 } catch (InvalidSocketException $e) {
944                         // Output exception message
945                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
946
947                         // Mark package as failed
948                         $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
949                 }
950
951                 // Debug message
952                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
953         }
954
955         /**
956          * Sends out encoded data to a socket
957          *
958          * @return      void
959          */
960         public function sendEncodedData () {
961                 // Debug message
962                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
963
964                 // Make sure there is pending encoded data
965                 assert($this->isEncodedDataPending());
966
967                 // Pop current data from stack
968                 $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
969
970                 // Init in this round sent bytes
971                 $sentBytes = 0;
972
973                 // Assert on socket
974                 assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
975
976                 // And deliver it
977                 //* 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]);
978                 if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) {
979                         // Send all out (encodedData is smaller than or equal buffer size)
980                         //* 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]))));
981                         $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]));
982                 } else {
983                         // Send buffer size out
984                         //* 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])));
985                         $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]);
986                 }
987
988                 // If there was an error, we don't continue here
989                 if ($sentBytes === FALSE) {
990                         // Handle the error with a faked recipientData array
991                         $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0'));
992
993                         // And throw it
994                         throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
995                 } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) {
996                         // Nothing sent means we are done
997                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
998                         return;
999                 } else {
1000                         // The difference between sent bytes and length of raw data should not go below zero
1001                         assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0);
1002
1003                         // Add total sent bytes
1004                         $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
1005
1006                         // Cut out the last unsent bytes
1007                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...');
1008                         $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes);
1009
1010                         // Calculate difference again
1011                         $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
1012
1013                         // Can we abort?
1014                         if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) {
1015                                 // Abort here, all sent!
1016                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
1017                                 return;
1018                         } // END - if
1019                 }
1020
1021                 // Push array back in stack
1022                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
1023
1024                 // Debug message
1025                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
1026         }
1027
1028         ///////////////////////////////////////////////////////////////////////////
1029         //                   Receiving packages / raw data
1030         ///////////////////////////////////////////////////////////////////////////
1031
1032         /**
1033          * Checks whether decoded raw data is pending
1034          *
1035          * @return      $isPending      Whether decoded raw data is pending
1036          */
1037         private function isRawDataPending () {
1038                 // Just return whether the stack is not empty
1039                 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
1040
1041                 // Return the status
1042                 return $isPending;
1043         }
1044
1045         /**
1046          * Checks whether new raw package data has arrived at a socket
1047          *
1048          * @return      $hasArrived             Whether new raw package data has arrived for processing
1049          */
1050         public function isNewRawDataPending () {
1051                 // Visit the pool. This monitors the pool for incoming raw data.
1052                 $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
1053
1054                 // Check for new data arrival
1055                 $hasArrived = $this->isRawDataPending();
1056
1057                 // Return the status
1058                 return $hasArrived;
1059         }
1060
1061         /**
1062          * Handles the incoming decoded raw data. This method does not "convert" the
1063          * decoded data back into a package array, it just "handles" it and pushs it
1064          * on the next stack.
1065          *
1066          * @return      void
1067          */
1068         public function handleIncomingDecodedData () {
1069                 /*
1070                  * This method should only be called if decoded raw data is pending,
1071                  * so check it again.
1072                  */
1073                 if (!$this->isRawDataPending()) {
1074                         // This is not fatal but should be avoided
1075                         self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!');
1076                         return;
1077                 } // END - if
1078
1079                 // Very noisy debug message:
1080                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
1081
1082                 // "Pop" the next entry (the same array again) from the stack
1083                 $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
1084
1085                 // Make sure both array elements are there
1086                 assert(
1087                         (is_array($decodedData)) &&
1088                         (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1089                         (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1090                 );
1091
1092                 /*
1093                  * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
1094                  * only want to handle unhandled packages here.
1095                  */
1096                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
1097                 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
1098
1099                 // Remove the last chunk SEPARATOR (because there is no need for it)
1100                 if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
1101                         // It is there and should be removed
1102                         $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
1103                 } // END - if
1104
1105                 // This package is "handled" and can be pushed on the next stack
1106                 //* 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 . ' ...');
1107                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
1108         }
1109
1110         /**
1111          * Adds raw decoded data from the given handler instance to this receiver
1112          *
1113          * @param       $handlerInstance        An instance of a Networkable class
1114          * @return      void
1115          */
1116         public function addRawDataToIncomingStack (Networkable $handlerInstance) {
1117                 /*
1118                  * Get the decoded data from the handler, this is an array with
1119                  * 'raw_data' and 'error_code' as elements.
1120                  */
1121                 $decodedData = $handlerInstance->getNextRawData();
1122
1123                 // Very noisy debug message:
1124                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
1125
1126                 // And push it on our stack
1127                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
1128         }
1129
1130         /**
1131          * Checks whether incoming decoded data is handled.
1132          *
1133          * @return      $isHandled      Whether incoming decoded data is handled
1134          */
1135         public function isIncomingRawDataHandled () {
1136                 // Determine if the stack is not empty
1137                 $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
1138
1139                 // Return it
1140                 return $isHandled;
1141         }
1142
1143         /**
1144          * Checks whether the assembler has pending data left
1145          *
1146          * @return      $isHandled      Whether the assembler has pending data left
1147          */
1148         public function ifAssemblerHasPendingDataLeft () {
1149                 // Determine if the stack is not empty
1150                 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
1151
1152                 // Return it
1153                 return $isHandled;
1154         }
1155
1156         /**
1157          * Checks whether the assembler has multiple packages pending
1158          *
1159          * @return      $isPending      Whether the assembler has multiple packages pending
1160          */
1161         public function ifMultipleMessagesPending () {
1162                 // Determine if the stack is not empty
1163                 $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
1164
1165                 // Return it
1166                 return $isPending;
1167         }
1168
1169         /**
1170          * Handles the attached assemler's pending data queue to be finally
1171          * assembled to the raw package data back.
1172          *
1173          * @return      void
1174          */
1175         public function handleAssemblerPendingData () {
1176                 // Handle it
1177                 $this->getAssemblerInstance()->handlePendingData();
1178         }
1179
1180         /**
1181          * Handles multiple messages.
1182          *
1183          * @return      void
1184          */
1185         public function handleMultipleMessages () {
1186                 // Handle it
1187                 $this->getAssemblerInstance()->handleMultipleMessages();
1188         }
1189
1190         /**
1191          * Assembles incoming decoded data so it will become an abstract network
1192          * package again. The assembler does later do it's job by an other task,
1193          * not this one to keep best speed possible.
1194          *
1195          * @return      void
1196          */
1197         public function assembleDecodedDataToPackage () {
1198                 // Make sure the raw decoded package data is handled
1199                 assert($this->isIncomingRawDataHandled());
1200
1201                 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
1202                 $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
1203
1204                 // Assert on some elements
1205                 assert(
1206                         (is_array($packageContent)) &&
1207                         (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1208                         (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1209                 );
1210
1211                 // Start assembling the raw package data array by chunking it
1212                 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
1213
1214                 // Remove the package from 'handled_decoded' stack ...
1215                 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
1216
1217                 // ... and push it on the 'chunked' stacker
1218                 //* 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));
1219                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
1220         }
1221
1222         /**
1223          * Accepts the visitor to process the visit "request"
1224          *
1225          * @param       $visitorInstance        An instance of a Visitor class
1226          * @return      void
1227          */
1228         public function accept (Visitor $visitorInstance) {
1229                 // Debug message
1230                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
1231
1232                 // Visit the package
1233                 $visitorInstance->visitNetworkPackage($this);
1234
1235                 // Then visit the assembler to handle multiple packages
1236                 $this->getAssemblerInstance()->accept($visitorInstance);
1237
1238                 // Debug message
1239                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
1240         }
1241
1242         /**
1243          * Clears all stacks
1244          *
1245          * @return      void
1246          */
1247         public function clearAllStacks () {
1248                 // Call the init method to force re-initialization
1249                 $this->initStacks(TRUE);
1250
1251                 // Debug message
1252                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
1253         }
1254
1255         /**
1256          * Removes the first failed outoging package from the stack to continue
1257          * with next one (it will never work until the issue is fixed by you).
1258          *
1259          * @return      void
1260          * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
1261          * @todo        This may be enchanced for outgoing packages?
1262          */
1263         public function removeFirstFailedPackage () {
1264                 // Get the package again
1265                 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
1266
1267                 // Is the package status 'failed'?
1268                 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
1269                         // Not failed!
1270                         throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
1271                 } // END - if
1272
1273                 // Remove this entry
1274                 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
1275         }
1276
1277         /**
1278          * "Decode" the package content into the same array when it was sent.
1279          *
1280          * @param       $rawPackageContent      The raw package content to be "decoded"
1281          * @return      $decodedData            An array with 'sender', 'recipient', 'content' and 'status' elements
1282          */
1283         public function decodeRawContent ($rawPackageContent) {
1284                 // Use the separator '#' to "decode" it
1285                 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1286
1287                 // Assert on count (should be always 3)
1288                 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1289
1290                 /*
1291                  * Create 'decodedData' array with all assoziative array elements.
1292                  */
1293                 $decodedData = array(
1294                         self::PACKAGE_DATA_SENDER           => $decodedArray[self::INDEX_PACKAGE_SENDER],
1295                         self::PACKAGE_DATA_RECIPIENT        => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
1296                         self::PACKAGE_DATA_CONTENT          => $decodedArray[self::INDEX_PACKAGE_CONTENT],
1297                         self::PACKAGE_DATA_STATUS           => self::PACKAGE_STATUS_DECODED,
1298                         self::PACKAGE_DATA_HASH             => $decodedArray[self::INDEX_PACKAGE_HASH],
1299                         self::PACKAGE_DATA_PRIVATE_KEY_HASH => $decodedArray[self::INDEX_PACKAGE_PRIVATE_KEY_HASH]
1300                 );
1301
1302                 // And return it
1303                 return $decodedData;
1304         }
1305
1306         /**
1307          * Handles decoded data for this node by "decoding" the 'content' part of
1308          * it. Again this method uses explode() for the "decoding" process.
1309          *
1310          * @param       $decodedData    An array with decoded raw package data
1311          * @return      void
1312          * @throws      InvalidDataChecksumException    If the checksum doesn't match
1313          */
1314         public function handleRawData (array $decodedData) {
1315                 /*
1316                  * "Decode" the package's content by a simple explode() call, for
1317                  * details of the array elements, see comments for constant
1318                  * PACKAGE_MASK.
1319                  */
1320                 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1321
1322                 // Assert on array count for a very basic validation
1323                 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1324
1325                 /*
1326                  * Convert the indexed array into an associative array. This is much
1327                  * better to remember than plain numbers, isn't it?
1328                  */
1329                 $decodedContent = array(
1330                         // Compressor's extension used to compress the data
1331                         self::PACKAGE_CONTENT_EXTENSION        => $decodedContent[self::INDEX_COMPRESSOR_EXTENSION],
1332                         // Package data (aka "message") in BASE64-decoded form but still compressed
1333                         self::PACKAGE_CONTENT_MESSAGE          => base64_decode($decodedContent[self::INDEX_PACKAGE_DATA]),
1334                         // Tags as an indexed array for "tagging" the message
1335                         self::PACKAGE_CONTENT_TAGS             => explode(self::PACKAGE_TAGS_SEPARATOR, $decodedContent[self::INDEX_TAGS]),
1336                         // Checksum of the _decoded_ data
1337                         self::PACKAGE_CONTENT_CHECKSUM         => $decodedContent[self::INDEX_CHECKSUM],
1338                         // Sender's id
1339                         self::PACKAGE_CONTENT_SENDER           => $decodedData[self::PACKAGE_DATA_SENDER],
1340                         // Hash from decoded raw data
1341                         self::PACKAGE_CONTENT_HASH             => $decodedData[self::PACKAGE_DATA_HASH],
1342                         // Hash of private key
1343                         self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => $decodedData[self::PACKAGE_DATA_PRIVATE_KEY_HASH]
1344                 );
1345
1346                 // Is the checksum valid?
1347                 if (!$this->isChecksumValid($decodedContent, $decodedData)) {
1348                         // Is not the same, so throw an exception here
1349                         throw new InvalidDataChecksumException(array($this, $decodedContent, $decodedData), BaseListener::EXCEPTION_INVALID_DATA_CHECKSUM);
1350                 } // END - if
1351
1352                 /*
1353                  * The checksum is the same, then it can be decompressed safely. The
1354                  * original message is at this point fully decoded.
1355                  */
1356                 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1357
1358                 // And push it on the next stack
1359                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1360         }
1361
1362         /**
1363          * Checks whether a new message has arrived
1364          *
1365          * @return      $hasArrived             Whether a new message has arrived for processing
1366          */
1367         public function isNewMessageArrived () {
1368                 // Determine if the stack is not empty
1369                 $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1370
1371                 // Return it
1372                 return $hasArrived;
1373         }
1374
1375         /**
1376          * Handles newly arrived messages
1377          *
1378          * @return      void
1379          * @todo        Implement verification of all sent tags here?
1380          */
1381         public function handleNewlyArrivedMessage () {
1382                 // Make sure there is at least one message
1383                 assert($this->isNewMessageArrived());
1384
1385                 // Get it from the stacker, it is the full array with the decoded message
1386                 $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE);
1387
1388                 // Generate the hash of comparing it
1389                 if (!$this->isPackageHashValid($decodedContent)) {
1390                         // Is not valid, so throw an exception here
1391                         exit(__METHOD__ . ':INVALID HASH! UNDER CONSTRUCTION!' . chr(10));
1392                 } // END - if
1393
1394                 // Now get a filter chain back from factory with given tags array
1395                 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1396
1397                 /*
1398                  * Process the message through all filters, note that all other
1399                  * elements from $decodedContent are no longer needed.
1400                  */
1401                 $chainInstance->processMessage($decodedContent, $this);
1402
1403                 /*
1404                  * Post-processing of message data (this won't remove the message from
1405                  * the stack).
1406                  */
1407                 $chainInstance->postProcessMessage($this);
1408         }
1409
1410         /**
1411          * Checks whether a processed message is pending for "interpretation"
1412          *
1413          * @return      $isPending      Whether a processed message is pending
1414          */
1415         public function isProcessedMessagePending () {
1416                 // Check it
1417                 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1418
1419                 // Return it
1420                 return $isPending;
1421         }
1422
1423         /**
1424          * Handle processed messages by "interpreting" the 'message_type' element
1425          *
1426          * @return      void
1427          */
1428         public function handleProcessedMessage () {
1429                 // Get it from the stacker, it is the full array with the processed message
1430                 $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
1431
1432                 // Add type for later easier handling
1433                 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1434
1435                 // Debug message
1436                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1437
1438                 // Create a handler instance from given message type
1439                 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1440
1441                 // Handle message data
1442                 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1443
1444                 // Post-handling of message data
1445                 $handlerInstance->postHandleMessageData($messageArray, $this);
1446         }
1447
1448         /**
1449          * Feeds the hash and sender (as recipient for the 'sender' reward) to the
1450          * miner's queue, unless the message is not a "reward claim" message as this
1451          * leads to an endless loop. You may wish to run the miner to get some
1452          * reward ("Hubcoins") for "mining" this hash.
1453          *
1454          * @param       $messageData    Array with message data
1455          * @return      void
1456          * @todo        ~10% done?
1457          */
1458         public function feedHashToMiner (array $messageData) {
1459                 // Is the feature enabled?
1460                 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
1461                         /*
1462                          * Feature is not enabled, don't feed the hash to the miner as it
1463                          *may be invalid.
1464                          */
1465                         return;
1466                 } // END - if
1467
1468                 // Make sure the required elements are there
1469                 assert(isset($messageData[self::MESSAGE_ARRAY_SENDER]));
1470                 assert(isset($messageData[self::MESSAGE_ARRAY_HASH]));
1471                 assert(isset($messageData[self::MESSAGE_ARRAY_TAGS]));
1472
1473                 // Debug message
1474                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageData=' . print_r($messageData, TRUE));
1475
1476                 // Resolve session id ('sender' is a session id) into node id
1477                 $nodeId = HubTools::resolveNodeIdBySessionId($messageData[self::MESSAGE_ARRAY_SENDER]);
1478
1479                 // Is 'claim_reward' the message type?
1480                 if (in_array('claim_reward', $messageData[self::MESSAGE_ARRAY_TAGS])) {
1481                         /*
1482                          * Then don't feed this message to the miner as this causes an
1483                          * endless loop of mining.
1484                          */
1485                         return;
1486                 } // END - if
1487
1488                 $this->partialStub('@TODO nodeId=' . $nodeId . ',messageData=' . print_r($messageData, TRUE));
1489         }
1490 }
1491
1492 // [EOF]
1493 ?>