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