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 * A network package handler instance
55 private $packageInstance = NULL;
58 * A Receivable instance
60 private $receiverInstance = NULL;
63 * Listener pool instance
65 private $listenerPoolInstance = NULL;
70 private $fragmenterInstance = NULL;
75 private $assemblerInstance = NULL;
80 private $infoInstance = NULL;
83 * Protected constructor
85 * @param $className Name of the class
88 protected function __construct ($className) {
89 // Call parent constructor
90 parent::__construct($className);
94 * Setter for network package handler instance
96 * @param $packageInstance The network package instance we shall set
99 protected final function setPackageInstance (Deliverable $packageInstance) {
100 $this->packageInstance = $packageInstance;
104 * Getter for network package handler instance
106 * @return $packageInstance The network package handler instance we shall set
108 protected final function getPackageInstance () {
109 return $this->packageInstance;
113 * Setter for receiver instance
115 * @param $receiverInstance A Receivable instance we shall set
118 protected final function setReceiverInstance (Receivable $receiverInstance) {
119 $this->receiverInstance = $receiverInstance;
123 * Getter for receiver instance
125 * @return $receiverInstance A Receivable instance we shall get
127 protected final function getReceiverInstance () {
128 return $this->receiverInstance;
132 * Setter for listener pool instance
134 * @param $listenerPoolInstance The new listener pool instance
137 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
138 $this->listenerPoolInstance = $listenerPoolInstance;
142 * Getter for listener pool instance
144 * @return $listenerPoolInstance Our current listener pool instance
146 public final function getListenerPoolInstance () {
147 return $this->listenerPoolInstance;
151 * Setter for fragmenter instance
153 * @param $fragmenterInstance A Fragmentable instance
156 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
157 $this->fragmenterInstance = $fragmenterInstance;
161 * Getter for fragmenter instance
163 * @return $fragmenterInstance A Fragmentable instance
165 protected final function getFragmenterInstance () {
166 return $this->fragmenterInstance;
170 * Setter for assembler instance
172 * @param $assemblerInstance An instance of an Assembler class
175 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
176 $this->assemblerInstance = $assemblerInstance;
180 * Getter for assembler instance
182 * @return $assemblerInstance An instance of an Assembler class
184 protected final function getAssemblerInstance () {
185 return $this->assemblerInstance;
189 * Setter for info instance
191 * @param $infoInstance A ShareableInfo instance
194 protected final function setInfoInstance (ShareableInfo $infoInstance) {
195 $this->infoInstance = $infoInstance;
199 * Getter for info instance
201 * @return $infoInstance An instance of a ShareableInfo class
203 public final function getInfoInstance () {
204 return $this->infoInstance;
210 * @param $nodeId The new node id
213 protected final function setNodeId ($nodeId) {
215 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
221 * @return $nodeId Current node id
223 public final function getNodeId () {
224 // Get it from config
225 return $this->getConfigInstance()->getConfigEntry('node_id');
229 * Setter for private key
231 * @param $privateKey The new private key
234 protected final function setPrivateKey ($privateKey) {
236 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
240 * Getter for private key
242 * @return $privateKey Current private key
244 public final function getPrivateKey () {
245 // Get it from config
246 return $this->getConfigInstance()->getConfigEntry('private_key');
250 * Setter for private key hash
252 * @param $privateKeyHash The new private key hash
255 protected final function setPrivateKeyHash ($privateKeyHash) {
257 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
261 * Getter for private key hash
263 * @return $privateKeyHash Current private key hash
265 public final function getPrivateKeyHash () {
266 // Get it from config
267 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
271 * Setter for session id
273 * @param $sessionId The new session id
276 protected final function setSessionId ($sessionId) {
277 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
281 * Getter for session id
283 * @return $sessionId Current session id
285 public final function getSessionId () {
286 return $this->getConfigInstance()->getConfigEntry('session_id');
290 * Constructs a callable method name from given socket error code. If the
291 * method is not found, a generic one is used.
293 * @param $errorCode Error code from socket_last_error()
294 * @return $handlerName Call-back method name for the error handler
295 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
297 protected function getSocketErrorHandlerFromCode ($errorCode) {
298 // Create a name from translated error code
299 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
301 // Is the call-back method there?
302 if (!method_exists($this, $handlerName)) {
303 // Please implement this
304 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
312 * Handles socket error for given socket resource and peer data. This method
313 * validates $socketResource if it is a valid resource (see is_resource())
314 * but assumes valid data in array $recipientData, except that
315 * count($recipientData) is always 2.
317 * @param $method Value of __METHOD__ from calling method
318 * @param $line Value of __LINE__ from calling method
319 * @param $socketResource A valid socket resource
320 * @param $unlData A valid UNL data array
322 * @throws InvalidSocketException If $socketResource is no socket resource
323 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
325 protected final function handleSocketError ($method, $line, $socketResource, array $unlData) {
326 // This method handles only socket resources
327 if (!is_resource($socketResource)) {
328 // No resource, abort here
329 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
333 //* DEBUG-DIE: */ die(__METHOD__ . ':unlData=' . print_r($unlData, TRUE));
334 assert(isset($unlData[UniversalNodeLocator::UNL_PART_PROTOCOL]));
335 assert(isset($unlData[UniversalNodeLocator::UNL_PART_ADDRESS]));
336 assert(isset($unlData[UniversalNodeLocator::UNL_PART_PORT]));
338 // Get error code for first validation (0 is not an error)
339 $errorCode = socket_last_error($socketResource);
341 // If the error code is zero, someone called this method without an error
342 if ($errorCode == 0) {
343 // No error detected (or previously cleared outside this method)
344 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
347 // Get handler (method) name
348 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
350 // Call-back the error handler method
351 call_user_func_array(array($this, $handlerName), array($socketResource, $unlData));
353 // Finally clear the error because it has been handled
354 socket_clear_error($socketResource);
358 * Translates socket error codes into our own internal names which can be
359 * used for call-backs.
361 * @param $errorCode The error code from socket_last_error() to be translated
362 * @return $errorName The translated name (all lower-case, with underlines)
364 public function translateSocketErrorCodeToName ($errorCode) {
365 // Nothing bad happened by default
366 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
368 // Is the code a number, then we have to change it
369 switch ($errorCode) {
370 case 0: // Silently ignored, the socket is connected
373 case 11: // "Resource temporary unavailable"
374 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
377 case 32: // "Broken pipe"
378 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
381 case 104: // "Connection reset by peer"
382 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
385 case 107: // "Transport end-point not connected"
386 case 134: // On some (?) systems for 'transport end-point not connected'
387 // @TODO On some systems it is 134, on some 107?
388 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
391 case 110: // "Connection timed out"
392 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
395 case 111: // "Connection refused"
396 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
399 case 113: // "No route to host"
400 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
403 case 114: // "Operation already in progress"
404 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
407 case 115: // "Operation now in progress"
408 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
411 default: // Everything else <> 0
412 // Unhandled error code detected, so first debug it because we may want to handle it like the others
413 self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
415 // Change it only in this class
416 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
420 // Return translated name
425 * Shuts down a given socket resource. This method does only ease calling
428 * @param $socketResource A valid socket resource
431 public function shutdownSocket ($socketResource) {
433 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
435 // Set socket resource
436 $this->setSocketResource($socketResource);
438 // Get a visitor instance
439 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
442 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
445 $this->accept($visitorInstance);
449 * Half-shuts down a given socket resource. This method does only ease calling
450 * an other visitor than shutdownSocket() does.
452 * @param $socketResource A valid socket resource
455 public function halfShutdownSocket ($socketResource) {
457 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
459 // Set socket resource
460 $this->setSocketResource($socketResource);
462 // Get a visitor instance
463 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
466 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
469 $this->accept($visitorInstance);
473 * "Getter" for a printable state name
475 * @return $stateName Name of the node's state in a printable format
477 public final function getPrintableState () {
481 // Get the state instance
482 $stateInstance = $this->getStateInstance();
484 // Is it an instance of Stateable?
485 if ($stateInstance instanceof Stateable) {
486 // Then use that state name
487 $stateName = $stateInstance->getStateName();