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