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