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