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