3 * A general hub system class
5 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
24 class BaseHubSystem extends BaseFrameworkSystem {
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;
39 // Message status codes
40 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
43 * Separator for all bootstrap node entries
45 const BOOTSTRAP_NODES_SEPARATOR = ';';
48 * An instance of a node
50 private $nodeInstance = NULL;
53 * An instance of a communicator
55 private $communicatorInstance = NULL;
58 * An instance of a crawler
60 private $crawlerInstance = NULL;
63 * An instance of a cruncher
65 private $cruncherInstance = NULL;
68 * An instance of a miner
70 private $minerInstance = NULL;
73 * A network package handler instance
75 private $packageInstance = NULL;
78 * A Receivable instance
80 private $receiverInstance = NULL;
85 private $stateInstance = NULL;
88 * Listener pool instance
90 private $listenerPoolInstance = NULL;
95 private $fragmenterInstance = NULL;
100 private $decoderInstance = NULL;
105 private $assemblerInstance = NULL;
110 private $infoInstance = NULL;
113 * Name of used protocol
115 private $protocolName = 'invalid';
118 * Protected constructor
120 * @param $className Name of the class
123 protected function __construct ($className) {
124 // Call parent constructor
125 parent::__construct($className);
129 * Getter for node instance
131 * @return $nodeInstance An instance of a node node
133 public final function getNodeInstance () {
134 return $this->nodeInstance;
138 * Setter for node instance
140 * @param $nodeInstance An instance of a node node
143 protected final function setNodeInstance (NodeHelper $nodeInstance) {
144 $this->nodeInstance = $nodeInstance;
148 * Getter for communicator instance
150 * @return $communicatorInstance An instance of a Communicator class
152 public final function getCommunicatorInstance () {
153 return $this->communicatorInstance;
157 * Setter for communicator instance
159 * @param $communicatorInstance An instance of a Communicator class
162 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
163 $this->communicatorInstance = $communicatorInstance;
167 * Getter for crawler instance
169 * @return $crawlerInstance An instance of a Crawler class
171 public final function getCrawlerInstance () {
172 return $this->crawlerInstance;
176 * Setter for crawler instance
178 * @param $crawlerInstance An instance of a Crawler class
181 protected final function setCrawlerInstance (Crawler $crawlerInstance) {
182 $this->crawlerInstance = $crawlerInstance;
186 * Getter for cruncher instance
188 * @return $cruncherInstance An instance of a cruncher cruncher
190 public final function getCruncherInstance () {
191 return $this->cruncherInstance;
195 * Setter for cruncher instance
197 * @param $cruncherInstance An instance of a cruncher cruncher
200 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
201 $this->cruncherInstance = $cruncherInstance;
205 * Getter for miner instance
207 * @return $minerInstance An instance of a miner miner
209 public final function getMinerInstance () {
210 return $this->minerInstance;
214 * Setter for miner instance
216 * @param $minerInstance An instance of a miner miner
219 protected final function setMinerInstance (MinerHelper $minerInstance) {
220 $this->minerInstance = $minerInstance;
224 * Setter for network package handler instance
226 * @param $packageInstance The network package instance we shall set
229 protected final function setPackageInstance (Deliverable $packageInstance) {
230 $this->packageInstance = $packageInstance;
234 * Getter for network package handler instance
236 * @return $packageInstance The network package handler instance we shall set
238 protected final function getPackageInstance () {
239 return $this->packageInstance;
243 * Setter for receiver instance
245 * @param $receiverInstance A Receivable instance we shall set
248 protected final function setReceiverInstance (Receivable $receiverInstance) {
249 $this->receiverInstance = $receiverInstance;
253 * Getter for receiver instance
255 * @return $receiverInstance A Receivable instance we shall get
257 protected final function getReceiverInstance () {
258 return $this->receiverInstance;
262 * Setter for state instance
264 * @param $stateInstance A Stateable instance
267 public final function setStateInstance (Stateable $stateInstance) {
268 $this->stateInstance = $stateInstance;
272 * Getter for state instance
274 * @return $stateInstance A Stateable instance
276 public final function getStateInstance () {
277 return $this->stateInstance;
281 * Setter for listener pool instance
283 * @param $listenerPoolInstance The new listener pool instance
286 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
287 $this->listenerPoolInstance = $listenerPoolInstance;
291 * Getter for listener pool instance
293 * @return $listenerPoolInstance Our current listener pool instance
295 public final function getListenerPoolInstance () {
296 return $this->listenerPoolInstance;
300 * Setter for fragmenter instance
302 * @param $fragmenterInstance A Fragmentable instance
305 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
306 $this->fragmenterInstance = $fragmenterInstance;
310 * Getter for fragmenter instance
312 * @return $fragmenterInstance A Fragmentable instance
314 protected final function getFragmenterInstance () {
315 return $this->fragmenterInstance;
319 * Setter for decoder instance
321 * @param $decoderInstance A Decodeable instance
324 protected final function setDecoderInstance (Decodeable $decoderInstance) {
325 $this->decoderInstance = $decoderInstance;
329 * Getter for decoder instance
331 * @return $decoderInstance A Decodeable instance
333 protected final function getDecoderInstance () {
334 return $this->decoderInstance;
338 * Setter for assembler instance
340 * @param $assemblerInstance A Decodeable instance
343 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
344 $this->assemblerInstance = $assemblerInstance;
348 * Getter for assembler instance
350 * @return $assemblerInstance A Decodeable instance
352 protected final function getAssemblerInstance () {
353 return $this->assemblerInstance;
357 * Setter for info instance
359 * @param $infoInstance A ShareableInfo instance
362 protected final function setInfoInstance (ShareableInfo $infoInstance) {
363 $this->infoInstance = $infoInstance;
367 * Getter for info instance
369 * @return $infoInstance A Decodeable instance
371 public final function getInfoInstance () {
372 return $this->infoInstance;
378 * @param $nodeId The new node id
381 protected final function setNodeId ($nodeId) {
383 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
389 * @return $nodeId Current node id
391 public final function getNodeId () {
392 // Get it from config
393 return $this->getConfigInstance()->getConfigEntry('node_id');
397 * Setter for private key
399 * @param $privateKey The new private key
402 protected final function setPrivateKey ($privateKey) {
404 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
408 * Getter for private key
410 * @return $privateKey Current private key
412 public final function getPrivateKey () {
413 // Get it from config
414 return $this->getConfigInstance()->getConfigEntry('private_key');
418 * Setter for private key hash
420 * @param $privateKeyHash The new private key hash
423 protected final function setPrivateKeyHash ($privateKeyHash) {
425 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
429 * Getter for private key hash
431 * @return $privateKeyHash Current private key hash
433 public final function getPrivateKeyHash () {
434 // Get it from config
435 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
439 * Setter for session id
441 * @param $sessionId The new session id
444 protected final function setSessionId ($sessionId) {
445 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
449 * Getter for session id
451 * @return $sessionId Current session id
453 public final function getSessionId () {
454 return $this->getConfigInstance()->getConfigEntry('session_id');
458 * Getter for protocol name
460 * @return $protocolName Name of used protocol
462 public final function getProtocolName () {
463 return $this->protocolName;
467 * Setter for protocol name
469 * @param $protocolName Name of used protocol
472 protected final function setProtocolName ($protocolName) {
473 $this->protocolName = $protocolName;
477 * Constructs a callable method name from given socket error code. If the
478 * method is not found, a generic one is used.
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
484 protected function getSocketErrorHandlerFromCode ($errorCode) {
485 // Create a name from translated error code
486 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
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);
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.
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
509 * @throws InvalidSocketException If $socketResource is no socket resource
510 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
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);
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]));
525 // Get error code for first validation (0 is not an error)
526 $errorCode = socket_last_error($socketResource);
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);
534 // Get handler (method) name
535 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
537 // Call-back the error handler method
538 call_user_func_array(array($this, $handlerName), array($socketResource, $unlData));
540 // Finally clear the error because it has been handled
541 socket_clear_error($socketResource);
545 * Checks whether the final (last) chunk is valid
547 * @param $chunks An array with chunks and (hopefully) a valid final chunk
548 * @return $isValid Whether the final (last) chunk is valid
550 protected function isValidFinalChunk (array $chunks) {
551 // Default is all fine
554 // Split the (possible) EOP chunk
555 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
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);
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) {
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
575 * Translates socket error codes into our own internal names which can be
576 * used for call-backs.
578 * @param $errorCode The error code from socket_last_error() to be translated
579 * @return $errorName The translated name (all lower-case, with underlines)
581 public function translateSocketErrorCodeToName ($errorCode) {
582 // Nothing bad happened by default
583 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
585 // Is the code a number, then we have to change it
586 switch ($errorCode) {
587 case 0: // Silently ignored, the socket is connected
590 case 11: // "Resource temporary unavailable"
591 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
594 case 32: // "Broken pipe"
595 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
598 case 104: // "Connection reset by peer"
599 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
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;
608 case 110: // "Connection timed out"
609 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
612 case 111: // "Connection refused"
613 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
616 case 113: // "No route to host"
617 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
620 case 114: // "Operation already in progress"
621 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
624 case 115: // "Operation now in progress"
625 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
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));
632 // Change it only in this class
633 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
637 // Return translated name
642 * Shuts down a given socket resource. This method does only ease calling
645 * @param $socketResource A valid socket resource
648 public function shutdownSocket ($socketResource) {
650 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
652 // Set socket resource
653 $this->setSocketResource($socketResource);
655 // Get a visitor instance
656 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
659 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
662 $this->accept($visitorInstance);
666 * Half-shuts down a given socket resource. This method does only ease calling
667 * an other visitor than shutdownSocket() does.
669 * @param $socketResource A valid socket resource
672 public function halfShutdownSocket ($socketResource) {
674 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
676 // Set socket resource
677 $this->setSocketResource($socketResource);
679 // Get a visitor instance
680 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
683 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
686 $this->accept($visitorInstance);
690 * "Getter" for a printable state name
692 * @return $stateName Name of the node's state in a printable format
694 public final function getPrintableState () {
698 // Get the state instance
699 $stateInstance = $this->getStateInstance();
701 // Is it an instance of Stateable?
702 if ($stateInstance instanceof Stateable) {
703 // Then use that state name
704 $stateName = $stateInstance->getStateName();