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