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