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