]> git.mxchange.org Git - hub.git/blob - application/hub/main/handler/chunks/class_ChunkHandler.php
Added line numbers to debug lines as this will become the 'norm'
[hub.git] / application / hub / main / handler / chunks / class_ChunkHandler.php
1 <?php
2 /**
3  * A Chunk handler
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24 class ChunkHandler extends BaseHandler implements HandleableChunks, Registerable {
25         /**
26          * Stacker for chunks with final EOP
27          */
28         const STACKER_NAME_CHUNKS_WITH_FINAL_EOP = 'final_chunks';
29         const STACKER_NAME_CHUNKS_WITHOUT_FINAL  = 'pending_chunks';
30         const STACKER_NAME_ASSEMBLED_RAW_DATA    = 'chunk_raw_data';
31
32         /**
33          * Chunk splits:
34          * 0 = Hash
35          * 1 = Serial number
36          * 2 = Raw data
37          */
38         const CHUNK_SPLITS_INDEX_HASH     = 0;
39         const CHUNK_SPLITS_INDEX_SERIAL   = 1;
40         const CHUNK_SPLITS_INDEX_RAW_DATA = 2;
41
42         /**
43          * The final array for assembling the original package back together
44          */
45         private $finalPackageChunks = array();
46
47         /**
48          * Array of chunk hashes
49          */
50         private $chunkHashes = array();
51
52         /**
53          * Raw EOP chunk data in an array:
54          *
55          * 0 = Final hash,
56          * 1 = Hash of last chunk
57          */
58         private $eopChunk = array();
59
60         /**
61          * Raw package data
62          */
63         private $rawPackageData = '';
64
65         /**
66          * Protected constructor
67          *
68          * @return      void
69          */
70         protected function __construct () {
71                 // Call parent constructor
72                 parent::__construct(__CLASS__);
73
74                 // Set handler name
75                 $this->setHandlerName('chunk');
76
77                 // Initialize handler
78                 $this->initHandler();
79         }
80
81         /**
82          * Creates an instance of this class
83          *
84          * @return      $handlerInstance        An instance of a chunk Handler class
85          */
86         public final static function createChunkHandler () {
87                 // Get new instance
88                 $handlerInstance = new ChunkHandler();
89
90                 // Get a FIFO stacker
91                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class');
92
93                 // Init all stacker
94                 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
95                 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITHOUT_FINAL);
96                 $stackerInstance->initStacker(self::STACKER_NAME_ASSEMBLED_RAW_DATA);
97
98                 // Set the stacker in this handler
99                 $handlerInstance->setStackerInstance($stackerInstance);
100
101                 // Get a crypto instance ...
102                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
103
104                 // ... and set it in this handler
105                 $handlerInstance->setCryptoInstance($cryptoInstance);
106
107                 // Get a fragmenter instance for later verification of serial numbers (e.g. if all are received)
108                 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
109
110                 // Set it in this handler
111                 $handlerInstance->setFragmenterInstance($fragmenterInstance);
112
113                 // Return the prepared instance
114                 return $handlerInstance;
115         }
116
117         /**
118          * Initializes the handler
119          *
120          * @return      void
121          */
122         private function initHandler () {
123                 // Init finalPackageChunks
124                 $this->finalPackageChunks = array(
125                         // Array for package content
126                         'content'        => array(),
127                         // ... and for the hashes
128                         'hashes'         => array(),
129                         // ... marker for that the final array is complete for assembling all chunks
130                         'is_complete'    => false,
131                         // ... steps done to assemble all chunks
132                         'assemble_steps' => 0,
133                 );
134
135                 // ... chunkHashes:
136                 $this->chunkHashes = array();
137
138                 // ... eopChunk:
139                 $this->eopChunk = array(
140                         0 => 'INVALID',
141                         1 => 'INVALID',
142                 );
143         }
144
145         /**
146          * Checks whether the hash generated from package content is the same ("valid") as given
147          *
148          * @param       $chunkSplits    An array from a splitted chunk
149          * @return      $isValid                Whether the hash is "valid"
150          */
151         private function isChunkHashValid (array $chunkSplits) {
152                 // Now hash the raw data again
153                 $chunkHash = $this->getCryptoInstance()->hashString($chunkSplits[self::CHUNK_SPLITS_INDEX_RAW_DATA], $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH], false);
154
155                 // Debug output
156                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: chunkHash=' . $chunkHash . ',chunkSplits[chunk_hash]=' . $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] . ',chunkSplits[serial]=' . $chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL] . ',chunkSplits[raw_data]=' . $chunkSplits[self::CHUNK_SPLITS_INDEX_RAW_DATA]);
157
158                 // Check it
159                 $isValid = ($chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] === $chunkHash);
160
161                 // ... and return it
162                 return $isValid;
163         }
164
165         /**
166          * Checks whether the given serial number is valid
167          *
168          * @param       $serialNumber   A serial number from a chunk
169          * @return      $isValid                Whether the serial number is valid
170          */
171         private function isSerialNumberValid ($serialNumber) {
172                 // Check it
173                 $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->hexval($serialNumber, false) === $serialNumber));
174
175                 // Return result
176                 return $isValid;
177         }
178
179         /**
180          * Adds the chunk to the final array which will be used for the final step
181          * which will be to assemble all chunks back to the original package content
182          * and for the final hash check.
183          *
184          * This method may throw an exception if a chunk with the same serial number
185          * has already been added to avoid mixing chunks from different packages.
186          *
187          * @param       $chunkSplits    An array from a splitted chunk
188          * @return      void
189          */
190         private function addChunkToFinalArray (array $chunkSplits) {
191                 // Is the serial number (index 1) already been added?
192                 if (isset($this->finalPackageChunks[$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]])) {
193                         // Then throw an exception
194                         throw new ChunkAlreadyAssembledException(array($this, $chunkSplits), self::EXCEPTION_CHUNK_ALREADY_ASSEMBLED);
195                 } // END - if
196
197                 // Debug message
198                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: serialNumber=' . $chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL] . ',hash=' . $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH]);
199
200                 // Add the chunk data (index 2) to the final array and use the serial number as index
201                 $this->finalPackageChunks['content'][$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]] = $chunkSplits[self::CHUNK_SPLITS_INDEX_RAW_DATA];
202
203                 // ... and the hash as well
204                 $this->finalPackageChunks['hashes'][$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]] = $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH];
205         }
206
207         /**
208          * Marks the final array as completed, do only this if you really have all
209          * chunks together including EOP and "hash chunk".
210          *
211          * @return      void
212          */
213         private function markFinalArrayAsCompleted () {
214                 /*
215                  * As for now, just set the array element. If any further steps are
216                  * being added, this should always be the last step.
217                  */
218                 $this->finalPackageChunks['is_complete'] = true;
219         }
220
221         /**
222          * Sorts the chunks array by using the serial number as a sorting key. In
223          * most situations a call of ksort() is enough to accomblish this. So this
224          * method may only call ksort() on the chunks array.
225          *
226          * This method sorts 'content' and 'hashes' so both must have used the
227          * serial numbers as array indexes.
228          *
229          * @return      void
230          */
231         private function sortChunksArray () {
232                 // Sort 'content' first
233                 ksort($this->finalPackageChunks['content']);
234
235                 // ... then 'hashes'
236                 ksort($this->finalPackageChunks['hashes']);
237         }
238
239         /**
240          * Prepares the package assemble by removing last chunks (last shall be
241          * hash chunk, pre-last shall be EOP chunk) and verify that all serial
242          * numbers are valid (same as PackageFragmenter class would generate).
243          *
244          * @return      void
245          */
246         private function preparePackageAssmble () {
247                 // Make sure both arrays have same count (this however should always be true)
248                 assert(count($this->finalPackageChunks['hashes']) == count($this->finalPackageChunks['content']));
249                 //* DIE: */ exit(__METHOD__ . ':finalPackageChunks='.print_r($this->finalPackageChunks['content'],true));
250
251                 /*
252                  * Remove last element (hash chunk) from 'hashes'. This hash will never
253                  * be needed, so ignore it.
254                  */
255                 array_pop($this->finalPackageChunks['hashes']);
256
257                 // ... and from 'content' as well but save it for later use
258                 $this->chunkHashes = explode(PackageFragmenter::CHUNK_HASH_SEPARATOR, substr(array_pop($this->finalPackageChunks['content']), strlen(PackageFragmenter::HASH_CHUNK_IDENTIFIER)));
259
260                 // Remove EOP chunk and keep a copy of it
261                 array_pop($this->finalPackageChunks['hashes']);
262                 $this->eopChunk = explode(PackageFragmenter::CHUNK_HASH_SEPARATOR, substr(array_pop($this->finalPackageChunks['content']), strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)));
263
264                 // Verify all serial numbers
265                 $this->verifyChunkSerialNumbers();
266         }
267
268         /**
269          * Verifies all chunk serial numbers by using a freshly initialized
270          * fragmenter instance. Do ALWAYS sort the array and array_pop() the hash
271          * chunk before calling this method to avoid re-requests of many chunks.
272          *
273          * @return      void
274          */
275         private function verifyChunkSerialNumbers () {
276                 // Reset the serial number generator
277                 $this->getFragmenterInstance()->resetSerialNumber();
278
279                 // "Walk" through all (content) chunks
280                 foreach ($this->finalPackageChunks['content'] as $serialNumber => $content) {
281                         // Get next serial number
282                         $nextSerial = $this->getFragmenterInstance()->getNextHexSerialNumber();
283
284                         // Debug output
285                         //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: serialNumber=' . $serialNumber . ',nextSerial=' . $nextSerial);
286
287                         // Is it not the same? Then re-request it
288                         if ($serialNumber != $nextSerial) {
289                                 // This is invalid, so remove it
290                                 unset($this->finalPackageChunks['content'][$serialNumber]);
291                                 unset($this->finalPackageChunks['hashes'][$serialNumber]);
292
293                                 // And re-request it with valid serial number (and hash chunk)
294                                 $this->rerequestChunkBySerialNumber($nextSerial);
295                         } // END - if
296                 } // END - foreach
297         }
298
299         /**
300          * Assembles and verifies ("final check") chunks back together to the
301          * original package (raw data for the start). This method should only be
302          * called AFTER the EOP and final-chunk chunk have been removed.
303          *
304          * @return      void
305          */
306         private function assembleAllChunksToPackage () {
307                 // If chunkHashes is not filled, don't continue
308                 assert(count($this->chunkHashes) > 0);
309
310                 // Init raw package data string
311                 $this->rawPackageData = '';
312
313                 // That went well, so start assembling all chunks
314                 foreach ($this->finalPackageChunks['content'] as $serialNumber => $content) {
315                         // Debug message
316                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: serialNumber=' . $serialNumber . ' - validating ...');
317                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('finalPackageChunks=' . print_r($this->finalPackageChunks,true) . 'chunkHashes=' . print_r($this->chunkHashes,true));
318
319                         // Is this chunk valid? This should be the case
320                         assert($this->isChunkHashValid(array(
321                                 self::CHUNK_SPLITS_INDEX_HASH     => $this->finalPackageChunks['hashes'][$serialNumber],
322                                 self::CHUNK_SPLITS_INDEX_RAW_DATA => $content
323                         )));
324
325                         // ... and is also in the hash chunk?
326                         assert(in_array($this->finalPackageChunks['hashes'][$serialNumber], $this->chunkHashes));
327
328                         // Verification okay, add it to the raw data
329                         $this->rawPackageData .= $content;
330                 } // END - foreach
331
332                 // Debug output
333                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: eopChunk[1]=' . $this->eopChunk[1] . ',' . chr(10) . 'index=' . (count($this->chunkHashes) - 2) . ',' . chr(10) . 'chunkHashes='.print_r($this->chunkHashes,true));
334
335                 // The last chunk hash must match with the one from eopChunk[1]
336                 assert($this->eopChunk[1] == $this->chunkHashes[count($this->chunkHashes) - 2]);
337         }
338
339         /**
340          * Verifies the finally assembled raw package data by comparing it against
341          * the final hash.
342          *
343          * @return      void
344          */
345         private function verifyRawPackageData () {
346                 // Hash the raw package data for final verification
347                 $finalHash = $this->getCryptoInstance()->hashString($this->rawPackageData, $this->eopChunk[0], false);
348
349                 // Is it the same?
350                 assert($finalHash == $this->eopChunk[0]);
351         }
352
353         /**
354          * Adds all chunks if the last one verifies as a 'final chunk'.
355          *
356          * @param       $chunks         An array with chunks, the last one should be a 'final'
357          * @return      void
358          * @throws      FinalChunkVerificationException         If the final chunk does not start with 'EOP:'
359          */
360         public function addAllChunksWithFinal (array $chunks) {
361                 // Try to validate the final chunk
362                 try {
363                         // Validate final chunk
364                         $this->isValidFinalChunk($chunks);
365                 } catch (AssertionException $e) {
366                         // Last chunk is not valid
367                         throw new FinalChunkVerificationException(array($this, $chunks, $e), BaseListener::EXCEPTION_FINAL_CHUNK_VERIFICATION);
368                 }
369
370                 // Do we have some pending chunks (no final)?
371                 while (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITHOUT_FINAL)) {
372                         // Then get it first and add it before the EOP chunks
373                         array_unshift($chunks, $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITHOUT_FINAL));
374                 } // END - while
375
376                 // Add all chunks to the FIFO stacker
377                 foreach ($chunks as $chunk) {
378                         // Add the chunk
379                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk);
380                 } // END - foreach
381         }
382
383         /**
384          * Adds all chunks and wait for more (e.g. incomplete transmission)
385          *
386          * @param       $chunks         An array with chunks, the last one should be a 'final'
387          * @return      void
388          */
389         public function addAllChunksWait (array $chunks) {
390                 // Add all chunks to the FIFO stacker
391                 foreach ($chunks as $chunk) {
392                         // Add the chunk
393                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITHOUT_FINAL, $chunk);
394                 } // END - foreach
395         }
396
397         /**
398          * Checks whether unhandled chunks are available
399          *
400          * @return      $unhandledChunks        Whether unhandled chunks are left
401          */
402         public function ifUnhandledChunksWithFinalAvailable () {
403                 // Simply check if the stacker is not empty
404                 $unhandledChunks = $this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP) === false;
405
406                 // Return result
407                 return $unhandledChunks;
408         }
409
410         /**
411          * Handles available chunks by processing one-by-one (not all together,
412          * this would slow-down the whole application) with the help of an
413          * iterator.
414          *
415          * @return      void
416          */
417         public function handleAvailableChunksWithFinal () {
418                 // First check if there are undhandled chunks available
419                 assert($this->ifUnhandledChunksWithFinalAvailable());
420
421                 // Get an entry from the stacker
422                 $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
423
424                 // Split the string with proper separator character
425                 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk);
426
427                 /*
428                  * Make sure three elements are always found:
429                  * 0 = Hash
430                  * 1 = Serial number
431                  * 2 = Raw data
432                  */
433                 assert(count($chunkSplits) == 3);
434
435                 // Is the generated hash from data same ("valid") as given hash?
436                 if (!$this->isChunkHashValid($chunkSplits)) {
437                         // Do some logging
438                         self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: Chunk content is not validating against given hash.');
439
440                         // Re-request this chunk (trust the hash in index # 0)
441                         $this->rerequestChunkBySplitsArray($chunkSplits);
442
443                         // Don't process this chunk
444                         return;
445                 } // END - if
446
447                 // Is the serial number valid (chars 0-9, length equals PackageFragmenter::MAX_SERIAL_LENGTH)?
448                 if (!$this->isSerialNumberValid($chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL])) {
449                         // Do some logging
450                         self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: Chunk serial number ' . $chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL] . ' for hash ' . $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] . ' is invalid.');
451
452                         // Re-request this chunk
453                         $this->rerequestChunkBySplitsArray($chunkSplits);
454
455                         // Don't process this chunk
456                         return;
457                 } // END - if
458
459                 /*
460                  * It is now known that (as long as the hash algorithm has no
461                  * collisions) the content is the same as the sender sends it to this
462                  * peer.
463                  *
464                  * And also the serial number is valid (basicly) at this point. Now the
465                  * chunk can be added to the final array.
466                  */
467                 $this->addChunkToFinalArray($chunkSplits);
468
469                 // Is the stack now empty?
470                 if ($this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP)) {
471                         // Then mark the final array as complete
472                         $this->markFinalArrayAsCompleted();
473                 } // END - if
474         }
475
476         /**
477          * Checks whether unassembled chunks are available (ready) in final array
478          *
479          * @return      $unassembledChunksAvailable             Whether unassembled chunks are available
480          */
481         public function ifUnassembledChunksAvailable () {
482                 // For now do only check the array element 'is_complete'
483                 $unassembledChunksAvailable = ($this->finalPackageChunks['is_complete'] === true);
484
485                 // Return status
486                 return $unassembledChunksAvailable;
487         }
488
489         /**
490          * Assembles all chunks (except EOP and "hash chunk") back together to the original package data.
491          *
492          * This is done by the following steps:
493          *
494          * 1) Sort the final array with ksort(). This will bring the "hash
495          *    chunk" up to the last array index and the EOP chunk to the
496          *    pre-last array index
497          * 2) Assemble all chunks except two last (see above step)
498          * 3) While so, do the final check on all hashes
499          * 4) If the package is assembled back together, hash it again for
500          *    the very final verification.
501          *
502          * @return      void
503          */
504         public function assembleChunksFromFinalArray () {
505                 // Make sure the final array is really completed
506                 assert($this->ifUnassembledChunksAvailable());
507
508                 // Count up stepping
509                 $this->finalPackageChunks['assemble_steps']++;
510
511                 // Do the next step
512                 switch ($this->finalPackageChunks['assemble_steps']) {
513                         case 1: // Sort the chunks array (the serial number shall act as a sorting key)
514                                 $this->sortChunksArray();
515                                 break;
516
517                         case 2: // Prepare the assemble by removing last two indexes
518                                 $this->preparePackageAssmble();
519                                 break;
520
521                         case 3: // Assemble all chunks back together to the original package
522                                 $this->assembleAllChunksToPackage();
523                                 break;
524
525                         case 4: // Verify the raw data by hashing it again
526                                 $this->verifyRawPackageData();
527                                 break;
528
529                         case 5: // Re-initialize handler to reset it to the old state
530                                 $this->initHandler();
531                                 break;
532
533                         default: // Invalid step found
534                                 self::createDebugInstance(__CLASS__)->debugOutput('CHUNK-HANDLER[' . __LINE__ . ']: Invalid step ' . $this->finalPackageChunks['assemble_steps'] . ' detected.');
535                                 break;
536                 } // END - switch
537         }
538
539         /**
540          * Checks whether the raw package data has been assembled back together.
541          * This can be safely assumed when rawPackageData is not empty and the
542          * collection of all chunks is false (because initHandler() will reset it).
543          *
544          * @return      $isRawPackageDataAvailable      Whether raw package data is available
545          */
546         public function ifRawPackageDataIsAvailable () {
547                 // Check it
548                 $isRawPackageDataAvailable = ((!empty($this->rawPackageData)) && (!$this->ifUnassembledChunksAvailable()));
549
550                 // Return it
551                 return $isRawPackageDataAvailable;
552         }
553
554         /**
555          * Handles the finally assembled raw package data by feeding it into another
556          * stacker for further decoding/processing.
557          *
558          * @return      void
559          */
560         public function handledAssembledRawPackageData () {
561                 // Assert to make sure that there is raw package data available
562                 assert($this->ifRawPackageDataIsAvailable());
563
564                 // Then feed it into the next stacker
565                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_ASSEMBLED_RAW_DATA, $this->rawPackageData);
566
567                 // ... and reset it
568                 $this->rawPackageData = '';
569         }
570 }
571
572 // [EOF]
573 ?>