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