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