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