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