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
38 // ... marker for that the final array is complete for assembling all chunks
39 'is_complete' => false
43 * Protected constructor
47 protected function __construct () {
48 // Call parent constructor
49 parent::__construct(__CLASS__);
52 $this->setHandlerName('chunk');
56 * Creates an instance of this class
58 * @return $handlerInstance An instance of a chunk Handler class
60 public final static function createChunkHandler () {
62 $handlerInstance = new ChunkHandler();
65 $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class');
68 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
70 // Set the stacker in this handler
71 $handlerInstance->setStackerInstance($stackerInstance);
73 // Get a crypto instance ...
74 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
76 // ... and set it in this handler
77 $handlerInstance->setCryptoInstance($cryptoInstance);
79 // Return the prepared instance
80 return $handlerInstance;
84 * Checks whether the hash generated from package content is the same ("valid") as given
86 * @param $chunkSplits An array from a splitted chunk
87 * @return $isValid Whether the hash is "valid"
89 private function isChunkHashValid (array $chunkSplits) {
90 // Now hash the raw data again
91 $chunkHash = $this->getCryptoInstance()->hashString($chunkSplits[2], $chunkSplits[0], false);
94 //* NOISY-DEBUG: */ $this->debugOutput('CHUNK-HANDLER: chunkHash=' . $chunkHash . ',chunkSplits[0]=' . $chunkSplits[0] . ',chunkSplits[1]=' . $chunkSplits[1]);
97 $isValid = ($chunkSplits[0] === $chunkHash);
104 * Checks whether the given serial number is valid
106 * @param $serialNumber A serial number from a chunk
107 * @return $isValid Whether the serial number is valid
109 private function isSerialNumberValid ($serialNumber) {
111 $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->bigintval($serialNumber, false) === $serialNumber));
118 * Adds the chunk to the final array which will be used for the final step
119 * which will be to assemble all chunks back to the original package content
120 * and for the final hash check.
122 * This method may throw an exception if a chunk with the same serial number
123 * has already been added to avoid mixing chunks from different packages.
125 * @param $chunkSplits An array from a splitted chunk
128 private function addChunkToFinalArray (array $chunkSplits) {
129 // Is the serial number (index 1) already been added?
130 if (isset($this->finalPackageChunks[$chunkSplits[1]])) {
131 // Then throw an exception
132 throw new ChunkAlreadyAssembledException(array($this, $chunkSplits), self::EXCEPTION_CHUNK_ALREADY_ASSEMBLED);
135 // Add the chunk data (index 2) to the final array and use the serial number as index
136 $this->finalPackageChunks['content'][$chunkSplits[1]] = $chunkSplits[2];
138 // ... and the hash as well
139 $this->finalPackageChunks['hashes'][$chunkSplits[1]] = $chunkSplits[0];
143 * Marks the final array as completed, do only this if you really have all
144 * chunks together including EOP and "hash chunk".
148 private function markFinalArrayAsCompleted () {
150 * As for now, just set the array element. If any further steps are
151 * being added, this should always be the last step.
153 $this->finalPackageChunks['is_complete'] = true;
157 * Adds all chunks if the last one verifies as a 'final chunk'.
159 * @param $chunks An array with chunks, the last one should be a 'final'
161 * @throws FinalChunkVerificationException If the final chunk does not start with 'EOP:'
163 public function addAllChunksWithFinal (array $chunks) {
164 // Validate final chunk
165 if (!$this->isValidFinalChunk($chunks)) {
166 // Last chunk is not valid
167 throw new FinalChunkVerificationException(array($this, $chunks), BaseListener::EXCEPTION_FINAL_CHUNK_VERIFICATION);
170 // Add all chunks to the FIFO stacker
171 foreach ($chunks as $chunk) {
173 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk);
178 * Checks whether unhandled chunks are available
180 * @return $unhandledChunks Whether unhandled chunks are left
182 public function ifUnhandledChunksWithFinalAvailable () {
183 // Simply check if the stacker is not empty
184 $unhandledChunks = $this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP) === false;
187 return $unhandledChunks;
191 * Handles available chunks by processing one-by-one (not all together,
192 * this would slow-down the whole application) with the help of an
197 public function handleAvailableChunksWithFinal () {
198 // First check if there are undhandled chunks available
199 assert($this->ifUnhandledChunksWithFinalAvailable());
201 // Get an entry from the stacker
202 $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
204 // Split the string with proper separator character
205 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk);
208 * Make sure three elements are always found:
213 assert(count($chunkSplits) == 3);
215 // Is the generated hash from data same ("valid") as given hash?
216 if (!$this->isChunkHashValid($chunkSplits)) {
218 $this->debugOutput('CHUNK-HANDLER: Chunk content is not validating against given hash.');
220 // Re-request this chunk (trust the hash in index # 0)
221 $this->rerequestChunkBySplitsArray($chunkSplits);
223 // Don't process this chunk
227 // Is the serial number valid (chars 0-9, length equals PackageFragmenter::MAX_SERIAL_LENGTH)?
228 if (!$this->isSerialNumberValid($chunkSplits[1])) {
230 $this->debugOutput('CHUNK-HANDLER: Chunk serial numberĀ for hash ' . $chunkSplits[0] . ' is invalid.');
232 // Re-request this chunk
233 $this->rerequestChunkBySplitsArray($chunkSplits);
235 // Don't process this chunk
240 * It is now known that (as long as the hash algorithm has no
241 * collisions) the content is the same as the sender sends it to this
244 * And also the serial number is valid (basicly) at this point.
246 * Now the chunk can be added to the final array
248 $this->addChunkToFinalArray($chunkSplits);
250 // Is the stack now empty?
251 if ($this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP)) {
252 // Then mark the final array as complete
253 $this->markFinalArrayAsCompleted();
258 * Checks whether unassembled chunks are available (ready) in final array
260 * @return $unassembledChunksAvailable Whether unassembled chunks are available
262 public function ifUnassembledChunksAvailable () {
263 // For now do only check the array element 'is_complete'
264 $unassembledChunksAvailable = ($this->finalPackageChunks['is_complete'] === true);
267 return $unassembledChunksAvailable;
271 * Assembles all chunks (except EOP and "hash chunk") back together to the original package data.
273 * This is done by the following steps:
275 * 1) Sort the final array with ksort(). This will bring the "hash
276 * chunk" up to the last array index and the EOP chunk to the
277 * pre-last array index
278 * 2) Assemble all chunks except two last (see above step)
279 * 3) While so, do the final check on all hashes
280 * 4) If the package is assembled back together, hash it again for
281 * the very final verification.
283 public function assembleChunksFromFinalArray () {
284 $this->partialStub('Please implement this method.');