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