]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
4e480d3e492ef000243ac74914ad4dcb12c7269e
[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                 // ... and begin iteration
315                 while ($iteratorInstance->valid()) {
316                         // Get current entry
317                         $currentRecipient = $iteratorInstance->current();
318
319                         // Debug message
320                         $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
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                         // Skip to next entry
329                         $iteratorInstance->next();
330                 } // END - while
331
332                 /*
333                  * The recipient list can be cleaned up here because the package which
334                  * shall be delivered has already been added for all entries from the
335                  * list.
336                  */
337                 $discoveryInstance->clearRecipients();
338         }
339
340         /**
341          * Delivers raw package data. In short, this will discover the raw socket
342          * resource through a discovery class (which will analyse the receipient of
343          * the package), register the socket with the connection (handler/helper?)
344          * instance and finally push the raw data on our outgoing queue.
345          *
346          * @param       $packageData    Raw package data in an array
347          * @return      void
348          */
349         private function deliverRawPackageData (array $packageData) {
350                 /*
351                  * This package may become big, depending on the shared object size or
352                  * delivered message size which shouldn't be so long (to save
353                  * bandwidth). Because of the nature of the used protocol (TCP) we need
354                  * to split it up into smaller pieces to fit it into a TCP frame.
355                  *
356                  * So first we need (again) a discovery class but now a protocol
357                  * discovery to choose the right socket resource. The discovery class
358                  * should take a look at the raw package data itself and then decide
359                  * which (configurable!) protocol should be used for that type of
360                  * package.
361                  */
362                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
363
364                 // Now discover the right protocol
365                 $socketResource = $discoveryInstance->discoverSocket($packageData);
366
367                 // Debug message
368                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
369
370                 // We have to put this socket in our registry, so get an instance
371                 $registryInstance = SocketRegistry::createSocketRegistry();
372
373                 // Get the listener from registry
374                 $helperInstance = Registry::getRegistry()->getInstance('connection');
375
376                 // Debug message
377                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
378
379                 // Is it not there?
380                 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
381                         // Debug message
382                         $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
383
384                         // Then register it
385                         $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
386                 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
387                         // Is not connected, then we cannot send
388                         $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
389
390                         // Shutdown the socket
391                         $this->shutdownSocket($socketResource);
392                 }
393
394                 // Debug message
395                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
396
397                 // Make sure the connection is up
398                 $helperInstance->getStateInstance()->validatePeerStateConnected();
399
400                 // Debug message
401                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
402
403                 // Enqueue it again on the out-going queue, the connection is up and working at this point
404                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
405
406                 // Debug message
407                 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
408         }
409
410         /**
411          * Sends waiting packages
412          *
413          * @param       $packageData    Raw package data
414          * @return      void
415          */
416         private function sendOutgoingRawPackageData (array $packageData) {
417                 // Init sent bytes
418                 $sentBytes = 0;
419
420                 // Get the right connection instance
421                 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
422
423                 // Is this connection still alive?
424                 if ($helperInstance->isShuttedDown()) {
425                         // This connection is shutting down
426                         // @TODO We may want to do somthing more here?
427                         return;
428                 } // END - if
429
430                 // Sent out package data
431                 $sentBytes = $helperInstance->sendRawPackageData($packageData);
432
433                 // Remember unsent raw bytes in back-buffer, if any
434                 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
435         }
436
437         /**
438          * Generates a signature for given raw package content and sender id
439          *
440          * @param       $content        Raw package data
441          * @param       $senderId       Sender id to generate a signature for
442          * @return      $signature      Signature as BASE64-encoded string
443          */
444         private function generatePackageSignature ($content, $senderId) {
445                 // ash content and sender id together, use md5() as last algo
446                 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content));
447
448                 // Encrypt the content again with the hash as a key
449                 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
450
451                 // Encode it with BASE64
452                 $signature = base64_encode($encryptedContent);
453
454                 // Return it
455                 return $signature;
456         }
457
458         /**
459          * "Enqueues" raw content into this delivery class by reading the raw content
460          * from given template instance and pushing it on the 'undeclared' stack.
461          *
462          * @param       $helperInstance         An instance of a HelpableHub class
463          * @param       $nodeInstance           An instance of a NodeHelper class
464          * @return      void
465          */
466         public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, NodeHelper $nodeInstance) {
467                 // Get the raw content ...
468                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
469
470                 // ... and compress it
471                 $content = $this->getCompressorInstance()->compressStream($content);
472
473                 // Add magic in front of it and hash behind it, including BASE64 encoding
474                 $content = sprintf(self::PACKAGE_MASK,
475                         // 1.) Compressor's extension
476                         $this->getCompressorInstance()->getCompressorExtension(),
477                         // - separator
478                         self::PACKAGE_MASK_SEPARATOR,
479                         // 2.) Raw package content, encoded with BASE64
480                         base64_encode($content),
481                         // - separator
482                         self::PACKAGE_MASK_SEPARATOR,
483                         // 3.) Tags
484                         implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
485                         // - separator
486                         self::PACKAGE_MASK_SEPARATOR,
487                         // 4.) Checksum
488                         $this->getHashFromContent($content, $helperInstance, $nodeInstance)
489                 );
490
491                 // Now prepare the temporary array and push it on the 'undeclared' stack
492                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
493                         self::PACKAGE_DATA_SENDER    => $nodeInstance->getSessionId(),
494                         self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
495                         self::PACKAGE_DATA_CONTENT   => $content,
496                         self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_NEW,
497                         self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $nodeInstance->getSessionId())
498                 ));
499         }
500
501         /**
502          * Checks whether a package has been enqueued for delivery.
503          *
504          * @return      $isEnqueued             Whether a package is enqueued
505          */
506         public function isPackageEnqueued () {
507                 // Check whether the stacker is not empty
508                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
509
510                 // Return the result
511                 return $isEnqueued;
512         }
513
514         /**
515          * Checks whether a package has been declared
516          *
517          * @return      $isDeclared             Whether a package is declared
518          */
519         public function isPackageDeclared () {
520                 // Check whether the stacker is not empty
521                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
522
523                 // Return the result
524                 return $isDeclared;
525         }
526
527         /**
528          * Checks whether a package should be sent out
529          *
530          * @return      $isWaitingDelivery      Whether a package is waiting for delivery
531          */
532         public function isPackageWaitingForDelivery () {
533                 // Check whether the stacker is not empty
534                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
535
536                 // Return the result
537                 return $isWaitingDelivery;
538         }
539
540         /**
541          * Delivers an enqueued package to the stated destination. If a non-session
542          * id is provided, recipient resolver is being asked (and instanced once).
543          * This allows that a single package is being delivered to multiple targets
544          * without enqueueing it for every target. If no target is provided or it
545          * can't be determined a NoTargetException is being thrown.
546          *
547          * @return      void
548          * @throws      NoTargetException       If no target can't be determined
549          */
550         public function declareEnqueuedPackage () {
551                 // Make sure this method isn't working if there is no package enqueued
552                 if (!$this->isPackageEnqueued()) {
553                         // This is not fatal but should be avoided
554                         // @TODO Add some logging here
555                         return;
556                 } // END - if
557
558                 // Now we know for sure there are packages to deliver, we can start
559                 // with the first one.
560                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
561
562                 // Declare the raw package data for delivery
563                 $this->declareRawPackageData($packageData);
564
565                 // And remove it finally
566                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
567         }
568
569         /**
570          * Delivers the next declared package. Only one package per time will be sent
571          * because this may take time and slows down the whole delivery
572          * infrastructure.
573          *
574          * @return      void
575          */
576         public function deliverDeclaredPackage () {
577                 // Sanity check if we have packages declared
578                 if (!$this->isPackageDeclared()) {
579                         // This is not fatal but should be avoided
580                         // @TODO Add some logging here
581                         return;
582                 } // END - if
583
584                 // Get the package
585                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
586
587                 try {
588                         // And try to send it
589                         $this->deliverRawPackageData($packageData);
590
591                         // And remove it finally
592                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
593                 } catch (InvalidStateException $e) {
594                         // The state is not excepected (shall be 'connected')
595                         $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
596
597                         // Mark the package with status failed
598                         $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
599                 }
600         }
601
602         /**
603          * Sends waiting packages out for delivery
604          *
605          * @return      void
606          */
607         public function sendWaitingPackage () {
608                 // Send any waiting bytes in the back-buffer before sending a new package
609                 $this->sendBackBufferBytes();
610
611                 // Sanity check if we have packages waiting for delivery
612                 if (!$this->isPackageWaitingForDelivery()) {
613                         // This is not fatal but should be avoided
614                         $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
615                         return;
616                 } // END - if
617
618                 // Get the package
619                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
620
621                 try {
622                         // Now try to send it
623                         $this->sendOutgoingRawPackageData($packageData);
624
625                         // And remove it finally
626                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
627                 } catch (InvalidSocketException $e) {
628                         // Output exception message
629                         $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
630
631                         // Mark package as failed
632                         $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
633                 }
634         }
635
636         ///////////////////////////////////////////////////////////////////////////
637         //                   Receiving packages / raw data
638         ///////////////////////////////////////////////////////////////////////////
639
640         /**
641          * Checks whether decoded raw data is pending
642          *
643          * @return      $isPending      Whether decoded raw data is pending
644          */
645         private function isDecodedDataPending () {
646                 // Just return whether the stack is not empty
647                 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
648
649                 // Return the status
650                 return $isPending;
651         }
652
653         /**
654          * Checks whether new raw package data has arrived at a socket
655          *
656          * @param       $poolInstance   An instance of a PoolableListener class
657          * @return      $hasArrived             Whether new raw package data has arrived for processing
658          */
659         public function isNewRawDataPending (PoolableListener $poolInstance) {
660                 // Visit the pool. This monitors the pool for incoming raw data.
661                 $poolInstance->accept($this->getVisitorInstance());
662
663                 // Check for new data arrival
664                 $hasArrived = $this->isDecodedDataPending();
665
666                 // Return the status
667                 return $hasArrived;
668         }
669
670         /**
671          * Handles the incoming decoded raw data. This method does not "convert" the
672          * decoded data back into a package array, it just "handles" it and pushs it
673          * on the next stack.
674          *
675          * @return      void
676          */
677         public function handleIncomingDecodedData () {
678                 /*
679                  * This method should only be called if decoded raw data is pending,
680                  * so check it again.
681                  */
682                 if (!$this->isDecodedDataPending()) {
683                         // This is not fatal but should be avoided
684                         // @TODO Add some logging here
685                         return;
686                 } // END - if
687
688                 // Very noisy debug message:
689                 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
690
691                 // "Pop" the next entry (the same array again) from the stack
692                 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
693
694                 // Make sure both array elements are there
695                 assert(
696                         (is_array($decodedData)) &&
697                         (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
698                         (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
699                 );
700
701                 /*
702                  * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
703                  * only want to handle unhandled packages here.
704                  */
705                 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
706
707                 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
708                 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
709                         // It is there and should be removed
710                         $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
711                 } // END - if
712
713                 // This package is "handled" and can be pushed on the next stack
714                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
715         }
716
717         /**
718          * Adds raw decoded data from the given handler instance to this receiver
719          *
720          * @param       $handlerInstance        An instance of a Networkable class
721          * @return      void
722          */
723         public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
724                 /*
725                  * Get the decoded data from the handler, this is an array with
726                  * 'decoded_data' and 'error_code' as elements.
727                  */
728                 $decodedData = $handlerInstance->getNextDecodedData();
729
730                 // Very noisy debug message:
731                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
732
733                 // And push it on our stack
734                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
735         }
736
737         /**
738          * Checks whether incoming decoded data is handled.
739          *
740          * @return      $isHandled      Whether incoming decoded data is handled
741          */
742         public function isIncomingDecodedDataHandled () {
743                 // Determine if the stack is not empty
744                 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
745
746                 // Return it
747                 return $isHandled;
748         }
749
750         /**
751          * Assembles incoming decoded data so it will become an abstract network
752          * package again. The assembler does later do it's job by an other task,
753          * not this one to keep best speed possible.
754          *
755          * @return      void
756          */
757         public function assembleDecodedDataToPackage () {
758                 // Make sure the raw decoded package data is handled
759                 assert($this->isIncomingDecodedDataHandled());
760
761                 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
762                 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
763
764                 // Get a singleton package assembler instance from factory
765                 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance();
766
767                 // Start assembling the raw package data array by chunking it
768                 $assemblerInstance->chunkPackageContent($packageContent);
769
770                 // Remove the package from 'handled_decoded' stack ...
771                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
772
773                 // ... and push it on the 'chunked' stacker
774                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
775         }
776
777         /**
778          * Checks whether a new package has arrived
779          *
780          * @return      $hasArrived             Whether a new package has arrived for processing
781          */
782         public function isNewPackageArrived () {
783                 // @TODO Add some content here
784         }
785
786         /**
787          * Accepts the visitor to process the visit "request"
788          *
789          * @param       $visitorInstance        An instance of a Visitor class
790          * @return      void
791          */
792         public function accept (Visitor $visitorInstance) {
793                 // Debug message
794                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
795
796                 // Visit the package
797                 $visitorInstance->visitNetworkPackage($this);
798
799                 // Debug message
800                 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
801         }
802
803         /**
804          * Clears all stacker
805          *
806          * @return      void
807          */
808         public function clearAllStacker () {
809                 // Call the init method to force re-initialization
810                 $this->initStackers(true);
811
812                 // Debug message
813                 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
814         }
815
816         /**
817          * Removes the first failed outoging package from the stack to continue
818          * with next one (it will never work until the issue is fixed by you).
819          *
820          * @return      void
821          * @throws      UnexpectedPackageStatusException        If the package status is not 'failed'
822          * @todo        This may be enchanced for outgoing packages?
823          */
824         public function removeFirstFailedPackage () {
825                 // Get the package again
826                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
827
828                 // Is the package status 'failed'?
829                 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
830                         // Not failed!
831                         throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
832                 } // END - if
833
834                 // Remove this entry
835                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
836         }
837
838         /**
839          * "Decode" the package content into the same array when it was sent.
840          *
841          * @param       $rawPackageContent      The raw package content to be "decoded"
842          * @return      $decodedData            An array with 'sender', 'recipient', 'content' and 'status' elements
843          */
844         public function decodeRawContent ($rawPackageContent) {
845                 // Use the separator '#' to "decode" it
846                 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
847
848                 // Assert on count (should be always 3)
849                 assert(count($decodedArray) == 3);
850
851                 // Create 'decodedData' array with all assoziative array elements
852                 $decodedData = array(
853                         self::PACKAGE_DATA_SENDER    => $decodedArray[self::INDEX_PACKAGE_SENDER],
854                         self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
855                         self::PACKAGE_DATA_CONTENT   => $decodedArray[self::INDEX_PACKAGE_CONTENT],
856                         self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_DECODED,
857                         self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER])
858                 );
859
860                 // And return it
861                 return $decodedData;
862         }
863 }
864
865 // [EOF]
866 ?>