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