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