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