]> git.mxchange.org Git - hub.git/blob - application/hub/main/class_BaseHubSystem.php
Made lower to upper case:
[hub.git] / application / hub / main / class_BaseHubSystem.php
1 <?php
2 /**
3  * A general hub system class
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 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 BaseHubSystem extends BaseFrameworkSystem {
25         // Exception codes
26         const EXCEPTION_UNSUPPORTED_ERROR_HANDLER     = 0x900;
27         const EXCEPTION_CHUNK_ALREADY_ASSEMBLED       = 0x901;
28         const EXCEPTION_ANNOUNCEMENT_NOT_ACCEPTED     = 0x902;
29         const EXCEPTION_INVALID_CONNECTION_TYPE       = 0x903;
30         const EXCEPTION_ANNOUNCEMENT_NOT_ATTEMPTED    = 0x904;
31         const EXCEPTION_BASE64_ENCODING_NOT_MODULO_4  = 0x905;
32         const EXCEPTION_NODE_SESSION_ID_NOT_VERIFYING = 0x906;
33         const EXCEPTION_REQUEST_NOT_ACCEPTED          = 0x907;
34
35         // Message status codes
36         const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
37
38         /**
39          * Separator for all bootstrap node entries
40          */
41         const BOOTSTRAP_NODES_SEPARATOR = ';';
42
43         /**
44          * An instance of a node
45          */
46         private $nodeInstance = NULL;
47
48         /**
49          * An instance of a cruncher
50          */
51         private $cruncherInstance = NULL;
52
53         /**
54          * Listener instance
55          */
56         private $listenerInstance = NULL;
57
58         /**
59          * A network package handler instance
60          */
61         private $packageInstance = NULL;
62
63         /**
64          * A Receivable instance
65          */
66         private $receiverInstance = NULL;
67
68         /**
69          * State instance
70          */
71         private $stateInstance = NULL;
72
73         /**
74          * Listener pool instance
75          */
76         private $listenerPoolInstance = NULL;
77
78         /**
79          * Fragmenter instance
80          */
81         private $fragmenterInstance = NULL;
82
83         /**
84          * Decoder instance
85          */
86         private $decoderInstance = NULL;
87
88         /**
89          * Assembler instance
90          */
91         private $assemblerInstance = NULL;
92
93         /**
94          * Protected constructor
95          *
96          * @param       $className      Name of the class
97          * @return      void
98          */
99         protected function __construct ($className) {
100                 // Call parent constructor
101                 parent::__construct($className);
102         }
103
104         /**
105          * Getter for node instance
106          *
107          * @return      $nodeInstance   An instance of a node node
108          */
109         public final function getNodeInstance () {
110                 return $this->nodeInstance;
111         }
112
113         /**
114          * Setter for node instance
115          *
116          * @param       $nodeInstance   An instance of a node node
117          * @return      void
118          */
119         protected final function setNodeInstance (NodeHelper $nodeInstance) {
120                 $this->nodeInstance = $nodeInstance;
121         }
122
123         /**
124          * Getter for cruncher instance
125          *
126          * @return      $cruncherInstance       An instance of a cruncher cruncher
127          */
128         public final function getCruncherInstance () {
129                 return $this->cruncherInstance;
130         }
131
132         /**
133          * Setter for cruncher instance
134          *
135          * @param       $cruncherInstance       An instance of a cruncher cruncher
136          * @return      void
137          */
138         protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
139                 $this->cruncherInstance = $cruncherInstance;
140         }
141
142         /**
143          * Setter for listener instance
144          *
145          * @param       $listenerInstance       A Listenable instance
146          * @return      void
147          */
148         protected final function setListenerInstance (Listenable $listenerInstance) {
149                 $this->listenerInstance = $listenerInstance;
150         }
151
152         /**
153          * Getter for listener instance
154          *
155          * @return      $listenerInstance       A Listenable instance
156          */
157         protected final function getListenerInstance () {
158                 return $this->listenerInstance;
159         }
160
161         /**
162          * Setter for network package handler instance
163          *
164          * @param       $packageInstance        The network package instance we shall set
165          * @return      void
166          */
167         protected final function setPackageInstance (Deliverable $packageInstance) {
168                 $this->packageInstance = $packageInstance;
169         }
170
171         /**
172          * Getter for network package handler instance
173          *
174          * @return      $packageInstance        The network package handler instance we shall set
175          */
176         protected final function getPackageInstance () {
177                 return $this->packageInstance;
178         }
179
180         /**
181          * Setter for receiver instance
182          *
183          * @param       $receiverInstance       A Receivable instance we shall set
184          * @return      void
185          */
186         protected final function setReceiverInstance (Receivable $receiverInstance) {
187                 $this->receiverInstance = $receiverInstance;
188         }
189
190         /**
191          * Getter for receiver instance
192          *
193          * @return      $receiverInstance       A Receivable instance we shall get
194          */
195         protected final function getReceiverInstance () {
196                 return $this->receiverInstance;
197         }
198
199         /**
200          * Setter for state instance
201          *
202          * @param       $stateInstance  A Stateable instance
203          * @return      void
204          */
205         public final function setStateInstance (Stateable $stateInstance) {
206                 $this->stateInstance = $stateInstance;
207         }
208
209         /**
210          * Getter for state instance
211          *
212          * @return      $stateInstance  A Stateable instance
213          */
214         public final function getStateInstance () {
215                 return $this->stateInstance;
216         }
217
218         /**
219          * Setter for listener pool instance
220          *
221          * @param       $listenerPoolInstance   The new listener pool instance
222          * @return      void
223          */
224         protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
225                 $this->listenerPoolInstance = $listenerPoolInstance;
226         }
227
228         /**
229          * Getter for listener pool instance
230          *
231          * @return      $listenerPoolInstance   Our current listener pool instance
232          */
233         public final function getListenerPoolInstance () {
234                 return $this->listenerPoolInstance;
235         }
236
237         /**
238          * Setter for fragmenter instance
239          *
240          * @param       $fragmenterInstance             A Fragmentable instance
241          * @return      void
242          */
243         protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
244                 $this->fragmenterInstance = $fragmenterInstance;
245         }
246
247         /**
248          * Getter for fragmenter instance
249          *
250          * @return      $fragmenterInstance             A Fragmentable instance
251          */
252         protected final function getFragmenterInstance () {
253                 return $this->fragmenterInstance;
254         }
255
256         /**
257          * Setter for decoder instance
258          *
259          * @param       $decoderInstance        A Decodeable instance
260          * @return      void
261          */
262         protected final function setDecoderInstance (Decodeable $decoderInstance) {
263                 $this->decoderInstance = $decoderInstance;
264         }
265
266         /**
267          * Getter for decoder instance
268          *
269          * @return      $decoderInstance        A Decodeable instance
270          */
271         protected final function getDecoderInstance () {
272                 return $this->decoderInstance;
273         }
274
275         /**
276          * Setter for assembler instance
277          *
278          * @param       $assemblerInstance      A Decodeable instance
279          * @return      void
280          */
281         protected final function setAssemblerInstance (Assembler $assemblerInstance) {
282                 $this->assemblerInstance = $assemblerInstance;
283         }
284
285         /**
286          * Getter for assembler instance
287          *
288          * @return      $assemblerInstance      A Decodeable instance
289          */
290         protected final function getAssemblerInstance () {
291                 return $this->assemblerInstance;
292         }
293
294         /**
295          * Setter for node id
296          *
297          * @param       $nodeId         The new node id
298          * @return      void
299          */
300         protected final function setNodeId ($nodeId) {
301                 // Set it config now
302                 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
303         }
304
305         /**
306          * Getter for node id
307          *
308          * @return      $nodeId         Current node id
309          */
310         public final function getNodeId () {
311                 // Get it from config
312                 return $this->getConfigInstance()->getConfigEntry('node_id');
313         }
314
315         /**
316          * Setter for private key
317          *
318          * @param       $privateKey             The new private key
319          * @return      void
320          */
321         protected final function setPrivateKey ($privateKey) {
322                 // Set it config now
323                 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
324         }
325
326         /**
327          * Getter for private key
328          *
329          * @return      $privateKey             Current private key
330          */
331         public final function getPrivateKey () {
332                 // Get it from config
333                 return $this->getConfigInstance()->getConfigEntry('private_key');
334         }
335
336         /**
337          * Setter for private key hash
338          *
339          * @param       $privateKeyHash         The new private key hash
340          * @return      void
341          */
342         protected final function setPrivateKeyHash ($privateKeyHash) {
343                 // Set it config now
344                 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
345         }
346
347         /**
348          * Getter for private key hash
349          *
350          * @return      $privateKeyHash         Current private key hash
351          */
352         public final function getPrivateKeyHash () {
353                 // Get it from config
354                 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
355         }
356
357         /**
358          * Setter for session id
359          *
360          * @param       $sessionId              The new session id
361          * @return      void
362          */
363         protected final function setSessionId ($sessionId) {
364                 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
365         }
366
367         /**
368          * Getter for session id
369          *
370          * @return      $sessionId              Current session id
371          */
372         public final function getSessionId () {
373                 return $this->getConfigInstance()->getConfigEntry('session_id');
374         }
375
376         /**
377          * Constructs a callable method name from given socket error code. If the
378          * method is not found, a generic one is used.
379          *
380          * @param       $errorCode              Error code from socket_last_error()
381          * @return      $handlerName    Call-back method name for the error handler
382          * @throws      UnsupportedSocketErrorHandlerException If the error handler is not implemented
383          */
384         protected function getSocketErrorHandlerFromCode ($errorCode) {
385                 // Create a name from translated error code
386                 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
387
388                 // Is the call-back method there?
389                 if (!method_exists($this, $handlerName)) {
390                         // Please implement this
391                         throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
392                 } // END - if
393
394                 // Return it
395                 return $handlerName;
396         }
397
398         /**
399          * Handles socket error for given socket resource and peer data. This method
400          * validates $socketResource if it is a valid resource (see is_resource())
401          * but assumes valid data in array $recipientData, except that
402          * count($recipientData) is always 2.
403          *
404          * @param       $method                         Value of __METHOD__ from calling method
405          * @param       $line                           Value of __LINE__ from calling method
406          * @param       $socketResource         A valid socket resource
407          * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
408          * @return      void
409          * @throws      InvalidSocketException  If $socketResource is no socket resource
410          * @throws      NoSocketErrorDetectedException  If socket_last_error() gives zero back
411          */
412         protected final function handleSocketError ($method, $line, $socketResource, array $recipientData) {
413                 // This method handles only socket resources
414                 if (!is_resource($socketResource)) {
415                         // No resource, abort here
416                         throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
417                 } // END - if
418
419                 // Check count of array, should be two
420                 assert(count($recipientData) == 2);
421
422                 // Get error code for first validation (0 is not an error)
423                 $errorCode = socket_last_error($socketResource);
424
425                 // If the error code is zero, someone called this method without an error
426                 if ($errorCode == 0) {
427                         // No error detected (or previously cleared outside this method)
428                         throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
429                 } // END - if
430
431                 // Get handler (method) name
432                 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
433
434                 // Call-back the error handler method
435                 call_user_func_array(array($this, $handlerName), array($socketResource, $recipientData));
436
437                 // Finally clear the error because it has been handled
438                 socket_clear_error($socketResource);
439         }
440
441         /**
442          * Checks whether the final (last) chunk is valid
443          *
444          * @param       $chunks         An array with chunks and (hopefully) a valid final chunk
445          * @return      $isValid        Whether the final (last) chunk is valid
446          */
447         protected function isValidFinalChunk (array $chunks) {
448                 // Default is all fine
449                 $isValid = TRUE;
450
451                 // Split the (possible) EOP chunk
452                 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
453
454                 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
455                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits, true));
456                 assert(count($chunkSplits) == 3);
457
458                 // Validate final chunk
459                 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
460                         // Not fine
461                         $isValid = FALSE;
462                 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
463                         // CHUNK_HASH_SEPARATOR shall only be found once
464                         $isValid = FALSE;
465                 }
466
467                 // Return status
468                 return $isValid;
469         }
470
471         /**
472          * Translates socket error codes into our own internal names which can be
473          * used for call-backs.
474          *
475          * @param       $errorCode      The error code from socket_last_error() to be translated
476          * @return      $errorName      The translated name (all lower-case, with underlines)
477          */
478         public function translateSocketErrorCodeToName ($errorCode) {
479                 // Nothing bad happened by default
480                 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
481
482                 // Is the code a number, then we have to change it
483                 switch ($errorCode) {
484                         case 0: // Silently ignored, the socket is connected
485                                 break;
486
487                         case 11:  // "Resource temporary unavailable"
488                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
489                                 break;
490
491                         case 107: // "Transport end-point not connected"
492                         case 134: // On some (?) systems for 'transport end-point not connected'
493                                 // @TODO On some systems it is 134, on some 107?
494                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
495                                 break;
496
497                         case 110: // "Connection timed out"
498                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
499                                 break;
500
501                         case 111: // "Connection refused"
502                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
503                                 break;
504
505                         case 113: // "No route to host"
506                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
507                                 break;
508
509                         case 114: // "Operation already in progress"
510                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
511                                 break;
512
513                         case 115: // "Operation now in progress"
514                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
515                                 break;
516
517                         default: // Everything else <> 0
518                                 // Unhandled error code detected, so first debug it because we may want to handle it like the others
519                                 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
520
521                                 // Change it only in this class
522                                 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
523                                 break;
524                 }
525
526                 // Return translated name
527                 return $errorName;
528         }
529
530         /**
531          * Shuts down a given socket resource. This method does only ease calling
532          * the right visitor.
533          *
534          * @param       $socketResource         A valid socket resource
535          * @return      void
536          */
537         public function shutdownSocket ($socketResource) {
538                 // Debug message
539                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
540
541                 // Set socket resource
542                 $this->setSocketResource($socketResource);
543
544                 // Get a visitor instance
545                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
546
547                 // Debug output
548                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
549
550                 // Call the visitor
551                 $this->accept($visitorInstance);
552         }
553
554         /**
555          * Half-shuts down a given socket resource. This method does only ease calling
556          * an other visitor than shutdownSocket() does.
557          *
558          * @param       $socketResource         A valid socket resource
559          * @return      void
560          */
561         public function halfShutdownSocket ($socketResource) {
562                 // Debug message
563                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
564
565                 // Set socket resource
566                 $this->setSocketResource($socketResource);
567
568                 // Get a visitor instance
569                 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
570
571                 // Debug output
572                 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
573
574                 // Call the visitor
575                 $this->accept($visitorInstance);
576         }
577
578         /**
579          * "Getter" for a printable state name
580          *
581          * @return      $stateName      Name of the node's state in a printable format
582          */
583         public final function getPrintableState () {
584                 // Default is 'null'
585                 $stateName = 'null';
586
587                 // Get the state instance
588                 $stateInstance = $this->getStateInstance();
589
590                 // Is it an instance of Stateable?
591                 if ($stateInstance instanceof Stateable) {
592                         // Then use that state name
593                         $stateName = $stateInstance->getStateName();
594                 } // END - if
595
596                 // Return result
597                 return $stateName;
598         }
599 }
600
601 // [EOF]
602 ?>