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