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