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