5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
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.
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.
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/>.
24 class ChunkHandler extends BaseHandler implements HandleableChunks, Registerable {
26 * Stacker for chunks with final EOP
28 const STACKER_NAME_CHUNKS_WITH_FINAL_EOP = 'final_chunks';
29 const STACKER_NAME_ASSEMBLED_RAW_DATA = 'chunk_raw_data';
37 const CHUNK_SPLITS_INDEX_HASH = 0;
38 const CHUNK_SPLITS_INDEX_SERIAL = 1;
39 const CHUNK_SPLITS_INDEX_RAW_DATA = 2;
42 * The final array for assembling the original package back together
44 private $finalPackageChunks = array();
47 * Array of chunk hashes
49 private $chunkHashes = array();
52 * Raw EOP chunk data in an array:
55 * 1 = Hash of last chunk
57 private $eopChunk = array();
62 private $rawPackageData = '';
65 * Protected constructor
69 protected function __construct () {
70 // Call parent constructor
71 parent::__construct(__CLASS__);
74 $this->setHandlerName('chunk');
81 * Creates an instance of this class
83 * @return $handlerInstance An instance of a chunk Handler class
85 public final static function createChunkHandler () {
87 $handlerInstance = new ChunkHandler();
90 $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class');
93 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
94 $stackerInstance->initStacker(self::STACKER_NAME_ASSEMBLED_RAW_DATA);
96 // Set the stacker in this handler
97 $handlerInstance->setStackerInstance($stackerInstance);
99 // Get a crypto instance ...
100 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
102 // ... and set it in this handler
103 $handlerInstance->setCryptoInstance($cryptoInstance);
105 // Get a fragmenter instance for later verification of serial numbers (e.g. if all are received)
106 $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
108 // Set it in this handler
109 $handlerInstance->setFragmenterInstance($fragmenterInstance);
111 // Return the prepared instance
112 return $handlerInstance;
116 * Initializes the handler
120 private function initHandler () {
121 // Init finalPackageChunks
122 $this->finalPackageChunks = array(
123 // Array for package content
124 'content' => array(),
125 // ... and for the hashes
127 // ... marker for that the final array is complete for assembling all chunks
128 'is_complete' => false,
129 // ... steps done to assemble all chunks
130 'assemble_steps' => 0,
134 $this->chunkHashes = array();
137 $this->eopChunk = array(
144 * Checks whether the hash generated from package content is the same ("valid") as given
146 * @param $chunkSplits An array from a splitted chunk
147 * @return $isValid Whether the hash is "valid"
149 private function isChunkHashValid (array $chunkSplits) {
150 // Now hash the raw data again
151 $chunkHash = $this->getCryptoInstance()->hashString($chunkSplits[self::CHUNK_SPLITS_INDEX_RAW_DATA], $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH], false);
154 //* NOISY-DEBUG: */ $this->debugOutput('CHUNK-HANDLER: 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 $isValid = ($chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] === $chunkHash);
164 * Checks whether the given serial number is valid
166 * @param $serialNumber A serial number from a chunk
167 * @return $isValid Whether the serial number is valid
169 private function isSerialNumberValid ($serialNumber) {
171 $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->bigintval($serialNumber, false) === $serialNumber));
178 * Adds the chunk to the final array which will be used for the final step
179 * which will be to assemble all chunks back to the original package content
180 * and for the final hash check.
182 * This method may throw an exception if a chunk with the same serial number
183 * has already been added to avoid mixing chunks from different packages.
185 * @param $chunkSplits An array from a splitted chunk
188 private function addChunkToFinalArray (array $chunkSplits) {
189 // Is the serial number (index 1) already been added?
190 if (isset($this->finalPackageChunks[$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]])) {
191 // Then throw an exception
192 throw new ChunkAlreadyAssembledException(array($this, $chunkSplits), self::EXCEPTION_CHUNK_ALREADY_ASSEMBLED);
195 // Add the chunk data (index 2) to the final array and use the serial number as index
196 $this->finalPackageChunks['content'][$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]] = $chunkSplits[self::CHUNK_SPLITS_INDEX_RAW_DATA];
198 // ... and the hash as well
199 $this->finalPackageChunks['hashes'][$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]] = $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH];
203 * Marks the final array as completed, do only this if you really have all
204 * chunks together including EOP and "hash chunk".
208 private function markFinalArrayAsCompleted () {
210 * As for now, just set the array element. If any further steps are
211 * being added, this should always be the last step.
213 $this->finalPackageChunks['is_complete'] = true;
217 * Sorts the chunks array by using the serial number as a sorting key. In
218 * most situations a call of ksort() is enough to accomblish this. So this
219 * method may only call ksort() on the chunks array.
221 * This method sorts 'content' and 'hashes' so both must have used the
222 * serial numbers as array indexes.
226 private function sortChunksArray () {
227 // Sort 'content' first
228 ksort($this->finalPackageChunks['content']);
231 ksort($this->finalPackageChunks['hashes']);
235 * Prepares the package assemble by removing last chunks (last shall be
236 * hash chunk, pre-last shall be EOP chunk) and verify that all serial
237 * numbers are valid (same as PackageFragmenter class would generate).
241 private function preparePackageAssmble () {
242 // Make sure both arrays have same count (this however should always be true)
243 assert(count($this->finalPackageChunks['hashes']) == count($this->finalPackageChunks['content']));
246 * Remove last element (hash chunk) from 'hashes'. This hash will never
247 * be needed, so ignore it.
249 array_pop($this->finalPackageChunks['hashes']);
251 // ... and from 'content' as well but save it for later use
252 $this->chunkHashes = explode(PackageFragmenter::CHUNK_HASH_SEPARATOR, substr(array_pop($this->finalPackageChunks['content']), strlen(PackageFragmenter::HASH_CHUNK_IDENTIFIER)));
254 // Remove EOP chunk and keep a copy of it
255 array_pop($this->finalPackageChunks['hashes']);
256 $this->eopChunk = explode(PackageFragmenter::CHUNK_HASH_SEPARATOR, substr(array_pop($this->finalPackageChunks['content']), strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)));
258 // Verify all serial numbers
259 $this->verifyChunkSerialNumbers();
263 * Verifies all chunk serial numbers by using a freshly initialized
264 * fragmenter instance. Do ALWAYS sort the array and array_pop() the hash
265 * chunk before calling this method to avoid re-requests of many chunks.
269 private function verifyChunkSerialNumbers () {
270 // Reset the serial number generator
271 $this->getFragmenterInstance()->resetSerialNumber();
273 // "Walk" through all (content) chunks
274 foreach ($this->finalPackageChunks['content'] as $serialNumber=>$content) {
275 // Get next serial number
276 $nextSerial = $this->getFragmenterInstance()->getNextHexSerialNumber();
279 //* NOISY-DEBUG */ $this->debugOutput('CHUNK-HANDLER: serialNumber=' . $serialNumber . ',nextSerial=' . $nextSerial);
281 // Is it not the same? Then re-request it
282 if ($serialNumber != $nextSerial) {
283 // This is invalid, so remove it
284 unset($this->finalPackageChunks['content'][$serialNumber]);
285 unset($this->finalPackageChunks['hashes'][$serialNumber]);
287 // And re-request it with valid serial number (and hash chunk)
288 $this->rerequestChunkBySerialNumber($nextSerial);
294 * Assembles and verifies ("final check") chunks back together to the
295 * original package (raw data for the start). This method should only be
296 * called AFTER the EOP and final-chunk chunk have been removed.
300 private function assembleAllChunksToPackage () {
301 // If chunkHashes is not filled, don't continue
302 assert(count($this->chunkHashes) > 0);
304 // Init raw package data string
305 $this->rawPackageData = '';
307 // That went well, so start assembling all chunks
308 foreach ($this->finalPackageChunks['content'] as $serialNumber=>$content) {
309 // Is this chunk valid? This should be the case
310 assert($this->isChunkHashValid(array(
311 self::CHUNK_SPLITS_INDEX_HASH => $this->finalPackageChunks['hashes'][$serialNumber],
312 self::CHUNK_SPLITS_INDEX_RAW_DATA => $content
315 // ... and is also in the hash chunk?
316 assert(in_array($this->finalPackageChunks['hashes'][$serialNumber], $this->chunkHashes));
318 // Verification okay, add it to the raw data
319 $this->rawPackageData .= $content;
323 //* NOISY-DEBUG: */ $this->debugOutput('CHUNK-HANDLER: eopChunk[1]=' . $this->eopChunk[1] . ',' . chr(10) . 'index=' . (count($this->chunkHashes) - 2) . ',' . chr(10) . 'chunkHashes='.print_r($this->chunkHashes,true));
325 // The last chunk hash must match with the one from eopChunk[1]
326 assert($this->eopChunk[1] == $this->chunkHashes[count($this->chunkHashes) - 2]);
330 * Verifies the finally assembled raw package data by comparing it against
335 private function verifyRawPackageData () {
336 // Hash the raw package data for final verification
337 $finalHash = $this->getCryptoInstance()->hashString($this->rawPackageData, $this->eopChunk[0], false);
340 assert($finalHash == $this->eopChunk[0]);
344 * Adds all chunks if the last one verifies as a 'final chunk'.
346 * @param $chunks An array with chunks, the last one should be a 'final'
348 * @throws FinalChunkVerificationException If the final chunk does not start with 'EOP:'
350 public function addAllChunksWithFinal (array $chunks) {
351 // Validate final chunk
352 if (!$this->isValidFinalChunk($chunks)) {
353 // Last chunk is not valid
354 throw new FinalChunkVerificationException(array($this, $chunks), BaseListener::EXCEPTION_FINAL_CHUNK_VERIFICATION);
357 // Add all chunks to the FIFO stacker
358 foreach ($chunks as $chunk) {
360 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk);
365 * Checks whether unhandled chunks are available
367 * @return $unhandledChunks Whether unhandled chunks are left
369 public function ifUnhandledChunksWithFinalAvailable () {
370 // Simply check if the stacker is not empty
371 $unhandledChunks = $this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP) === false;
374 return $unhandledChunks;
378 * Handles available chunks by processing one-by-one (not all together,
379 * this would slow-down the whole application) with the help of an
384 public function handleAvailableChunksWithFinal () {
385 // First check if there are undhandled chunks available
386 assert($this->ifUnhandledChunksWithFinalAvailable());
388 // Get an entry from the stacker
389 $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
391 // Split the string with proper separator character
392 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk);
395 * Make sure three elements are always found:
400 assert(count($chunkSplits) == 3);
402 // Is the generated hash from data same ("valid") as given hash?
403 if (!$this->isChunkHashValid($chunkSplits)) {
405 $this->debugOutput('CHUNK-HANDLER: Chunk content is not validating against given hash.');
407 // Re-request this chunk (trust the hash in index # 0)
408 $this->rerequestChunkBySplitsArray($chunkSplits);
410 // Don't process this chunk
414 // Is the serial number valid (chars 0-9, length equals PackageFragmenter::MAX_SERIAL_LENGTH)?
415 if (!$this->isSerialNumberValid($chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL])) {
417 $this->debugOutput('CHUNK-HANDLER: Chunk serial numberĀ for hash ' . $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] . ' is invalid.');
419 // Re-request this chunk
420 $this->rerequestChunkBySplitsArray($chunkSplits);
422 // Don't process this chunk
427 * It is now known that (as long as the hash algorithm has no
428 * collisions) the content is the same as the sender sends it to this
431 * And also the serial number is valid (basicly) at this point. Now the
432 * chunk can be added to the final array.
434 $this->addChunkToFinalArray($chunkSplits);
436 // Is the stack now empty?
437 if ($this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP)) {
438 // Then mark the final array as complete
439 $this->markFinalArrayAsCompleted();
444 * Checks whether unassembled chunks are available (ready) in final array
446 * @return $unassembledChunksAvailable Whether unassembled chunks are available
448 public function ifUnassembledChunksAvailable () {
449 // For now do only check the array element 'is_complete'
450 $unassembledChunksAvailable = ($this->finalPackageChunks['is_complete'] === true);
453 return $unassembledChunksAvailable;
457 * Assembles all chunks (except EOP and "hash chunk") back together to the original package data.
459 * This is done by the following steps:
461 * 1) Sort the final array with ksort(). This will bring the "hash
462 * chunk" up to the last array index and the EOP chunk to the
463 * pre-last array index
464 * 2) Assemble all chunks except two last (see above step)
465 * 3) While so, do the final check on all hashes
466 * 4) If the package is assembled back together, hash it again for
467 * the very final verification.
471 public function assembleChunksFromFinalArray () {
472 // Make sure the final array is really completed
473 assert($this->ifUnassembledChunksAvailable());
476 $this->finalPackageChunks['assemble_steps']++;
479 switch ($this->finalPackageChunks['assemble_steps']) {
480 case 1: // Sort the chunks array (the serial number shall act as a sorting key)
481 $this->sortChunksArray();
484 case 2: // Prepare the assemble by removing last two indexes
485 $this->preparePackageAssmble();
488 case 3: // Assemble all chunks back together to the original package
489 $this->assembleAllChunksToPackage();
492 case 4: // Verify the raw data by hashing it again
493 $this->verifyRawPackageData();
496 case 5: // Re-initialize handler to reset it to the old state
497 $this->initHandler();
500 default: // Invalid step found
501 $this->debugOutput('CHUNK-HANDLER: Invalid step ' . $this->finalPackageChunks['assemble_steps'] . ' detected.');
507 * Checks whether the raw package data has been assembled back together.
508 * This can be safely assumed when rawPackageData is not empty and the
509 * collection of all chunks is false (because initHandler() will reset it).
511 * @return $isRawPackageDataAvailable Whether raw package data is available
513 public function ifRawPackageDataIsAvailable () {
515 $isRawPackageDataAvailable = ((!empty($this->rawPackageData)) && (!$this->ifUnassembledChunksAvailable()));
518 return $isRawPackageDataAvailable;
522 * Handles the finally assembled raw package data by feeding it into another
523 * stacker for further decoding/processing.
527 public function handledAssembledRawPackageData () {
528 // Assert to make sure that there is raw package data available
529 assert($this->ifRawPackageDataIsAvailable());
531 // Then feed it into the next stacker
532 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_ASSEMBLED_RAW_DATA, $this->rawPackageData);
535 $this->rawPackageData = '';