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