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