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