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