* @version 0.0.0 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team * @license GNU GPL 3.0 or any newer version * @link http://www.ship-simu.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ class ChunkHandler extends BaseHandler implements HandleableChunks, Registerable { /** * Stacker for chunks with final EOP */ const STACKER_NAME_CHUNKS_WITH_FINAL_EOP = 'final_chunks'; /** * The final array for assembling the original package back together */ private $finalPackageChunks = array( // Array for package content 'content' => array(), // ... and for the hashes 'hashes' => array(), // ... marker for that the final array is complete for assembling all chunks 'is_complete' => false ); /** * Protected constructor * * @return void */ protected function __construct () { // Call parent constructor parent::__construct(__CLASS__); // Set handler name $this->setHandlerName('chunk'); } /** * Creates an instance of this class * * @return $handlerInstance An instance of a chunk Handler class */ public final static function createChunkHandler () { // Get new instance $handlerInstance = new ChunkHandler(); // Get a FIFO stacker $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class'); // Init all stacker $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP); // Set the stacker in this handler $handlerInstance->setStackerInstance($stackerInstance); // Get a crypto instance ... $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class'); // ... and set it in this handler $handlerInstance->setCryptoInstance($cryptoInstance); // Return the prepared instance return $handlerInstance; } /** * Checks whether the hash generated from package content is the same ("valid") as given * * @param $chunkSplits An array from a splitted chunk * @return $isValid Whether the hash is "valid" */ private function isChunkHashValid (array $chunkSplits) { // Now hash the raw data again $chunkHash = $this->getCryptoInstance()->hashString($chunkSplits[2], $chunkSplits[0], false); // Debug output //* NOISY-DEBUG: */ $this->debugOutput('CHUNK-HANDLER: chunkHash=' . $chunkHash . ',chunkSplits[0]=' . $chunkSplits[0] . ',chunkSplits[1]=' . $chunkSplits[1]); // Check it $isValid = ($chunkSplits[0] === $chunkHash); // ... and return it return $isValid; } /** * Checks whether the given serial number is valid * * @param $serialNumber A serial number from a chunk * @return $isValid Whether the serial number is valid */ private function isSerialNumberValid ($serialNumber) { // Check it $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->bigintval($serialNumber, false) === $serialNumber)); // Return result return $isValid; } /** * Adds the chunk to the final array which will be used for the final step * which will be to assemble all chunks back to the original package content * and for the final hash check. * * This method may throw an exception if a chunk with the same serial number * has already been added to avoid mixing chunks from different packages. * * @param $chunkSplits An array from a splitted chunk * @return void */ private function addChunkToFinalArray (array $chunkSplits) { // Is the serial number (index 1) already been added? if (isset($this->finalPackageChunks[$chunkSplits[1]])) { // Then throw an exception throw new ChunkAlreadyAssembledException(array($this, $chunkSplits), self::EXCEPTION_CHUNK_ALREADY_ASSEMBLED); } // END - if // Add the chunk data (index 2) to the final array and use the serial number as index $this->finalPackageChunks['content'][$chunkSplits[1]] = $chunkSplits[2]; // ... and the hash as well $this->finalPackageChunks['hashes'][$chunkSplits[1]] = $chunkSplits[0]; } /** * Marks the final array as completed, do only this if you really have all * chunks together including EOP and "hash chunk". * * @return void */ private function markFinalArrayAsCompleted () { /* * As for now, just set the array element. If any further steps are * being added, this should always be the last step. */ $this->finalPackageChunks['is_complete'] = true; } /** * Adds all chunks if the last one verifies as a 'final chunk'. * * @param $chunks An array with chunks, the last one should be a 'final' * @return void * @throws FinalChunkVerificationException If the final chunk does not start with 'EOP:' */ public function addAllChunksWithFinal (array $chunks) { // Validate final chunk if (!$this->isValidFinalChunk($chunks)) { // Last chunk is not valid throw new FinalChunkVerificationException(array($this, $chunks), BaseListener::EXCEPTION_FINAL_CHUNK_VERIFICATION); } // END - if // Add all chunks to the FIFO stacker foreach ($chunks as $chunk) { // Add the chunk $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk); } // END - foreach } /** * Checks whether unhandled chunks are available * * @return $unhandledChunks Whether unhandled chunks are left */ public function ifUnhandledChunksWithFinalAvailable () { // Simply check if the stacker is not empty $unhandledChunks = $this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP) === false; // Return result return $unhandledChunks; } /** * Handles available chunks by processing one-by-one (not all together, * this would slow-down the whole application) with the help of an * iterator. * * @return void */ public function handleAvailableChunksWithFinal () { // First check if there are undhandled chunks available assert($this->ifUnhandledChunksWithFinalAvailable()); // Get an entry from the stacker $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP); // Split the string with proper separator character $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk); /* * Make sure three elements are always found: * 0 = Hash * 1 = Serial number * 2 = Raw data */ assert(count($chunkSplits) == 3); // Is the generated hash from data same ("valid") as given hash? if (!$this->isChunkHashValid($chunkSplits)) { // Do some logging $this->debugOutput('CHUNK-HANDLER: Chunk content is not validating against given hash.'); // Re-request this chunk (trust the hash in index # 0) $this->rerequestChunkBySplitsArray($chunkSplits); // Don't process this chunk return; } // END - if // Is the serial number valid (chars 0-9, length equals PackageFragmenter::MAX_SERIAL_LENGTH)? if (!$this->isSerialNumberValid($chunkSplits[1])) { // Do some logging $this->debugOutput('CHUNK-HANDLER: Chunk serial number for hash ' . $chunkSplits[0] . ' is invalid.'); // Re-request this chunk $this->rerequestChunkBySplitsArray($chunkSplits); // Don't process this chunk return; } // END - if /* * It is now known that (as long as the hash algorithm has no * collisions) the content is the same as the sender sends it to this * peer. * * And also the serial number is valid (basicly) at this point. * * Now the chunk can be added to the final array */ $this->addChunkToFinalArray($chunkSplits); // Is the stack now empty? if ($this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP)) { // Then mark the final array as complete $this->markFinalArrayAsCompleted(); } // END - if } /** * Checks whether unassembled chunks are available (ready) in final array * * @return $unassembledChunksAvailable Whether unassembled chunks are available */ public function ifUnassembledChunksAvailable () { // For now do only check the array element 'is_complete' $unassembledChunksAvailable = ($this->finalPackageChunks['is_complete'] === true); // Return status return $unassembledChunksAvailable; } /** * Assembles all chunks (except EOP and "hash chunk") back together to the original package data. * * This is done by the following steps: * * 1) Sort the final array with ksort(). This will bring the "hash * chunk" up to the last array index and the EOP chunk to the * pre-last array index * 2) Assemble all chunks except two last (see above step) * 3) While so, do the final check on all hashes * 4) If the package is assembled back together, hash it again for * the very final verification. */ public function assembleChunksFromFinalArray () { $this->partialStub('Please implement this method.'); } } // [EOF] ?>