3 * A general hub system class
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 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 * Protected constructor
114 * @param $className Name of the class
117 protected function __construct ($className) {
118 // Call parent constructor
119 parent::__construct($className);
123 * Getter for node instance
125 * @return $nodeInstance An instance of a node node
127 public final function getNodeInstance () {
128 return $this->nodeInstance;
132 * Setter for node instance
134 * @param $nodeInstance An instance of a node node
137 protected final function setNodeInstance (NodeHelper $nodeInstance) {
138 $this->nodeInstance = $nodeInstance;
142 * Getter for communicator instance
144 * @return $communicatorInstance An instance of a Communicator class
146 public final function getCommunicatorInstance () {
147 return $this->communicatorInstance;
151 * Setter for communicator instance
153 * @param $communicatorInstance An instance of a Communicator class
156 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
157 $this->communicatorInstance = $communicatorInstance;
161 * Getter for crawler instance
163 * @return $crawlerInstance An instance of a Crawler class
165 public final function getCrawlerInstance () {
166 return $this->crawlerInstance;
170 * Setter for crawler instance
172 * @param $crawlerInstance An instance of a Crawler class
175 protected final function setCrawlerInstance (Crawler $crawlerInstance) {
176 $this->crawlerInstance = $crawlerInstance;
180 * Getter for cruncher instance
182 * @return $cruncherInstance An instance of a cruncher cruncher
184 public final function getCruncherInstance () {
185 return $this->cruncherInstance;
189 * Setter for cruncher instance
191 * @param $cruncherInstance An instance of a cruncher cruncher
194 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
195 $this->cruncherInstance = $cruncherInstance;
199 * Getter for miner instance
201 * @return $minerInstance An instance of a miner miner
203 public final function getMinerInstance () {
204 return $this->minerInstance;
208 * Setter for miner instance
210 * @param $minerInstance An instance of a miner miner
213 protected final function setMinerInstance (MinerHelper $minerInstance) {
214 $this->minerInstance = $minerInstance;
218 * Setter for listener instance
220 * @param $listenerInstance A Listenable instance
223 protected final function setListenerInstance (Listenable $listenerInstance) {
224 $this->listenerInstance = $listenerInstance;
228 * Getter for listener instance
230 * @return $listenerInstance A Listenable instance
232 protected final function getListenerInstance () {
233 return $this->listenerInstance;
237 * Setter for network package handler instance
239 * @param $packageInstance The network package instance we shall set
242 protected final function setPackageInstance (Deliverable $packageInstance) {
243 $this->packageInstance = $packageInstance;
247 * Getter for network package handler instance
249 * @return $packageInstance The network package handler instance we shall set
251 protected final function getPackageInstance () {
252 return $this->packageInstance;
256 * Setter for receiver instance
258 * @param $receiverInstance A Receivable instance we shall set
261 protected final function setReceiverInstance (Receivable $receiverInstance) {
262 $this->receiverInstance = $receiverInstance;
266 * Getter for receiver instance
268 * @return $receiverInstance A Receivable instance we shall get
270 protected final function getReceiverInstance () {
271 return $this->receiverInstance;
275 * Setter for state instance
277 * @param $stateInstance A Stateable instance
280 public final function setStateInstance (Stateable $stateInstance) {
281 $this->stateInstance = $stateInstance;
285 * Getter for state instance
287 * @return $stateInstance A Stateable instance
289 public final function getStateInstance () {
290 return $this->stateInstance;
294 * Setter for listener pool instance
296 * @param $listenerPoolInstance The new listener pool instance
299 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
300 $this->listenerPoolInstance = $listenerPoolInstance;
304 * Getter for listener pool instance
306 * @return $listenerPoolInstance Our current listener pool instance
308 public final function getListenerPoolInstance () {
309 return $this->listenerPoolInstance;
313 * Setter for fragmenter instance
315 * @param $fragmenterInstance A Fragmentable instance
318 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
319 $this->fragmenterInstance = $fragmenterInstance;
323 * Getter for fragmenter instance
325 * @return $fragmenterInstance A Fragmentable instance
327 protected final function getFragmenterInstance () {
328 return $this->fragmenterInstance;
332 * Setter for decoder instance
334 * @param $decoderInstance A Decodeable instance
337 protected final function setDecoderInstance (Decodeable $decoderInstance) {
338 $this->decoderInstance = $decoderInstance;
342 * Getter for decoder instance
344 * @return $decoderInstance A Decodeable instance
346 protected final function getDecoderInstance () {
347 return $this->decoderInstance;
351 * Setter for assembler instance
353 * @param $assemblerInstance A Decodeable instance
356 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
357 $this->assemblerInstance = $assemblerInstance;
361 * Getter for assembler instance
363 * @return $assemblerInstance A Decodeable instance
365 protected final function getAssemblerInstance () {
366 return $this->assemblerInstance;
372 * @param $nodeId The new node id
375 protected final function setNodeId ($nodeId) {
377 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
383 * @return $nodeId Current node id
385 public final function getNodeId () {
386 // Get it from config
387 return $this->getConfigInstance()->getConfigEntry('node_id');
391 * Setter for private key
393 * @param $privateKey The new private key
396 protected final function setPrivateKey ($privateKey) {
398 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
402 * Getter for private key
404 * @return $privateKey Current private key
406 public final function getPrivateKey () {
407 // Get it from config
408 return $this->getConfigInstance()->getConfigEntry('private_key');
412 * Setter for private key hash
414 * @param $privateKeyHash The new private key hash
417 protected final function setPrivateKeyHash ($privateKeyHash) {
419 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
423 * Getter for private key hash
425 * @return $privateKeyHash Current private key hash
427 public final function getPrivateKeyHash () {
428 // Get it from config
429 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
433 * Setter for session id
435 * @param $sessionId The new session id
438 protected final function setSessionId ($sessionId) {
439 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
443 * Getter for session id
445 * @return $sessionId Current session id
447 public final function getSessionId () {
448 return $this->getConfigInstance()->getConfigEntry('session_id');
452 * Constructs a callable method name from given socket error code. If the
453 * method is not found, a generic one is used.
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
459 protected function getSocketErrorHandlerFromCode ($errorCode) {
460 // Create a name from translated error code
461 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
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);
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.
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
484 * @throws InvalidSocketException If $socketResource is no socket resource
485 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
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);
494 // Check count of array, should be two
495 assert(count($recipientData) == 2);
497 // Get error code for first validation (0 is not an error)
498 $errorCode = socket_last_error($socketResource);
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);
506 // Get handler (method) name
507 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
509 // Call-back the error handler method
510 call_user_func_array(array($this, $handlerName), array($socketResource, $recipientData));
512 // Finally clear the error because it has been handled
513 socket_clear_error($socketResource);
517 * Checks whether the final (last) chunk is valid
519 * @param $chunks An array with chunks and (hopefully) a valid final chunk
520 * @return $isValid Whether the final (last) chunk is valid
522 protected function isValidFinalChunk (array $chunks) {
523 // Default is all fine
526 // Split the (possible) EOP chunk
527 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
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);
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) {
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
547 * Translates socket error codes into our own internal names which can be
548 * used for call-backs.
550 * @param $errorCode The error code from socket_last_error() to be translated
551 * @return $errorName The translated name (all lower-case, with underlines)
553 public function translateSocketErrorCodeToName ($errorCode) {
554 // Nothing bad happened by default
555 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
557 // Is the code a number, then we have to change it
558 switch ($errorCode) {
559 case 0: // Silently ignored, the socket is connected
562 case 11: // "Resource temporary unavailable"
563 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
566 case 32: // "Broken pipe"
567 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
570 case 104: // "Connection reset by peer"
571 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
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;
580 case 110: // "Connection timed out"
581 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
584 case 111: // "Connection refused"
585 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
588 case 113: // "No route to host"
589 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
592 case 114: // "Operation already in progress"
593 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
596 case 115: // "Operation now in progress"
597 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
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));
604 // Change it only in this class
605 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
609 // Return translated name
614 * Shuts down a given socket resource. This method does only ease calling
617 * @param $socketResource A valid socket resource
620 public function shutdownSocket ($socketResource) {
622 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
624 // Set socket resource
625 $this->setSocketResource($socketResource);
627 // Get a visitor instance
628 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
631 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
634 $this->accept($visitorInstance);
638 * Half-shuts down a given socket resource. This method does only ease calling
639 * an other visitor than shutdownSocket() does.
641 * @param $socketResource A valid socket resource
644 public function halfShutdownSocket ($socketResource) {
646 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
648 // Set socket resource
649 $this->setSocketResource($socketResource);
651 // Get a visitor instance
652 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
655 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
658 $this->accept($visitorInstance);
662 * "Getter" for a printable state name
664 * @return $stateName Name of the node's state in a printable format
666 public final function getPrintableState () {
670 // Get the state instance
671 $stateInstance = $this->getStateInstance();
673 // Is it an instance of Stateable?
674 if ($stateInstance instanceof Stateable) {
675 // Then use that state name
676 $stateName = $stateInstance->getStateName();