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 * A network package handler instance
60 private $packageInstance = NULL;
63 * A Receivable instance
65 private $receiverInstance = NULL;
70 private $stateInstance = NULL;
73 * Listener pool instance
75 private $listenerPoolInstance = NULL;
80 private $fragmenterInstance = NULL;
85 private $assemblerInstance = NULL;
90 private $infoInstance = NULL;
93 * Name of used protocol
95 private $protocolName = 'invalid';
98 * Protected constructor
100 * @param $className Name of the class
103 protected function __construct ($className) {
104 // Call parent constructor
105 parent::__construct($className);
109 * Getter for node instance
111 * @return $nodeInstance An instance of a node node
113 public final function getNodeInstance () {
114 return $this->nodeInstance;
118 * Setter for node instance
120 * @param $nodeInstance An instance of a node node
123 protected final function setNodeInstance (NodeHelper $nodeInstance) {
124 $this->nodeInstance = $nodeInstance;
128 * Getter for communicator instance
130 * @return $communicatorInstance An instance of a Communicator class
132 public final function getCommunicatorInstance () {
133 return $this->communicatorInstance;
137 * Setter for communicator instance
139 * @param $communicatorInstance An instance of a Communicator class
142 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
143 $this->communicatorInstance = $communicatorInstance;
147 * Setter for network package handler instance
149 * @param $packageInstance The network package instance we shall set
152 protected final function setPackageInstance (Deliverable $packageInstance) {
153 $this->packageInstance = $packageInstance;
157 * Getter for network package handler instance
159 * @return $packageInstance The network package handler instance we shall set
161 protected final function getPackageInstance () {
162 return $this->packageInstance;
166 * Setter for receiver instance
168 * @param $receiverInstance A Receivable instance we shall set
171 protected final function setReceiverInstance (Receivable $receiverInstance) {
172 $this->receiverInstance = $receiverInstance;
176 * Getter for receiver instance
178 * @return $receiverInstance A Receivable instance we shall get
180 protected final function getReceiverInstance () {
181 return $this->receiverInstance;
185 * Setter for state instance
187 * @param $stateInstance A Stateable instance
190 public final function setStateInstance (Stateable $stateInstance) {
191 $this->stateInstance = $stateInstance;
195 * Getter for state instance
197 * @return $stateInstance A Stateable instance
199 public final function getStateInstance () {
200 return $this->stateInstance;
204 * Setter for listener pool instance
206 * @param $listenerPoolInstance The new listener pool instance
209 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
210 $this->listenerPoolInstance = $listenerPoolInstance;
214 * Getter for listener pool instance
216 * @return $listenerPoolInstance Our current listener pool instance
218 public final function getListenerPoolInstance () {
219 return $this->listenerPoolInstance;
223 * Setter for fragmenter instance
225 * @param $fragmenterInstance A Fragmentable instance
228 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
229 $this->fragmenterInstance = $fragmenterInstance;
233 * Getter for fragmenter instance
235 * @return $fragmenterInstance A Fragmentable instance
237 protected final function getFragmenterInstance () {
238 return $this->fragmenterInstance;
242 * Setter for assembler instance
244 * @param $assemblerInstance An instance of an Assembler class
247 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
248 $this->assemblerInstance = $assemblerInstance;
252 * Getter for assembler instance
254 * @return $assemblerInstance An instance of an Assembler class
256 protected final function getAssemblerInstance () {
257 return $this->assemblerInstance;
261 * Setter for info instance
263 * @param $infoInstance A ShareableInfo instance
266 protected final function setInfoInstance (ShareableInfo $infoInstance) {
267 $this->infoInstance = $infoInstance;
271 * Getter for info instance
273 * @return $infoInstance An instance of a ShareableInfo class
275 public final function getInfoInstance () {
276 return $this->infoInstance;
282 * @param $nodeId The new node id
285 protected final function setNodeId ($nodeId) {
287 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
293 * @return $nodeId Current node id
295 public final function getNodeId () {
296 // Get it from config
297 return $this->getConfigInstance()->getConfigEntry('node_id');
301 * Setter for private key
303 * @param $privateKey The new private key
306 protected final function setPrivateKey ($privateKey) {
308 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
312 * Getter for private key
314 * @return $privateKey Current private key
316 public final function getPrivateKey () {
317 // Get it from config
318 return $this->getConfigInstance()->getConfigEntry('private_key');
322 * Setter for private key hash
324 * @param $privateKeyHash The new private key hash
327 protected final function setPrivateKeyHash ($privateKeyHash) {
329 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
333 * Getter for private key hash
335 * @return $privateKeyHash Current private key hash
337 public final function getPrivateKeyHash () {
338 // Get it from config
339 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
343 * Setter for session id
345 * @param $sessionId The new session id
348 protected final function setSessionId ($sessionId) {
349 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
353 * Getter for session id
355 * @return $sessionId Current session id
357 public final function getSessionId () {
358 return $this->getConfigInstance()->getConfigEntry('session_id');
362 * Getter for protocol name
364 * @return $protocolName Name of used protocol
366 public final function getProtocolName () {
367 return $this->protocolName;
371 * Setter for protocol name
373 * @param $protocolName Name of used protocol
376 protected final function setProtocolName ($protocolName) {
377 $this->protocolName = $protocolName;
381 * Constructs a callable method name from given socket error code. If the
382 * method is not found, a generic one is used.
384 * @param $errorCode Error code from socket_last_error()
385 * @return $handlerName Call-back method name for the error handler
386 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
388 protected function getSocketErrorHandlerFromCode ($errorCode) {
389 // Create a name from translated error code
390 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
392 // Is the call-back method there?
393 if (!method_exists($this, $handlerName)) {
394 // Please implement this
395 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
403 * Handles socket error for given socket resource and peer data. This method
404 * validates $socketResource if it is a valid resource (see is_resource())
405 * but assumes valid data in array $recipientData, except that
406 * count($recipientData) is always 2.
408 * @param $method Value of __METHOD__ from calling method
409 * @param $line Value of __LINE__ from calling method
410 * @param $socketResource A valid socket resource
411 * @param $unlData A valid UNL data array
413 * @throws InvalidSocketException If $socketResource is no socket resource
414 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
416 protected final function handleSocketError ($method, $line, $socketResource, array $unlData) {
417 // This method handles only socket resources
418 if (!is_resource($socketResource)) {
419 // No resource, abort here
420 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
424 //* DEBUG-DIE: */ die(__METHOD__ . ':unlData=' . print_r($unlData, TRUE));
425 assert(isset($unlData[UniversalNodeLocator::UNL_PART_PROTOCOL]));
426 assert(isset($unlData[UniversalNodeLocator::UNL_PART_ADDRESS]));
427 assert(isset($unlData[UniversalNodeLocator::UNL_PART_PORT]));
429 // Get error code for first validation (0 is not an error)
430 $errorCode = socket_last_error($socketResource);
432 // If the error code is zero, someone called this method without an error
433 if ($errorCode == 0) {
434 // No error detected (or previously cleared outside this method)
435 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
438 // Get handler (method) name
439 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
441 // Call-back the error handler method
442 call_user_func_array(array($this, $handlerName), array($socketResource, $unlData));
444 // Finally clear the error because it has been handled
445 socket_clear_error($socketResource);
449 * Translates socket error codes into our own internal names which can be
450 * used for call-backs.
452 * @param $errorCode The error code from socket_last_error() to be translated
453 * @return $errorName The translated name (all lower-case, with underlines)
455 public function translateSocketErrorCodeToName ($errorCode) {
456 // Nothing bad happened by default
457 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
459 // Is the code a number, then we have to change it
460 switch ($errorCode) {
461 case 0: // Silently ignored, the socket is connected
464 case 11: // "Resource temporary unavailable"
465 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
468 case 32: // "Broken pipe"
469 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
472 case 104: // "Connection reset by peer"
473 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
476 case 107: // "Transport end-point not connected"
477 case 134: // On some (?) systems for 'transport end-point not connected'
478 // @TODO On some systems it is 134, on some 107?
479 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
482 case 110: // "Connection timed out"
483 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
486 case 111: // "Connection refused"
487 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
490 case 113: // "No route to host"
491 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
494 case 114: // "Operation already in progress"
495 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
498 case 115: // "Operation now in progress"
499 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
502 default: // Everything else <> 0
503 // Unhandled error code detected, so first debug it because we may want to handle it like the others
504 self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
506 // Change it only in this class
507 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
511 // Return translated name
516 * Shuts down a given socket resource. This method does only ease calling
519 * @param $socketResource A valid socket resource
522 public function shutdownSocket ($socketResource) {
524 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
526 // Set socket resource
527 $this->setSocketResource($socketResource);
529 // Get a visitor instance
530 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
533 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
536 $this->accept($visitorInstance);
540 * Half-shuts down a given socket resource. This method does only ease calling
541 * an other visitor than shutdownSocket() does.
543 * @param $socketResource A valid socket resource
546 public function halfShutdownSocket ($socketResource) {
548 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
550 // Set socket resource
551 $this->setSocketResource($socketResource);
553 // Get a visitor instance
554 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
557 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
560 $this->accept($visitorInstance);
564 * "Getter" for a printable state name
566 * @return $stateName Name of the node's state in a printable format
568 public final function getPrintableState () {
572 // Get the state instance
573 $stateInstance = $this->getStateInstance();
575 // Is it an instance of Stateable?
576 if ($stateInstance instanceof Stateable) {
577 // Then use that state name
578 $stateName = $stateInstance->getStateName();