3 * A general hub system class
5 * @author Roland Haeder <webmaster@shipsimu.org>
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
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;
108 * Name of used protocol
110 private $protocolName = 'invalid';
113 * Protected constructor
115 * @param $className Name of the class
118 protected function __construct ($className) {
119 // Call parent constructor
120 parent::__construct($className);
124 * Getter for node instance
126 * @return $nodeInstance An instance of a node node
128 public final function getNodeInstance () {
129 return $this->nodeInstance;
133 * Setter for node instance
135 * @param $nodeInstance An instance of a node node
138 protected final function setNodeInstance (NodeHelper $nodeInstance) {
139 $this->nodeInstance = $nodeInstance;
143 * Getter for communicator instance
145 * @return $communicatorInstance An instance of a Communicator class
147 public final function getCommunicatorInstance () {
148 return $this->communicatorInstance;
152 * Setter for communicator instance
154 * @param $communicatorInstance An instance of a Communicator class
157 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
158 $this->communicatorInstance = $communicatorInstance;
162 * Getter for crawler instance
164 * @return $crawlerInstance An instance of a Crawler class
166 public final function getCrawlerInstance () {
167 return $this->crawlerInstance;
171 * Setter for crawler instance
173 * @param $crawlerInstance An instance of a Crawler class
176 protected final function setCrawlerInstance (Crawler $crawlerInstance) {
177 $this->crawlerInstance = $crawlerInstance;
181 * Getter for cruncher instance
183 * @return $cruncherInstance An instance of a cruncher cruncher
185 public final function getCruncherInstance () {
186 return $this->cruncherInstance;
190 * Setter for cruncher instance
192 * @param $cruncherInstance An instance of a cruncher cruncher
195 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
196 $this->cruncherInstance = $cruncherInstance;
200 * Getter for miner instance
202 * @return $minerInstance An instance of a miner miner
204 public final function getMinerInstance () {
205 return $this->minerInstance;
209 * Setter for miner instance
211 * @param $minerInstance An instance of a miner miner
214 protected final function setMinerInstance (MinerHelper $minerInstance) {
215 $this->minerInstance = $minerInstance;
219 * Setter for network package handler instance
221 * @param $packageInstance The network package instance we shall set
224 protected final function setPackageInstance (Deliverable $packageInstance) {
225 $this->packageInstance = $packageInstance;
229 * Getter for network package handler instance
231 * @return $packageInstance The network package handler instance we shall set
233 protected final function getPackageInstance () {
234 return $this->packageInstance;
238 * Setter for receiver instance
240 * @param $receiverInstance A Receivable instance we shall set
243 protected final function setReceiverInstance (Receivable $receiverInstance) {
244 $this->receiverInstance = $receiverInstance;
248 * Getter for receiver instance
250 * @return $receiverInstance A Receivable instance we shall get
252 protected final function getReceiverInstance () {
253 return $this->receiverInstance;
257 * Setter for state instance
259 * @param $stateInstance A Stateable instance
262 public final function setStateInstance (Stateable $stateInstance) {
263 $this->stateInstance = $stateInstance;
267 * Getter for state instance
269 * @return $stateInstance A Stateable instance
271 public final function getStateInstance () {
272 return $this->stateInstance;
276 * Setter for listener pool instance
278 * @param $listenerPoolInstance The new listener pool instance
281 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
282 $this->listenerPoolInstance = $listenerPoolInstance;
286 * Getter for listener pool instance
288 * @return $listenerPoolInstance Our current listener pool instance
290 public final function getListenerPoolInstance () {
291 return $this->listenerPoolInstance;
295 * Setter for fragmenter instance
297 * @param $fragmenterInstance A Fragmentable instance
300 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
301 $this->fragmenterInstance = $fragmenterInstance;
305 * Getter for fragmenter instance
307 * @return $fragmenterInstance A Fragmentable instance
309 protected final function getFragmenterInstance () {
310 return $this->fragmenterInstance;
314 * Setter for decoder instance
316 * @param $decoderInstance A Decodeable instance
319 protected final function setDecoderInstance (Decodeable $decoderInstance) {
320 $this->decoderInstance = $decoderInstance;
324 * Getter for decoder instance
326 * @return $decoderInstance A Decodeable instance
328 protected final function getDecoderInstance () {
329 return $this->decoderInstance;
333 * Setter for assembler instance
335 * @param $assemblerInstance A Decodeable instance
338 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
339 $this->assemblerInstance = $assemblerInstance;
343 * Getter for assembler instance
345 * @return $assemblerInstance A Decodeable instance
347 protected final function getAssemblerInstance () {
348 return $this->assemblerInstance;
354 * @param $nodeId The new node id
357 protected final function setNodeId ($nodeId) {
359 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
365 * @return $nodeId Current node id
367 public final function getNodeId () {
368 // Get it from config
369 return $this->getConfigInstance()->getConfigEntry('node_id');
373 * Setter for private key
375 * @param $privateKey The new private key
378 protected final function setPrivateKey ($privateKey) {
380 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
384 * Getter for private key
386 * @return $privateKey Current private key
388 public final function getPrivateKey () {
389 // Get it from config
390 return $this->getConfigInstance()->getConfigEntry('private_key');
394 * Setter for private key hash
396 * @param $privateKeyHash The new private key hash
399 protected final function setPrivateKeyHash ($privateKeyHash) {
401 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
405 * Getter for private key hash
407 * @return $privateKeyHash Current private key hash
409 public final function getPrivateKeyHash () {
410 // Get it from config
411 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
415 * Setter for session id
417 * @param $sessionId The new session id
420 protected final function setSessionId ($sessionId) {
421 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
425 * Getter for session id
427 * @return $sessionId Current session id
429 public final function getSessionId () {
430 return $this->getConfigInstance()->getConfigEntry('session_id');
434 * Getter for protocol name
436 * @return $protocolName Name of used protocol
438 public final function getProtocolName () {
439 return $this->protocolName;
443 * Setter for protocol name
445 * @param $protocolName Name of used protocol
448 protected final function setProtocolName ($protocolName) {
449 $this->protocolName = $protocolName;
453 * Constructs a callable method name from given socket error code. If the
454 * method is not found, a generic one is used.
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
460 protected function getSocketErrorHandlerFromCode ($errorCode) {
461 // Create a name from translated error code
462 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
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);
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.
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
485 * @throws InvalidSocketException If $socketResource is no socket resource
486 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
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);
495 // Check count of array, should be two
496 assert(count($recipientData) == 2);
498 // Get error code for first validation (0 is not an error)
499 $errorCode = socket_last_error($socketResource);
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);
507 // Get handler (method) name
508 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
510 // Call-back the error handler method
511 call_user_func_array(array($this, $handlerName), array($socketResource, $recipientData));
513 // Finally clear the error because it has been handled
514 socket_clear_error($socketResource);
518 * Checks whether the final (last) chunk is valid
520 * @param $chunks An array with chunks and (hopefully) a valid final chunk
521 * @return $isValid Whether the final (last) chunk is valid
523 protected function isValidFinalChunk (array $chunks) {
524 // Default is all fine
527 // Split the (possible) EOP chunk
528 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
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);
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) {
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
548 * Translates socket error codes into our own internal names which can be
549 * used for call-backs.
551 * @param $errorCode The error code from socket_last_error() to be translated
552 * @return $errorName The translated name (all lower-case, with underlines)
554 public function translateSocketErrorCodeToName ($errorCode) {
555 // Nothing bad happened by default
556 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
558 // Is the code a number, then we have to change it
559 switch ($errorCode) {
560 case 0: // Silently ignored, the socket is connected
563 case 11: // "Resource temporary unavailable"
564 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
567 case 32: // "Broken pipe"
568 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
571 case 104: // "Connection reset by peer"
572 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
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;
581 case 110: // "Connection timed out"
582 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
585 case 111: // "Connection refused"
586 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
589 case 113: // "No route to host"
590 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
593 case 114: // "Operation already in progress"
594 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
597 case 115: // "Operation now in progress"
598 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
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));
605 // Change it only in this class
606 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
610 // Return translated name
615 * Shuts down a given socket resource. This method does only ease calling
618 * @param $socketResource A valid socket resource
621 public function shutdownSocket ($socketResource) {
623 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
625 // Set socket resource
626 $this->setSocketResource($socketResource);
628 // Get a visitor instance
629 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
632 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
635 $this->accept($visitorInstance);
639 * Half-shuts down a given socket resource. This method does only ease calling
640 * an other visitor than shutdownSocket() does.
642 * @param $socketResource A valid socket resource
645 public function halfShutdownSocket ($socketResource) {
647 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
649 // Set socket resource
650 $this->setSocketResource($socketResource);
652 // Get a visitor instance
653 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
656 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
659 $this->accept($visitorInstance);
663 * "Getter" for a printable state name
665 * @return $stateName Name of the node's state in a printable format
667 public final function getPrintableState () {
671 // Get the state instance
672 $stateInstance = $this->getStateInstance();
674 // Is it an instance of Stateable?
675 if ($stateInstance instanceof Stateable) {
676 // Then use that state name
677 $stateName = $stateInstance->getStateName();