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