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';
31 * The final array for assembling the original package back together
33 private $finalPackageChunks = array(
34 // Array for package content
36 // ... and for the hashes
41 * Protected constructor
45 protected function __construct () {
46 // Call parent constructor
47 parent::__construct(__CLASS__);
50 $this->setHandlerName('chunk');
54 * Creates an instance of this class
56 * @return $handlerInstance An instance of a chunk Handler class
58 public final static function createChunkHandler () {
60 $handlerInstance = new ChunkHandler();
63 $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class');
66 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
68 // Set the stacker in this handler
69 $handlerInstance->setStackerInstance($stackerInstance);
71 // Get a crypto instance ...
72 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
74 // ... and set it in this handler
75 $handlerInstance->setCryptoInstance($cryptoInstance);
77 // Return the prepared instance
78 return $handlerInstance;
82 * Checks whether the hash generated from package content is the same ("valid") as given
84 * @param $chunkSplits An array from a splitted chunk
85 * @return $isValid Whether the hash is "valid"
87 private function isChunkHashValid (array $chunkSplits) {
88 // Now hash the raw data again
89 $chunkHash = $this->getCryptoInstance()->hashString($chunkSplits[2], $chunkSplits[0], false);
92 //* NOISY-DEBUG: */ $this->debugOutput('CHUNK-HANDLER: chunkHash=' . $chunkHash . ',chunkSplits[0]=' . $chunkSplits[0] . ',chunkSplits[1]=' . $chunkSplits[1]);
95 $isValid = ($chunkSplits[0] === $chunkHash);
102 * Checks whether the given serial number is valid
104 * @param $serialNumber A serial number from a chunk
105 * @return $isValid Whether the serial number is valid
107 private function isSerialNumberValid ($serialNumber) {
109 $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->bigintval($serialNumber, false) === $serialNumber));
116 * Adds the chunk to the final array which will be used for the final step
117 * which will be to assemble all chunks back to the original package content
118 * and for the final hash check.
120 * This method may throw an exception if a chunk with the same serial number
121 * has already been added to avoid mixing chunks from different packages.
123 * @param $chunkSplits An array from a splitted chunk
126 private function addChunkToFinalArray (array $chunkSplits) {
127 // Is the serial number (index 1) already been added?
128 if (isset($this->finalPackageChunks[$chunkSplits[1])) {
129 // Then throw an exception
130 throw new ChunkAlreadyAssembledException(array($this, $chunkSplits), self::EXCEPTION_CHUNK_ALREADY_ASSEMBLED);
133 // Add the chunk data (index 2) to the final array and use the serial number as index
134 $this->finalPackageChunks['content'][$chunkSplits[1]] = $chunkSplits[2];
136 // ... and the hash as well
137 $this->finalPackageChunks['hashes'][$chunkSplits[1]] = $chunkSplits[0];
141 * Adds all chunks if the last one verifies as a 'final chunk'.
143 * @param $chunks An array with chunks, the last one should be a 'final'
145 * @throws FinalChunkVerificationException If the final chunk does not start with 'EOP:'
147 public function addAllChunksWithFinal (array $chunks) {
148 // Validate final chunk
149 if (!$this->isValidFinalChunk($chunks)) {
150 // Last chunk is not valid
151 throw new FinalChunkVerificationException(array($this, $chunks), BaseListener::EXCEPTION_FINAL_CHUNK_VERIFICATION);
154 // Add all chunks to the FIFO stacker
155 foreach ($chunks as $chunk) {
157 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk);
162 * Checks whether unhandled chunks are available
164 * @return $unhandledChunks Whether unhandled chunks are left
166 public function ifUnhandledChunksWithFinalAvailable () {
167 // Simply check if the stacker is not empty
168 $unhandledChunks = $this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP) === false;
171 return $unhandledChunks;
175 * Handles available chunks by processing one-by-one (not all together,
176 * this would slow-down the whole application) with the help of an
181 public function handleAvailableChunksWithFinal () {
182 // First check if there are undhandled chunks available
183 assert($this->ifUnhandledChunksWithFinalAvailable());
185 // Get an entry from the stacker
186 $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
188 // Split the string with proper separator character
189 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk);
192 * Make sure three elements are always found:
197 assert(count($chunkSplits) == 3);
199 // Is the generated hash from data same ("valid") as given hash?
200 if (!$this->isChunkHashValid($chunkSplits)) {
202 $this->debugOutput('CHUNK-HANDLER: Chunk content is not validating against given hash.');
204 // Re-request this chunk (trust the hash in index # 0)
205 $this->rerequestChunkBySplitsArray($chunkSplits);
207 // Don't process this chunk
211 // Is the serial number valid (chars 0-9, length equals PackageFragmenter::MAX_SERIAL_LENGTH)?
212 if (!$this->isSerialNumberValid($chunkSplits[1])) {
214 $this->debugOutput('CHUNK-HANDLER: Chunk serial numberĀ for hash ' . $chunkSplits[0] . ' is invalid.');
216 // Re-request this chunk
217 $this->rerequestChunkBySplitsArray($chunkSplits);
219 // Don't process this chunk
224 * It is now known that (as long as the hash algorithm has no
225 * collisions) the content is the same as the sender sends it to this
228 * And also the serial number is valid (basicly) at this point.
230 * Now the chunk can be added to the final array
232 $this->addChunkToFinalArray($chunkSplits);