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