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