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