]> git.mxchange.org Git - hub.git/blob - application/hub/main/handler/chunks/class_ChunkHandler.php
Rewrote numbered indexes to assoziative
[hub.git] / application / hub / main / handler / chunks / class_ChunkHandler.php
1 <?php
2 /**
3  * A Chunk handler
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class ChunkHandler extends BaseHandler implements HandleableChunks, Registerable {
25         /**
26          * Stacker for chunks with final EOP
27          */
28         const STACKER_NAME_CHUNKS_WITH_FINAL_EOP = 'final_chunks';
29
30         /**
31          * Chunk splits:
32          * 0 = Hash
33          * 1 = Serial number
34          * 2 = Raw data
35          */
36         const CHUNK_SPLITS_INDEX_HASH     = 0;
37         const CHUNK_SPLITS_INDEX_SERIAL   = 0;
38         const CHUNK_SPLITS_INDEX_RAW_DATA = 0;
39
40         /**
41          * The final array for assembling the original package back together
42          */
43         private $finalPackageChunks = array(
44                 // Array for package content
45                 'content'     => array(),
46                 // ... and for the hashes
47                 'hashes'      => array(),
48                 // ... marker for that the final array is complete for assembling all chunks
49                 'is_complete' => false
50         );
51
52         /**
53          * Protected constructor
54          *
55          * @return      void
56          */
57         protected function __construct () {
58                 // Call parent constructor
59                 parent::__construct(__CLASS__);
60
61                 // Set handler name
62                 $this->setHandlerName('chunk');
63         }
64
65         /**
66          * Creates an instance of this class
67          *
68          * @return      $handlerInstance        An instance of a chunk Handler class
69          */
70         public final static function createChunkHandler () {
71                 // Get new instance
72                 $handlerInstance = new ChunkHandler();
73
74                 // Get a FIFO stacker
75                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class');
76
77                 // Init all stacker
78                 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
79
80                 // Set the stacker in this handler
81                 $handlerInstance->setStackerInstance($stackerInstance);
82
83                 // Get a crypto instance ...
84                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
85
86                 // ... and set it in this handler
87                 $handlerInstance->setCryptoInstance($cryptoInstance);
88
89                 // Return the prepared instance
90                 return $handlerInstance;
91         }
92
93         /**
94          * Checks whether the hash generated from package content is the same ("valid") as given
95          *
96          * @param       $chunkSplits    An array from a splitted chunk
97          * @return      $isValid                Whether the hash is "valid"
98          */
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);
102
103                 // Debug output
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]);
105
106                 // Check it
107                 $isValid = ($chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] === $chunkHash);
108
109                 // ... and return it
110                 return $isValid;
111         }
112
113         /**
114          * Checks whether the given serial number is valid
115          *
116          * @param       $serialNumber   A serial number from a chunk
117          * @return      $isValid                Whether the serial number is valid
118          */
119         private function isSerialNumberValid ($serialNumber) {
120                 // Check it
121                 $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->bigintval($serialNumber, false) === $serialNumber));
122
123                 // Return result
124                 return $isValid;
125         }
126
127         /**
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.
131          *
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.
134          *
135          * @param       $chunkSplits    An array from a splitted chunk
136          * @return      void
137          */
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);
143                 } // END - if
144
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];
147
148                 // ... and the hash as well
149                 $this->finalPackageChunks['hashes'][$chunkSplits[self::CHUNK_SPLITS_INDEX_SERIAL]] = $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH];
150         }
151
152         /**
153          * Marks the final array as completed, do only this if you really have all
154          * chunks together including EOP and "hash chunk".
155          *
156          * @return      void
157          */
158         private function markFinalArrayAsCompleted () {
159                 /*
160                  * As for now, just set the array element. If any further steps are
161                  * being added, this should always be the last step.
162                  */
163                 $this->finalPackageChunks['is_complete'] = true;
164         }
165
166         /**
167          * Adds all chunks if the last one verifies as a 'final chunk'.
168          *
169          * @param       $chunks         An array with chunks, the last one should be a 'final'
170          * @return      void
171          * @throws      FinalChunkVerificationException         If the final chunk does not start with 'EOP:'
172          */
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);
178                 } // END - if
179
180                 // Add all chunks to the FIFO stacker
181                 foreach ($chunks as $chunk) {
182                         // Add the chunk
183                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk);
184                 } // END - foreach
185         }
186
187         /**
188          * Checks whether unhandled chunks are available
189          *
190          * @return      $unhandledChunks        Whether unhandled chunks are left
191          */
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;
195
196                 // Return result
197                 return $unhandledChunks;
198         }
199
200         /**
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
203          * iterator.
204          *
205          * @return      void
206          */
207         public function handleAvailableChunksWithFinal () {
208                 // First check if there are undhandled chunks available
209                 assert($this->ifUnhandledChunksWithFinalAvailable());
210
211                 // Get an entry from the stacker
212                 $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
213
214                 // Split the string with proper separator character
215                 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk);
216
217                 /*
218                  * Make sure three elements are always found:
219                  * 0 = Hash
220                  * 1 = Serial number
221                  * 2 = Raw data
222                  */
223                 assert(count($chunkSplits) == 3);
224
225                 // Is the generated hash from data same ("valid") as given hash?
226                 if (!$this->isChunkHashValid($chunkSplits)) {
227                         // Do some logging
228                         $this->debugOutput('CHUNK-HANDLER: Chunk content is not validating against given hash.');
229
230                         // Re-request this chunk (trust the hash in index # 0)
231                         $this->rerequestChunkBySplitsArray($chunkSplits);
232
233                         // Don't process this chunk
234                         return;
235                 } // END - if
236
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])) {
239                         // Do some logging
240                         $this->debugOutput('CHUNK-HANDLER: Chunk serial numberĀ for hash ' . $chunkSplits[self::CHUNK_SPLITS_INDEX_HASH] . ' is invalid.');
241
242                         // Re-request this chunk
243                         $this->rerequestChunkBySplitsArray($chunkSplits);
244
245                         // Don't process this chunk
246                         return;
247                 } // END - if
248
249                 /*
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
252                  * peer.
253                  *
254                  * And also the serial number is valid (basicly) at this point. Now the
255                  * chunk can be added to the final array.
256                  */
257                 $this->addChunkToFinalArray($chunkSplits);
258
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();
263                 } // END - if
264         }
265
266         /**
267          * Checks whether unassembled chunks are available (ready) in final array
268          *
269          * @return      $unassembledChunksAvailable             Whether unassembled chunks are available
270          */
271         public function ifUnassembledChunksAvailable () {
272                 // For now do only check the array element 'is_complete'
273                 $unassembledChunksAvailable = ($this->finalPackageChunks['is_complete'] === true);
274
275                 // Return status
276                 return $unassembledChunksAvailable;
277         }
278
279         /**
280          * Assembles all chunks (except EOP and "hash chunk") back together to the original package data.
281          *
282          * This is done by the following steps:
283          *
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.
291          *
292          * @return      void
293          */
294         public function assembleChunksFromFinalArray () {
295                 // Make sure the final array is really completed
296                 assert($this->ifUnassembledChunksAvailable());
297
298                 $this->partialStub('Please implement this method.');
299         }
300 }
301
302 // [EOF]
303 ?>