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;
38 // Message status codes
39 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
42 * Separator for all bootstrap node entries
44 const BOOTSTRAP_NODES_SEPARATOR = ';';
47 * An instance of a node
49 private $nodeInstance = NULL;
52 * An instance of a communicator
54 private $communicatorInstance = NULL;
57 * An instance of a crawler
59 private $crawlerInstance = NULL;
62 * An instance of a cruncher
64 private $cruncherInstance = NULL;
67 * An instance of a miner
69 private $minerInstance = NULL;
74 private $listenerInstance = NULL;
77 * A network package handler instance
79 private $packageInstance = NULL;
82 * A Receivable instance
84 private $receiverInstance = NULL;
89 private $stateInstance = NULL;
92 * Listener pool instance
94 private $listenerPoolInstance = NULL;
99 private $fragmenterInstance = NULL;
104 private $decoderInstance = NULL;
109 private $assemblerInstance = NULL;
112 * Name of used protocol
114 private $protocolName = 'invalid';
117 * Protected constructor
119 * @param $className Name of the class
122 protected function __construct ($className) {
123 // Call parent constructor
124 parent::__construct($className);
128 * Getter for node instance
130 * @return $nodeInstance An instance of a node node
132 public final function getNodeInstance () {
133 return $this->nodeInstance;
137 * Setter for node instance
139 * @param $nodeInstance An instance of a node node
142 protected final function setNodeInstance (NodeHelper $nodeInstance) {
143 $this->nodeInstance = $nodeInstance;
147 * Getter for communicator instance
149 * @return $communicatorInstance An instance of a Communicator class
151 public final function getCommunicatorInstance () {
152 return $this->communicatorInstance;
156 * Setter for communicator instance
158 * @param $communicatorInstance An instance of a Communicator class
161 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
162 $this->communicatorInstance = $communicatorInstance;
166 * Getter for crawler instance
168 * @return $crawlerInstance An instance of a Crawler class
170 public final function getCrawlerInstance () {
171 return $this->crawlerInstance;
175 * Setter for crawler instance
177 * @param $crawlerInstance An instance of a Crawler class
180 protected final function setCrawlerInstance (Crawler $crawlerInstance) {
181 $this->crawlerInstance = $crawlerInstance;
185 * Getter for cruncher instance
187 * @return $cruncherInstance An instance of a cruncher cruncher
189 public final function getCruncherInstance () {
190 return $this->cruncherInstance;
194 * Setter for cruncher instance
196 * @param $cruncherInstance An instance of a cruncher cruncher
199 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
200 $this->cruncherInstance = $cruncherInstance;
204 * Getter for miner instance
206 * @return $minerInstance An instance of a miner miner
208 public final function getMinerInstance () {
209 return $this->minerInstance;
213 * Setter for miner instance
215 * @param $minerInstance An instance of a miner miner
218 protected final function setMinerInstance (MinerHelper $minerInstance) {
219 $this->minerInstance = $minerInstance;
223 * Setter for listener instance
225 * @param $listenerInstance A Listenable instance
228 protected final function setListenerInstance (Listenable $listenerInstance) {
229 $this->listenerInstance = $listenerInstance;
233 * Getter for listener instance
235 * @return $listenerInstance A Listenable instance
237 protected final function getListenerInstance () {
238 return $this->listenerInstance;
242 * Setter for network package handler instance
244 * @param $packageInstance The network package instance we shall set
247 protected final function setPackageInstance (Deliverable $packageInstance) {
248 $this->packageInstance = $packageInstance;
252 * Getter for network package handler instance
254 * @return $packageInstance The network package handler instance we shall set
256 protected final function getPackageInstance () {
257 return $this->packageInstance;
261 * Setter for receiver instance
263 * @param $receiverInstance A Receivable instance we shall set
266 protected final function setReceiverInstance (Receivable $receiverInstance) {
267 $this->receiverInstance = $receiverInstance;
271 * Getter for receiver instance
273 * @return $receiverInstance A Receivable instance we shall get
275 protected final function getReceiverInstance () {
276 return $this->receiverInstance;
280 * Setter for state instance
282 * @param $stateInstance A Stateable instance
285 public final function setStateInstance (Stateable $stateInstance) {
286 $this->stateInstance = $stateInstance;
290 * Getter for state instance
292 * @return $stateInstance A Stateable instance
294 public final function getStateInstance () {
295 return $this->stateInstance;
299 * Setter for listener pool instance
301 * @param $listenerPoolInstance The new listener pool instance
304 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
305 $this->listenerPoolInstance = $listenerPoolInstance;
309 * Getter for listener pool instance
311 * @return $listenerPoolInstance Our current listener pool instance
313 public final function getListenerPoolInstance () {
314 return $this->listenerPoolInstance;
318 * Setter for fragmenter instance
320 * @param $fragmenterInstance A Fragmentable instance
323 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
324 $this->fragmenterInstance = $fragmenterInstance;
328 * Getter for fragmenter instance
330 * @return $fragmenterInstance A Fragmentable instance
332 protected final function getFragmenterInstance () {
333 return $this->fragmenterInstance;
337 * Setter for decoder instance
339 * @param $decoderInstance A Decodeable instance
342 protected final function setDecoderInstance (Decodeable $decoderInstance) {
343 $this->decoderInstance = $decoderInstance;
347 * Getter for decoder instance
349 * @return $decoderInstance A Decodeable instance
351 protected final function getDecoderInstance () {
352 return $this->decoderInstance;
356 * Setter for assembler instance
358 * @param $assemblerInstance A Decodeable instance
361 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
362 $this->assemblerInstance = $assemblerInstance;
366 * Getter for assembler instance
368 * @return $assemblerInstance A Decodeable instance
370 protected final function getAssemblerInstance () {
371 return $this->assemblerInstance;
377 * @param $nodeId The new node id
380 protected final function setNodeId ($nodeId) {
382 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
388 * @return $nodeId Current node id
390 public final function getNodeId () {
391 // Get it from config
392 return $this->getConfigInstance()->getConfigEntry('node_id');
396 * Setter for private key
398 * @param $privateKey The new private key
401 protected final function setPrivateKey ($privateKey) {
403 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
407 * Getter for private key
409 * @return $privateKey Current private key
411 public final function getPrivateKey () {
412 // Get it from config
413 return $this->getConfigInstance()->getConfigEntry('private_key');
417 * Setter for private key hash
419 * @param $privateKeyHash The new private key hash
422 protected final function setPrivateKeyHash ($privateKeyHash) {
424 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
428 * Getter for private key hash
430 * @return $privateKeyHash Current private key hash
432 public final function getPrivateKeyHash () {
433 // Get it from config
434 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
438 * Setter for session id
440 * @param $sessionId The new session id
443 protected final function setSessionId ($sessionId) {
444 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
448 * Getter for session id
450 * @return $sessionId Current session id
452 public final function getSessionId () {
453 return $this->getConfigInstance()->getConfigEntry('session_id');
457 * Getter for protocol name
459 * @return $protocolName Name of used protocol
461 public final function getProtocolName () {
462 return $this->protocolName;
466 * Setter for protocol name
468 * @param $protocolName Name of used protocol
471 protected final function setProtocolName ($protocolName) {
472 $this->protocolName = $protocolName;
476 * Getter for protocol name
478 * @return $protocolName Name of used protocol
480 public final function getProtocolName () {
481 return $this->protocolName;
485 * Setter for protocol name
487 * @param $protocolName Name of used protocol
490 protected final function setProtocolName ($protocolName) {
491 $this->protocolName = $protocolName;
495 * Constructs a callable method name from given socket error code. If the
496 * method is not found, a generic one is used.
498 * @param $errorCode Error code from socket_last_error()
499 * @return $handlerName Call-back method name for the error handler
500 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
502 protected function getSocketErrorHandlerFromCode ($errorCode) {
503 // Create a name from translated error code
504 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
506 // Is the call-back method there?
507 if (!method_exists($this, $handlerName)) {
508 // Please implement this
509 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
517 * Handles socket error for given socket resource and peer data. This method
518 * validates $socketResource if it is a valid resource (see is_resource())
519 * but assumes valid data in array $recipientData, except that
520 * count($recipientData) is always 2.
522 * @param $method Value of __METHOD__ from calling method
523 * @param $line Value of __LINE__ from calling method
524 * @param $socketResource A valid socket resource
525 * @param $recipientData An array with two elements: 0=IP number, 1=port number
527 * @throws InvalidSocketException If $socketResource is no socket resource
528 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
530 protected final function handleSocketError ($method, $line, $socketResource, array $recipientData) {
531 // This method handles only socket resources
532 if (!is_resource($socketResource)) {
533 // No resource, abort here
534 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
537 // Check count of array, should be two
538 assert(count($recipientData) == 2);
540 // Get error code for first validation (0 is not an error)
541 $errorCode = socket_last_error($socketResource);
543 // If the error code is zero, someone called this method without an error
544 if ($errorCode == 0) {
545 // No error detected (or previously cleared outside this method)
546 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
549 // Get handler (method) name
550 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
552 // Call-back the error handler method
553 call_user_func_array(array($this, $handlerName), array($socketResource, $recipientData));
555 // Finally clear the error because it has been handled
556 socket_clear_error($socketResource);
560 * Checks whether the final (last) chunk is valid
562 * @param $chunks An array with chunks and (hopefully) a valid final chunk
563 * @return $isValid Whether the final (last) chunk is valid
565 protected function isValidFinalChunk (array $chunks) {
566 // Default is all fine
569 // Split the (possible) EOP chunk
570 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
572 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
573 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits, TRUE));
574 assert(count($chunkSplits) == 3);
576 // Validate final chunk
577 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
580 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
581 // CHUNK_HASH_SEPARATOR shall only be found once
590 * Translates socket error codes into our own internal names which can be
591 * used for call-backs.
593 * @param $errorCode The error code from socket_last_error() to be translated
594 * @return $errorName The translated name (all lower-case, with underlines)
596 public function translateSocketErrorCodeToName ($errorCode) {
597 // Nothing bad happened by default
598 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
600 // Is the code a number, then we have to change it
601 switch ($errorCode) {
602 case 0: // Silently ignored, the socket is connected
605 case 11: // "Resource temporary unavailable"
606 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
609 case 32: // "Broken pipe"
610 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
613 case 104: // "Connection reset by peer"
614 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
617 case 107: // "Transport end-point not connected"
618 case 134: // On some (?) systems for 'transport end-point not connected'
619 // @TODO On some systems it is 134, on some 107?
620 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
623 case 110: // "Connection timed out"
624 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
627 case 111: // "Connection refused"
628 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
631 case 113: // "No route to host"
632 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
635 case 114: // "Operation already in progress"
636 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
639 case 115: // "Operation now in progress"
640 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
643 default: // Everything else <> 0
644 // Unhandled error code detected, so first debug it because we may want to handle it like the others
645 self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
647 // Change it only in this class
648 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
652 // Return translated name
657 * Shuts down a given socket resource. This method does only ease calling
660 * @param $socketResource A valid socket resource
663 public function shutdownSocket ($socketResource) {
665 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
667 // Set socket resource
668 $this->setSocketResource($socketResource);
670 // Get a visitor instance
671 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
674 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
677 $this->accept($visitorInstance);
681 * Half-shuts down a given socket resource. This method does only ease calling
682 * an other visitor than shutdownSocket() does.
684 * @param $socketResource A valid socket resource
687 public function halfShutdownSocket ($socketResource) {
689 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
691 // Set socket resource
692 $this->setSocketResource($socketResource);
694 // Get a visitor instance
695 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
698 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
701 $this->accept($visitorInstance);
705 * "Getter" for a printable state name
707 * @return $stateName Name of the node's state in a printable format
709 public final function getPrintableState () {
713 // Get the state instance
714 $stateInstance = $this->getStateInstance();
716 // Is it an instance of Stateable?
717 if ($stateInstance instanceof Stateable) {
718 // Then use that state name
719 $stateName = $stateInstance->getStateName();