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';
36 const CHUNK_SPLITS_INDEX_HASH = 0;
37 const CHUNK_SPLITS_INDEX_SERIAL = 0;
38 const CHUNK_SPLITS_INDEX_RAW_DATA = 0;
41 * The final array for assembling the original package back together
43 private $finalPackageChunks = array(
44 // Array for package content
46 // ... and for the hashes
48 // ... marker for that the final array is complete for assembling all chunks
49 'is_complete' => false
53 * Protected constructor
57 protected function __construct () {
58 // Call parent constructor
59 parent::__construct(__CLASS__);
62 $this->setHandlerName('chunk');
66 * Creates an instance of this class
68 * @return $handlerInstance An instance of a chunk Handler class
70 public final static function createChunkHandler () {
72 $handlerInstance = new ChunkHandler();
75 $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class');
78 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
80 // Set the stacker in this handler
81 $handlerInstance->setStackerInstance($stackerInstance);
83 // Get a crypto instance ...
84 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
86 // ... and set it in this handler
87 $handlerInstance->setCryptoInstance($cryptoInstance);
89 // Return the prepared instance
90 return $handlerInstance;
94 * Checks whether the hash generated from package content is the same ("valid") as given
96 * @param $chunkSplits An array from a splitted chunk
97 * @return $isValid Whether the hash is "valid"
99 private function isChunkHashValid (array $chunkSplits) {
100 // Now hash the raw data again
101 $chunkHash = $this->getCryptoInstance()->hashString($chunkSplits[self::CHUNK_SPLITS_INDEX_RAW_DATA], $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH], false);
104 //* 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]);
107 $isValid = ($chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] === $chunkHash);
114 * Checks whether the given serial number is valid
116 * @param $serialNumber A serial number from a chunk
117 * @return $isValid Whether the serial number is valid
119 private function isSerialNumberValid ($serialNumber) {
121 $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->bigintval($serialNumber, false) === $serialNumber));
128 * Adds the chunk to the final array which will be used for the final step
129 * which will be to assemble all chunks back to the original package content
130 * and for the final hash check.
132 * This method may throw an exception if a chunk with the same serial number
133 * has already been added to avoid mixing chunks from different packages.
135 * @param $chunkSplits An array from a splitted chunk
138 private function addChunkToFinalArray (array $chunkSplits) {
139 // Is the serial number (index 1) already been added?
140 if (isset($this->finalPackageChunks[$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]])) {
141 // Then throw an exception
142 throw new ChunkAlreadyAssembledException(array($this, $chunkSplits), self::EXCEPTION_CHUNK_ALREADY_ASSEMBLED);
145 // Add the chunk data (index 2) to the final array and use the serial number as index
146 $this->finalPackageChunks['content'][$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]] = $chunkSplits[self::CHUNK_SPLITS_INDEX_RAW_DATA];
148 // ... and the hash as well
149 $this->finalPackageChunks['hashes'][$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]] = $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH];
153 * Marks the final array as completed, do only this if you really have all
154 * chunks together including EOP and "hash chunk".
158 private function markFinalArrayAsCompleted () {
160 * As for now, just set the array element. If any further steps are
161 * being added, this should always be the last step.
163 $this->finalPackageChunks['is_complete'] = true;
167 * Adds all chunks if the last one verifies as a 'final chunk'.
169 * @param $chunks An array with chunks, the last one should be a 'final'
171 * @throws FinalChunkVerificationException If the final chunk does not start with 'EOP:'
173 public function addAllChunksWithFinal (array $chunks) {
174 // Validate final chunk
175 if (!$this->isValidFinalChunk($chunks)) {
176 // Last chunk is not valid
177 throw new FinalChunkVerificationException(array($this, $chunks), BaseListener::EXCEPTION_FINAL_CHUNK_VERIFICATION);
180 // Add all chunks to the FIFO stacker
181 foreach ($chunks as $chunk) {
183 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk);
188 * Checks whether unhandled chunks are available
190 * @return $unhandledChunks Whether unhandled chunks are left
192 public function ifUnhandledChunksWithFinalAvailable () {
193 // Simply check if the stacker is not empty
194 $unhandledChunks = $this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP) === false;
197 return $unhandledChunks;
201 * Handles available chunks by processing one-by-one (not all together,
202 * this would slow-down the whole application) with the help of an
207 public function handleAvailableChunksWithFinal () {
208 // First check if there are undhandled chunks available
209 assert($this->ifUnhandledChunksWithFinalAvailable());
211 // Get an entry from the stacker
212 $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
214 // Split the string with proper separator character
215 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk);
218 * Make sure three elements are always found:
223 assert(count($chunkSplits) == 3);
225 // Is the generated hash from data same ("valid") as given hash?
226 if (!$this->isChunkHashValid($chunkSplits)) {
228 $this->debugOutput('CHUNK-HANDLER: Chunk content is not validating against given hash.');
230 // Re-request this chunk (trust the hash in index # 0)
231 $this->rerequestChunkBySplitsArray($chunkSplits);
233 // Don't process this chunk
237 // Is the serial number valid (chars 0-9, length equals PackageFragmenter::MAX_SERIAL_LENGTH)?
238 if (!$this->isSerialNumberValid($chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL])) {
240 $this->debugOutput('CHUNK-HANDLER: Chunk serial numberĀ for hash ' . $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] . ' is invalid.');
242 // Re-request this chunk
243 $this->rerequestChunkBySplitsArray($chunkSplits);
245 // Don't process this chunk
250 * It is now known that (as long as the hash algorithm has no
251 * collisions) the content is the same as the sender sends it to this
254 * And also the serial number is valid (basicly) at this point. Now the
255 * chunk can be added to the final array.
257 $this->addChunkToFinalArray($chunkSplits);
259 // Is the stack now empty?
260 if ($this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP)) {
261 // Then mark the final array as complete
262 $this->markFinalArrayAsCompleted();
267 * Checks whether unassembled chunks are available (ready) in final array
269 * @return $unassembledChunksAvailable Whether unassembled chunks are available
271 public function ifUnassembledChunksAvailable () {
272 // For now do only check the array element 'is_complete'
273 $unassembledChunksAvailable = ($this->finalPackageChunks['is_complete'] === true);
276 return $unassembledChunksAvailable;
280 * Assembles all chunks (except EOP and "hash chunk") back together to the original package data.
282 * This is done by the following steps:
284 * 1) Sort the final array with ksort(). This will bring the "hash
285 * chunk" up to the last array index and the EOP chunk to the
286 * pre-last array index
287 * 2) Assemble all chunks except two last (see above step)
288 * 3) While so, do the final check on all hashes
289 * 4) If the package is assembled back together, hash it again for
290 * the very final verification.
294 public function assembleChunksFromFinalArray () {
295 // Make sure the final array is really completed
296 assert($this->ifUnassembledChunksAvailable());
298 $this->partialStub('Please implement this method.');