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