]> git.mxchange.org Git - hub.git/blob - application/hub/main/handler/chunks/class_ChunkHandler.php
2e56498347221a99c1174291005aa2ab922bf1bc
[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          * The final array for assembling the original package back together
32          */
33         private $finalPackageChunks = array(
34                 // Array for package content
35                 'content' => array(),
36                 // ... and for the hashes
37                 'hashes'  => array()
38         );
39
40         /**
41          * Protected constructor
42          *
43          * @return      void
44          */
45         protected function __construct () {
46                 // Call parent constructor
47                 parent::__construct(__CLASS__);
48
49                 // Set handler name
50                 $this->setHandlerName('chunk');
51         }
52
53         /**
54          * Creates an instance of this class
55          *
56          * @return      $handlerInstance        An instance of a chunk Handler class
57          */
58         public final static function createChunkHandler () {
59                 // Get new instance
60                 $handlerInstance = new ChunkHandler();
61
62                 // Get a FIFO stacker
63                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('chunk_handler_stacker_class');
64
65                 // Init all stacker
66                 $stackerInstance->initStacker(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
67
68                 // Set the stacker in this handler
69                 $handlerInstance->setStackerInstance($stackerInstance);
70
71                 // Get a crypto instance ...
72                 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
73
74                 // ... and set it in this handler
75                 $handlerInstance->setCryptoInstance($cryptoInstance);
76
77                 // Return the prepared instance
78                 return $handlerInstance;
79         }
80
81         /**
82          * Checks whether the hash generated from package content is the same ("valid") as given
83          *
84          * @param       $chunkSplits    An array from a splitted chunk
85          * @return      $isValid                Whether the hash is "valid"
86          */
87         private function isChunkHashValid (array $chunkSplits) {
88                 // Now hash the raw data again
89                 $chunkHash = $this->getCryptoInstance()->hashString($chunkSplits[2], $chunkSplits[0], false);
90
91                 // Debug output
92                 //* NOISY-DEBUG: */ $this->debugOutput('CHUNK-HANDLER: chunkHash=' . $chunkHash . ',chunkSplits[0]=' . $chunkSplits[0] . ',chunkSplits[1]=' . $chunkSplits[1]);
93
94                 // Check it
95                 $isValid = ($chunkSplits[0] === $chunkHash);
96
97                 // ... and return it
98                 return $isValid;
99         }
100
101         /**
102          * Checks whether the given serial number is valid
103          *
104          * @param       $serialNumber   A serial number from a chunk
105          * @return      $isValid                Whether the serial number is valid
106          */
107         private function isSerialNumberValid ($serialNumber) {
108                 // Check it
109                 $isValid = ((strlen($serialNumber) == PackageFragmenter::MAX_SERIAL_LENGTH) && ($this->bigintval($serialNumber, false) === $serialNumber));
110
111                 // Return result
112                 return $isValid;
113         }
114
115         /**
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.
119          *
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.
122          *
123          * @param       $chunkSplits    An array from a splitted chunk
124          * @return      void
125          */
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);
131                 } // END - if
132
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];
135
136                 // ... and the hash as well
137                 $this->finalPackageChunks['hashes'][$chunkSplits[1]] = $chunkSplits[0];
138         }
139
140         /**
141          * Adds all chunks if the last one verifies as a 'final chunk'.
142          *
143          * @param       $chunks         An array with chunks, the last one should be a 'final'
144          * @return      void
145          * @throws      FinalChunkVerificationException         If the final chunk does not start with 'EOP:'
146          */
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);
152                 } // END - if
153
154                 // Add all chunks to the FIFO stacker
155                 foreach ($chunks as $chunk) {
156                         // Add the chunk
157                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP, $chunk);
158                 } // END - foreach
159         }
160
161         /**
162          * Checks whether unhandled chunks are available
163          *
164          * @return      $unhandledChunks        Whether unhandled chunks are left
165          */
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;
169
170                 // Return result
171                 return $unhandledChunks;
172         }
173
174         /**
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
177          * iterator.
178          *
179          * @return      void
180          */
181         public function handleAvailableChunksWithFinal () {
182                 // First check if there are undhandled chunks available
183                 assert($this->ifUnhandledChunksWithFinalAvailable());
184
185                 // Get an entry from the stacker
186                 $chunk = $this->getStackerInstance()->popNamed(self::STACKER_NAME_CHUNKS_WITH_FINAL_EOP);
187
188                 // Split the string with proper separator character
189                 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunk);
190
191                 /*
192                  * Make sure three elements are always found:
193                  * 0 = Hash
194                  * 1 = Serial number
195                  * 2 = Raw data
196                  */
197                 assert(count($chunkSplits) == 3);
198
199                 // Is the generated hash from data same ("valid") as given hash?
200                 if (!$this->isChunkHashValid($chunkSplits)) {
201                         // Do some logging
202                         $this->debugOutput('CHUNK-HANDLER: Chunk content is not validating against given hash.');
203
204                         // Re-request this chunk (trust the hash in index # 0)
205                         $this->rerequestChunkBySplitsArray($chunkSplits);
206
207                         // Don't process this chunk
208                         return;
209                 } // END - if
210
211                 // Is the serial number valid (chars 0-9, length equals PackageFragmenter::MAX_SERIAL_LENGTH)?
212                 if (!$this->isSerialNumberValid($chunkSplits[1])) {
213                         // Do some logging
214                         $this->debugOutput('CHUNK-HANDLER: Chunk serial numberĀ for hash ' . $chunkSplits[0] . ' is invalid.');
215
216                         // Re-request this chunk
217                         $this->rerequestChunkBySplitsArray($chunkSplits);
218
219                         // Don't process this chunk
220                         return;
221                 } // END - if
222
223                 /*
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
226                  * peer.
227                  *
228                  * And also the serial number is valid (basicly) at this point.
229                  *
230                  * Now the chunk can be added to the final array
231                  */
232                 $this->addChunkToFinalArray($chunkSplits);
233         }
234 }
235
236 // [EOF]
237 ?>