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