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