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