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