]> git.mxchange.org Git - hub.git/blob - application/hub/classes/package/class_NetworkPackage.php
Added really lame script to update copyright year.
[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         const MESSAGE_ARRAY_DATA_NODE_ID = 'node-id';
126
127         /**
128          * Generic answer status field
129          */
130
131         /**
132          * Tags separator
133          */
134         const PACKAGE_TAGS_SEPARATOR = ';';
135
136         /**
137          * Raw package data separator
138          */
139         const PACKAGE_DATA_SEPARATOR = '#';
140
141         /**
142          * Separator for more than one recipient
143          */
144         const PACKAGE_RECIPIENT_SEPARATOR = ':';
145
146         /**
147          * Network target (alias): 'upper nodes'
148          */
149         const NETWORK_TARGET_UPPER = 'upper';
150
151         /**
152          * Network target (alias): 'self'
153          */
154         const NETWORK_TARGET_SELF = 'self';
155
156         /**
157          * Network target (alias): 'dht'
158          */
159         const NETWORK_TARGET_DHT = 'dht';
160
161         /**
162          * TCP package size in bytes
163          */
164         const TCP_PACKAGE_SIZE = 512;
165
166         /**************************************************************************
167          *                    Stacker for out-going packages                      *
168          **************************************************************************/
169
170         /**
171          * Stacker name for "undeclared" packages
172          */
173         const STACKER_NAME_UNDECLARED = 'package_undeclared';
174
175         /**
176          * Stacker name for "declared" packages (which are ready to send out)
177          */
178         const STACKER_NAME_DECLARED = 'package_declared';
179
180         /**
181          * Stacker name for "out-going" packages
182          */
183         const STACKER_NAME_OUTGOING = 'package_outgoing';
184
185         /**************************************************************************
186          *                     Stacker for incoming packages                      *
187          **************************************************************************/
188
189         /**
190          * Stacker name for "incoming" decoded raw data
191          */
192         const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
193
194         /**
195          * Stacker name for handled decoded raw data
196          */
197         const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
198
199         /**
200          * Stacker name for "chunked" decoded raw data
201          */
202         const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
203
204         /**************************************************************************
205          *                     Stacker for incoming messages                      *
206          **************************************************************************/
207
208         /**
209          * Stacker name for new messages
210          */
211         const STACKER_NAME_NEW_MESSAGE = 'package_new_message';
212
213         /**
214          * Stacker name for processed messages
215          */
216         const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message';
217
218         /**************************************************************************
219          *                      Stacker for raw data handling                     *
220          **************************************************************************/
221
222         /**
223          * Stacker for outgoing data stream
224          */
225         const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream';
226
227         /**
228          * Array index for final hash
229          */
230         const RAW_FINAL_HASH_INDEX = 'hash';
231
232         /**
233          * Array index for encoded data
234          */
235         const RAW_ENCODED_DATA_INDEX = 'data';
236
237         /**
238          * Array index for sent bytes
239          */
240         const RAW_SENT_BYTES_INDEX = 'sent';
241
242         /**
243          * Array index for socket resource
244          */
245         const RAW_SOCKET_INDEX = 'socket';
246
247         /**
248          * Array index for buffer size
249          */
250         const RAW_BUFFER_SIZE_INDEX = 'buffer';
251
252         /**
253          * Array index for diff between buffer and sent bytes
254          */
255         const RAW_DIFF_INDEX = 'diff';
256
257         /**************************************************************************
258          *                            Protocol names                              *
259          **************************************************************************/
260         const PROTOCOL_TCP = 'TCP';
261         const PROTOCOL_UDP = 'UDP';
262
263         /**
264          * Protected constructor
265          *
266          * @return      void
267          */
268         protected function __construct () {
269                 // Call parent constructor
270                 parent::__construct(__CLASS__);
271         }
272
273         /**
274          * Creates an instance of this class
275          *
276          * @param       $compressorInstance             A Compressor instance for compressing the content
277          * @return      $packageInstance                An instance of a Deliverable class
278          */
279         public static final function createNetworkPackage (Compressor $compressorInstance) {
280                 // Get new instance
281                 $packageInstance = new NetworkPackage();
282
283                 // Now set the compressor instance
284                 $packageInstance->setCompressorInstance($compressorInstance);
285
286                 /*
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.
290                  */
291                 $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
292
293                 // At last, set it in this class
294                 $packageInstance->setStackInstance($stackInstance);
295
296                 // Init all stacker
297                 $packageInstance->initStacks();
298
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);
302
303                 // Get crypto instance and set it, too
304                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
305                 $packageInstance->setCryptoInstance($cryptoInstance);
306
307                 // Get a singleton package assembler instance from factory and set it here, too
308                 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
309                 $packageInstance->setAssemblerInstance($assemblerInstance);
310
311                 // Get node instance
312                 $nodeInstance = NodeObjectFactory::createNodeInstance();
313
314                 // Get pool instance from node
315                 $poolInstance = $nodeInstance->getListenerPoolInstance();
316
317                 // And set it here
318                 $packageInstance->setListenerPoolInstance($poolInstance);
319
320                 // Return the prepared instance
321                 return $packageInstance;
322         }
323
324         /**
325          * Initialize all stackers
326          *
327          * @param       $forceReInit    Whether to force reinitialization of all stacks
328          * @return      void
329          */
330         protected function initStacks ($forceReInit = FALSE) {
331                 // Initialize all
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
342                 ), $forceReInit);
343         }
344
345         /**
346          * Determines private key hash from given session id
347          *
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
351          */
352         private function determineSenderPrivateKeyHash (array $decodedData) {
353                 // Get DHT instance
354                 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
355
356                 // Ask DHT for session id
357                 $senderData = $dhtInstance->findNodeLocalBySessionId($decodedData[self::PACKAGE_CONTENT_SENDER]);
358
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]));
364
365                         // Don't accept empty hashes
366                         if (empty($senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH])) {
367                                 // Don't accept
368                                 throw new InvalidPrivateKeyHashException(array($this, $senderData, 'empty hash in senderData'), self::EXCEPTION_INVALID_PRIVATE_KEY_HASH);
369                         } // END - if
370
371                         // Return it
372                         return $senderData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_PRIVATE_KEY_HASH];
373                 } // END - if
374
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]));
378
379                 // Don't accept empty keys
380                 if (empty($decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH])) {
381                         // This needs fixing
382                         throw new InvalidPrivateKeyHashException(array($this, $senderData, 'empty hash in decodedData'), self::EXCEPTION_INVALID_PRIVATE_KEY_HASH);
383                 } // END - if
384
385                 // There is no DHT entry so, accept the hash from decoded data
386                 return $decodedData[self::PACKAGE_CONTENT_PRIVATE_KEY_HASH];
387         }
388
389         /**
390          * "Getter" for hash from given content
391          *
392          * @param       $content        Raw package content
393          * @return      $hash           Hash for given package content
394          */
395         private function getHashFromContent ($content) {
396                 // Debug message
397                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
398
399                 // Create the hash
400                 // @TODO md5() is very weak, but it needs to be fast
401                 $hash = md5(
402                         $content .
403                         self::PACKAGE_CHECKSUM_SEPARATOR .
404                         $this->getSessionId() .
405                         self::PACKAGE_CHECKSUM_SEPARATOR .
406                         $this->getCompressorInstance()->getCompressorExtension()
407                 );
408
409                 // Debug message
410                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
411
412                 // And return it
413                 return $hash;
414         }
415
416         /**
417          * Checks whether the checksum (sometimes called "hash") is the same
418          *
419          * @param       $decodedContent         Package raw content
420          * @param       $decodedData            Whole raw package data array
421          * @return      $isChecksumValid        Whether the checksum is the same
422          */
423         private function isChecksumValid (array $decodedContent, array $decodedData) {
424                 // Get checksum
425                 $checksum = $this->getHashFromContentSessionId($decodedContent, $decodedData[self::PACKAGE_DATA_SENDER]);
426
427                 // Is it the same?
428                 $isChecksumValid = ($checksum == $decodedContent[self::PACKAGE_CONTENT_CHECKSUM]);
429
430                 // Return it
431                 return $isChecksumValid;
432         }
433
434         /**
435          * Change the package with given status in given stack
436          *
437          * @param       $packageData    Raw package data in an array
438          * @param       $stackerName    Name of the stacker
439          * @param       $newStatus              New status to set
440          * @return      void
441          */
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
446                         return;
447                 } // END - if
448
449                 // Pop the entry (it should be it)
450                 $nextData = $this->getStackInstance()->popNamed($stackerName);
451
452                 // Compare both hashes
453                 assert($nextData[self::PACKAGE_DATA_HASH] == $packageData[self::PACKAGE_DATA_HASH]);
454
455                 // Temporary set the new status
456                 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
457
458                 // And push it again
459                 $this->getStackInstance()->pushNamed($stackerName, $packageData);
460         }
461
462         /**
463          * "Getter" for hash from given content and sender's session id
464          *
465          * @param       $decodedContent         Raw package content
466          * @param       $sessionId                      Session id of the sender
467          * @return      $hash                           Hash for given package content
468          */
469         public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
470                 // Debug message
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]);
472
473                 // Create the hash
474                 // @TODO md5() is very weak, but it needs to be fast
475                 $hash = md5(
476                         $decodedContent[self::PACKAGE_CONTENT_MESSAGE] .
477                         self::PACKAGE_CHECKSUM_SEPARATOR .
478                         $sessionId .
479                         self::PACKAGE_CHECKSUM_SEPARATOR .
480                         $decodedContent[self::PACKAGE_CONTENT_EXTENSION]
481                 );
482
483                 // And return it
484                 return $hash;
485         }
486
487         ///////////////////////////////////////////////////////////////////////////
488         //                   Delivering packages / raw data
489         ///////////////////////////////////////////////////////////////////////////
490
491         /**
492          * Declares the given raw package data by discovering recipients
493          *
494          * @param       $packageData    Raw package data in an array
495          * @return      void
496          */
497         private function declareRawPackageData (array $packageData) {
498                 // Make sure the required field is there
499                 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
500
501                 /*
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.
506                  */
507                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
508
509                 // Discover all recipients, this may throw an exception
510                 $discoveryInstance->discoverRecipients($packageData);
511
512                 // Now get an iterator
513                 $iteratorInstance = $discoveryInstance->getIterator();
514
515                 // Make sure the iterator instance is valid
516                 assert($iteratorInstance instanceof Iterator);
517
518                 // Rewind back to the beginning
519                 $iteratorInstance->rewind();
520
521                 // ... and begin iteration
522                 while ($iteratorInstance->valid()) {
523                         // Get current entry
524                         $currentRecipient = $iteratorInstance->current();
525
526                         // Debug message
527                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
528
529                         // Set the recipient
530                         $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
531
532                         // Push the declared package to the next stack.
533                         $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
534
535                         // Debug message
536                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
537
538                         // Skip to next entry
539                         $iteratorInstance->next();
540                 } // END - while
541
542                 /*
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
545                  * list.
546                  */
547                 $discoveryInstance->clearRecipients();
548         }
549
550         /**
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.
555          *
556          * @param       $packageData    Raw package data in an array
557          * @return      void
558          */
559         private function deliverRawPackageData (array $packageData) {
560                 /*
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.
565                  *
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
570                  * package.
571                  */
572                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
573
574                 // Now discover the right protocol
575                 $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
576
577                 // Debug message
578                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
579
580                 // Debug message
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.');
583
584                 // The socket needs to be put in a special registry that can handle such data
585                 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
586
587                 // Get the connection helper from registry
588                 $helperInstance = Registry::getRegistry()->getInstance('connection');
589
590                 // And make sure it is valid
591                 assert($helperInstance instanceof ConnectionHelper);
592
593                 // Get connection info class
594                 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($helperInstance->getProtocolName(), 'helper');
595
596                 // Will the info instance with connection helper data
597                 $infoInstance->fillWithConnectionHelperInformation($helperInstance);
598
599                 // Is it not there?
600                 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($infoInstance, $socketResource))) {
601                         // Debug message
602                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
603
604                         // Then register it
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.');
609
610                         // Shutdown the socket
611                         $this->shutdownSocket($socketResource);
612                 }
613
614                 // Debug message
615                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
616
617                 // Make sure the connection is up
618                 $helperInstance->getStateInstance()->validatePeerStateConnected();
619
620                 // Debug message
621                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
622
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);
625
626                 // Debug message
627                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
628         }
629
630         /**
631          * Sends waiting packages
632          *
633          * @param       $packageData    Raw package data
634          * @return      void
635          */
636         private function sendOutgoingRawPackageData (array $packageData) {
637                 // Init sent bytes
638                 $sentBytes = 0;
639
640                 // Get the right connection instance
641                 $infoInstance = SocketRegistryFactory::createSocketRegistryInstance()->getInfoInstanceFromPackageData($packageData);
642
643                 // Test helper instance
644                 assert($infoInstance instanceof ShareableInfo);
645
646                 // Get helper instance
647                 $helperInstance = $infoInstance->getHelperInstance();
648
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());
653
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?
658                         return;
659                 } // END - if
660
661                 // Sent out package data
662                 $helperInstance->sendRawPackageData($packageData);
663         }
664
665         /**
666          * Generates a secure hash for given raw package content and sender id
667          *
668          * @param       $content        Raw package data
669          * @param       $senderId       Sender id to generate a hash for
670          * @return      $hash           Hash as hex-encoded string
671          */
672         private function generatePackageHash ($content, $senderId) {
673                 // Debug message
674                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content()=' . strlen($content) . ',senderId=' . $senderId . ' - CALLED!');
675
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 ...');
680                         return NULL;
681                 } // END - if
682
683                 // Fake array
684                 $data = array(
685                         self::PACKAGE_CONTENT_SENDER           => $senderId,
686                         self::PACKAGE_CONTENT_MESSAGE          => $content,
687                         self::PACKAGE_CONTENT_PRIVATE_KEY_HASH => ''
688                 );
689         
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)));
693
694                 // Debug message
695                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: hash=' . $hash . ' - EXIT!');
696
697                 // Return it
698                 return $hash;
699         }
700
701         /**
702          * Checks whether the hash of given package data is 'valid', here that
703          * means it is the same or not.
704          *
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
708          */
709         private function isPackageHashValid (array $decodedArray) {
710                 // Debug message
711                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedArray=' . print_r($decodedArray, TRUE) . ' - CALLED!');
712
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]));
718
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 ...');
723                         return TRUE;
724                 } // END - if
725
726                 // Check validity
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]));
730
731                 // Return it
732                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: isHashValid=' . intval($isHashValid) . ' - EXIT!');
733                 return $isHashValid;
734         }
735
736         /**
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'
739          * stack.
740          *
741          * @param       $helperInstance         An instance of a HubHelper class
742          * @return      void
743          */
744         public function enqueueRawDataFromTemplate (HubHelper $helperInstance) {
745                 // Debug message
746                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
747
748                 // Get the raw content ...
749                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
750                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
751
752                 // ... and compress it
753                 $compressed = $this->getCompressorInstance()->compressStream($content);
754
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(),
759                         // - separator
760                         self::PACKAGE_MASK_SEPARATOR,
761                         // 2.) Compressed raw package content, encoded with BASE64
762                         base64_encode($compressed),
763                         // - separator
764                         self::PACKAGE_MASK_SEPARATOR,
765                         // 3.) Tags
766                         implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
767                         // - separator
768                         self::PACKAGE_MASK_SEPARATOR,
769                         // 4.) Checksum
770                         $this->getHashFromContent($compressed)
771                 );
772
773                 // Debug message
774                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': Enqueueing package for recipientType=' . $helperInstance->getRecipientType() . ' ...');
775
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(),
784                 ));
785
786                 // Debug message
787                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
788         }
789
790         /**
791          * Checks whether a package has been enqueued for delivery.
792          *
793          * @return      $isEnqueued             Whether a package is enqueued
794          */
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)));
798
799                 // Return the result
800                 return $isEnqueued;
801         }
802
803         /**
804          * Checks whether a package has been declared
805          *
806          * @return      $isDeclared             Whether a package is declared
807          */
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)));
811
812                 // Return the result
813                 return $isDeclared;
814         }
815
816         /**
817          * Checks whether a package should be sent out
818          *
819          * @return      $isWaitingDelivery      Whether a package is waiting for delivery
820          */
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)));
824
825                 // Return the result
826                 return $isWaitingDelivery;
827         }
828
829         /**
830          * Checks whether encoded (raw) data is pending
831          *
832          * @return      $isPending              Whether encoded data is pending
833          */
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)));
837
838                 // Return the result
839                 return $isPending;
840         }
841
842         /**
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.
848          *
849          * @return      void
850          * @throws      NoTargetException       If no target can't be determined
851          */
852         public function declareEnqueuedPackage () {
853                 // Debug message
854                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
855
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!');
860                         return;
861                 } // END - if
862
863                 /*
864                  * Now there are for sure packages to deliver, so start with the first
865                  * one.
866                  */
867                 $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
868
869                 // Declare the raw package data for delivery
870                 $this->declareRawPackageData($packageData);
871
872                 // Debug message
873                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
874         }
875
876         /**
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
879          * infrastructure.
880          *
881          * @return      void
882          */
883         public function processDeclaredPackage () {
884                 // Debug message
885                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
886
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!');
891                         return;
892                 } // END - if
893
894                 // Get the package
895                 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
896
897                 // Assert on it
898                 assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
899
900                 // Try to deliver the package
901                 try {
902                         // And try to send it
903                         $this->deliverRawPackageData($packageData);
904
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());
910
911                         // Mark the package with status failed
912                         $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
913                 }
914
915                 // Debug message
916                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
917         }
918
919         /**
920          * Sends waiting packages out for delivery
921          *
922          * @return      void
923          */
924         public function sendWaitingPackage () {
925                 // Debug message
926                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
927
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.');
932                         return;
933                 } // END - if
934
935                 // Get the package
936                 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING);
937
938                 try {
939                         // Now try to send it
940                         $this->sendOutgoingRawPackageData($packageData);
941
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());
947
948                         // Mark package as failed
949                         $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
950                 }
951
952                 // Debug message
953                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
954         }
955
956         /**
957          * Sends out encoded data to a socket
958          *
959          * @return      void
960          */
961         public function sendEncodedData () {
962                 // Debug message
963                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': CALLED!');
964
965                 // Make sure there is pending encoded data
966                 assert($this->isEncodedDataPending());
967
968                 // Pop current data from stack
969                 $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM);
970
971                 // Init in this round sent bytes
972                 $sentBytes = 0;
973
974                 // Assert on socket
975                 assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX]));
976
977                 // And deliver it
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]));
983                 } else {
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]);
987                 }
988
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'));
993
994                         // And throw it
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__ . ')');
999                         return;
1000                 } else {
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);
1003
1004                         // Add total sent bytes
1005                         $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes;
1006
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);
1010
1011                         // Calculate difference again
1012                         $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]);
1013
1014                         // Can we abort?
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__ . ')');
1018                                 return;
1019                         } // END - if
1020                 }
1021
1022                 // Push array back in stack
1023                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
1024
1025                 // Debug message
1026                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ': EXIT!');
1027         }
1028
1029         ///////////////////////////////////////////////////////////////////////////
1030         //                   Receiving packages / raw data
1031         ///////////////////////////////////////////////////////////////////////////
1032
1033         /**
1034          * Checks whether decoded raw data is pending
1035          *
1036          * @return      $isPending      Whether decoded raw data is pending
1037          */
1038         private function isRawDataPending () {
1039                 // Just return whether the stack is not empty
1040                 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
1041
1042                 // Return the status
1043                 return $isPending;
1044         }
1045
1046         /**
1047          * Checks whether new raw package data has arrived at a socket
1048          *
1049          * @return      $hasArrived             Whether new raw package data has arrived for processing
1050          */
1051         public function isNewRawDataPending () {
1052                 // Visit the pool. This monitors the pool for incoming raw data.
1053                 $this->getListenerPoolInstance()->accept($this->getVisitorInstance());
1054
1055                 // Check for new data arrival
1056                 $hasArrived = $this->isRawDataPending();
1057
1058                 // Return the status
1059                 return $hasArrived;
1060         }
1061
1062         /**
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.
1066          *
1067          * @return      void
1068          */
1069         public function handleIncomingDecodedData () {
1070                 /*
1071                  * This method should only be called if decoded raw data is pending,
1072                  * so check it again.
1073                  */
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!');
1077                         return;
1078                 } // END - if
1079
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.');
1082
1083                 // "Pop" the next entry (the same array again) from the stack
1084                 $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
1085
1086                 // Make sure both array elements are there
1087                 assert(
1088                         (is_array($decodedData)) &&
1089                         (isset($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1090                         (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1091                 );
1092
1093                 /*
1094                  * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
1095                  * only want to handle unhandled packages here.
1096                  */
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);
1099
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);
1104                 } // END - if
1105
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);
1109         }
1110
1111         /**
1112          * Adds raw decoded data from the given handler instance to this receiver
1113          *
1114          * @param       $handlerInstance        An instance of a Networkable class
1115          * @return      void
1116          */
1117         public function addRawDataToIncomingStack (Networkable $handlerInstance) {
1118                 /*
1119                  * Get the decoded data from the handler, this is an array with
1120                  * 'raw_data' and 'error_code' as elements.
1121                  */
1122                 $decodedData = $handlerInstance->getNextRawData();
1123
1124                 // Very noisy debug message:
1125                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE));
1126
1127                 // And push it on our stack
1128                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
1129         }
1130
1131         /**
1132          * Checks whether incoming decoded data is handled.
1133          *
1134          * @return      $isHandled      Whether incoming decoded data is handled
1135          */
1136         public function isIncomingRawDataHandled () {
1137                 // Determine if the stack is not empty
1138                 $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
1139
1140                 // Return it
1141                 return $isHandled;
1142         }
1143
1144         /**
1145          * Checks whether the assembler has pending data left
1146          *
1147          * @return      $isHandled      Whether the assembler has pending data left
1148          */
1149         public function ifAssemblerHasPendingDataLeft () {
1150                 // Determine if the stack is not empty
1151                 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
1152
1153                 // Return it
1154                 return $isHandled;
1155         }
1156
1157         /**
1158          * Checks whether the assembler has multiple packages pending
1159          *
1160          * @return      $isPending      Whether the assembler has multiple packages pending
1161          */
1162         public function ifMultipleMessagesPending () {
1163                 // Determine if the stack is not empty
1164                 $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending());
1165
1166                 // Return it
1167                 return $isPending;
1168         }
1169
1170         /**
1171          * Handles the attached assemler's pending data queue to be finally
1172          * assembled to the raw package data back.
1173          *
1174          * @return      void
1175          */
1176         public function handleAssemblerPendingData () {
1177                 // Handle it
1178                 $this->getAssemblerInstance()->handlePendingData();
1179         }
1180
1181         /**
1182          * Handles multiple messages.
1183          *
1184          * @return      void
1185          */
1186         public function handleMultipleMessages () {
1187                 // Handle it
1188                 $this->getAssemblerInstance()->handleMultipleMessages();
1189         }
1190
1191         /**
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.
1195          *
1196          * @return      void
1197          */
1198         public function assembleDecodedDataToPackage () {
1199                 // Make sure the raw decoded package data is handled
1200                 assert($this->isIncomingRawDataHandled());
1201
1202                 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
1203                 $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
1204
1205                 // Assert on some elements
1206                 assert(
1207                         (is_array($packageContent)) &&
1208                         (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
1209                         (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
1210                 );
1211
1212                 // Start assembling the raw package data array by chunking it
1213                 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
1214
1215                 // Remove the package from 'handled_decoded' stack ...
1216                 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
1217
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);
1221         }
1222
1223         /**
1224          * Accepts the visitor to process the visit "request"
1225          *
1226          * @param       $visitorInstance        An instance of a Visitor class
1227          * @return      void
1228          */
1229         public function accept (Visitor $visitorInstance) {
1230                 // Debug message
1231                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - CALLED!');
1232
1233                 // Visit the package
1234                 $visitorInstance->visitNetworkPackage($this);
1235
1236                 // Then visit the assembler to handle multiple packages
1237                 $this->getAssemblerInstance()->accept($visitorInstance);
1238
1239                 // Debug message
1240                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - EXIT!');
1241         }
1242
1243         /**
1244          * Clears all stacks
1245          *
1246          * @return      void
1247          */
1248         public function clearAllStacks () {
1249                 // Call the init method to force re-initialization
1250                 $this->initStacks(TRUE);
1251
1252                 // Debug message
1253                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.');
1254         }
1255
1256         /**
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).
1259          *
1260          * @return      void
1261          * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
1262          * @todo        This may be enchanced for outgoing packages?
1263          */
1264         public function removeFirstFailedPackage () {
1265                 // Get the package again
1266                 $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED);
1267
1268                 // Is the package status 'failed'?
1269                 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
1270                         // Not failed!
1271                         throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
1272                 } // END - if
1273
1274                 // Remove this entry
1275                 $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED);
1276         }
1277
1278         /**
1279          * "Decode" the package content into the same array when it was sent.
1280          *
1281          * @param       $rawPackageContent      The raw package content to be "decoded"
1282          * @return      $decodedData            An array with 'sender', 'recipient', 'content' and 'status' elements
1283          */
1284         public function decodeRawContent ($rawPackageContent) {
1285                 // Use the separator '#' to "decode" it
1286                 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
1287
1288                 // Assert on count (should be always 3)
1289                 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
1290
1291                 /*
1292                  * Create 'decodedData' array with all assoziative array elements.
1293                  */
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]
1301                 );
1302
1303                 // And return it
1304                 return $decodedData;
1305         }
1306
1307         /**
1308          * Handles decoded data for this node by "decoding" the 'content' part of
1309          * it. Again this method uses explode() for the "decoding" process.
1310          *
1311          * @param       $decodedData    An array with decoded raw package data
1312          * @return      void
1313          * @throws      InvalidDataChecksumException    If the checksum doesn't match
1314          */
1315         public function handleRawData (array $decodedData) {
1316                 /*
1317                  * "Decode" the package's content by a simple explode() call, for
1318                  * details of the array elements, see comments for constant
1319                  * PACKAGE_MASK.
1320                  */
1321                 $decodedContent = explode(self::PACKAGE_MASK_SEPARATOR, $decodedData[self::PACKAGE_DATA_CONTENT]);
1322
1323                 // Assert on array count for a very basic validation
1324                 assert(count($decodedContent) == self::PACKAGE_CONTENT_ARRAY_SIZE);
1325
1326                 /*
1327                  * Convert the indexed array into an associative array. This is much
1328                  * better to remember than plain numbers, isn't it?
1329                  */
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],
1339                         // Sender's id
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]
1345                 );
1346
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);
1351                 } // END - if
1352
1353                 /*
1354                  * The checksum is the same, then it can be decompressed safely. The
1355                  * original message is at this point fully decoded.
1356                  */
1357                 $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]);
1358
1359                 // And push it on the next stack
1360                 $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent);
1361         }
1362
1363         /**
1364          * Checks whether a new message has arrived
1365          *
1366          * @return      $hasArrived             Whether a new message has arrived for processing
1367          */
1368         public function isNewMessageArrived () {
1369                 // Determine if the stack is not empty
1370                 $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE));
1371
1372                 // Return it
1373                 return $hasArrived;
1374         }
1375
1376         /**
1377          * Handles newly arrived messages
1378          *
1379          * @return      void
1380          * @todo        Implement verification of all sent tags here?
1381          */
1382         public function handleNewlyArrivedMessage () {
1383                 // Make sure there is at least one message
1384                 assert($this->isNewMessageArrived());
1385
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);
1388
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));
1393                 } // END - if
1394
1395                 // Now get a filter chain back from factory with given tags array
1396                 $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]);
1397
1398                 /*
1399                  * Process the message through all filters, note that all other
1400                  * elements from $decodedContent are no longer needed.
1401                  */
1402                 $chainInstance->processMessage($decodedContent, $this);
1403
1404                 /*
1405                  * Post-processing of message data (this won't remove the message from
1406                  * the stack).
1407                  */
1408                 $chainInstance->postProcessMessage($this);
1409         }
1410
1411         /**
1412          * Checks whether a processed message is pending for "interpretation"
1413          *
1414          * @return      $isPending      Whether a processed message is pending
1415          */
1416         public function isProcessedMessagePending () {
1417                 // Check it
1418                 $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE));
1419
1420                 // Return it
1421                 return $isPending;
1422         }
1423
1424         /**
1425          * Handle processed messages by "interpreting" the 'message_type' element
1426          *
1427          * @return      void
1428          */
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);
1432
1433                 // Add type for later easier handling
1434                 $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
1435
1436                 // Debug message
1437                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE));
1438
1439                 // Create a handler instance from given message type
1440                 $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
1441
1442                 // Handle message data
1443                 $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
1444
1445                 // Post-handling of message data
1446                 $handlerInstance->postHandleMessageData($messageArray, $this);
1447         }
1448
1449         /**
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.
1454          *
1455          * @param       $messageData    Array with message data
1456          * @return      void
1457          * @todo        ~10% done?
1458          */
1459         public function feedHashToMiner (array $messageData) {
1460                 // Is the feature enabled?
1461                 if (!FrameworkFeature::isFeatureAvailable('hubcoin_reward')) {
1462                         /*
1463                          * Feature is not enabled, don't feed the hash to the miner as it
1464                          *may be invalid.
1465                          */
1466                         return;
1467                 } // END - if
1468
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]));
1473
1474                 // Copy node id
1475                 $messageData[self::MESSAGE_ARRAY_DATA_NODE_ID] = $messageData[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_DATA_NODE_ID];
1476
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]);
1480
1481                 // Debug message
1482                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageData=' . print_r($messageData, TRUE));
1483
1484                 // Resolve session id ('sender' is a session id) into node id
1485                 $nodeId = HubTools::resolveNodeIdBySessionId($messageData[self::MESSAGE_ARRAY_SENDER]);
1486
1487                 // Is 'claim_reward' the message type?
1488                 if (in_array(BaseTag::TAG_CLAIM_MINING_REWARD, $messageData[self::MESSAGE_ARRAY_TAGS])) {
1489                         /*
1490                          * Then don't feed this message to the miner as this causes an
1491                          * endless loop of mining.
1492                          */
1493                         return;
1494                 } // END - if
1495
1496                 // Also remove tags as the miner don't need this.
1497                 unset($messageData[self::MESSAGE_ARRAY_TAGS]);
1498
1499                 $this->partialStub('@TODO nodeId=' . $nodeId . ',messageData=' . print_r($messageData, TRUE));
1500         }
1501 }
1502
1503 // [EOF]
1504 ?>