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 SOCKET_ERROR_CONNECTION_RESET_BY_PEER = 0x909;
37 // Message status codes
38 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
41 * Separator for all bootstrap node entries
43 const BOOTSTRAP_NODES_SEPARATOR = ';';
46 * An instance of a node
48 private $nodeInstance = NULL;
51 * An instance of a cruncher
53 private $cruncherInstance = NULL;
58 private $listenerInstance = NULL;
61 * A network package handler instance
63 private $packageInstance = NULL;
66 * A Receivable instance
68 private $receiverInstance = NULL;
73 private $stateInstance = NULL;
76 * Listener pool instance
78 private $listenerPoolInstance = NULL;
83 private $fragmenterInstance = NULL;
88 private $decoderInstance = NULL;
93 private $assemblerInstance = NULL;
96 * Protected constructor
98 * @param $className Name of the class
101 protected function __construct ($className) {
102 // Call parent constructor
103 parent::__construct($className);
107 * Getter for node instance
109 * @return $nodeInstance An instance of a node node
111 public final function getNodeInstance () {
112 return $this->nodeInstance;
116 * Setter for node instance
118 * @param $nodeInstance An instance of a node node
121 protected final function setNodeInstance (NodeHelper $nodeInstance) {
122 $this->nodeInstance = $nodeInstance;
126 * Getter for cruncher instance
128 * @return $cruncherInstance An instance of a cruncher cruncher
130 public final function getCruncherInstance () {
131 return $this->cruncherInstance;
135 * Setter for cruncher instance
137 * @param $cruncherInstance An instance of a cruncher cruncher
140 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
141 $this->cruncherInstance = $cruncherInstance;
145 * Setter for listener instance
147 * @param $listenerInstance A Listenable instance
150 protected final function setListenerInstance (Listenable $listenerInstance) {
151 $this->listenerInstance = $listenerInstance;
155 * Getter for listener instance
157 * @return $listenerInstance A Listenable instance
159 protected final function getListenerInstance () {
160 return $this->listenerInstance;
164 * Setter for network package handler instance
166 * @param $packageInstance The network package instance we shall set
169 protected final function setPackageInstance (Deliverable $packageInstance) {
170 $this->packageInstance = $packageInstance;
174 * Getter for network package handler instance
176 * @return $packageInstance The network package handler instance we shall set
178 protected final function getPackageInstance () {
179 return $this->packageInstance;
183 * Setter for receiver instance
185 * @param $receiverInstance A Receivable instance we shall set
188 protected final function setReceiverInstance (Receivable $receiverInstance) {
189 $this->receiverInstance = $receiverInstance;
193 * Getter for receiver instance
195 * @return $receiverInstance A Receivable instance we shall get
197 protected final function getReceiverInstance () {
198 return $this->receiverInstance;
202 * Setter for state instance
204 * @param $stateInstance A Stateable instance
207 public final function setStateInstance (Stateable $stateInstance) {
208 $this->stateInstance = $stateInstance;
212 * Getter for state instance
214 * @return $stateInstance A Stateable instance
216 public final function getStateInstance () {
217 return $this->stateInstance;
221 * Setter for listener pool instance
223 * @param $listenerPoolInstance The new listener pool instance
226 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
227 $this->listenerPoolInstance = $listenerPoolInstance;
231 * Getter for listener pool instance
233 * @return $listenerPoolInstance Our current listener pool instance
235 public final function getListenerPoolInstance () {
236 return $this->listenerPoolInstance;
240 * Setter for fragmenter instance
242 * @param $fragmenterInstance A Fragmentable instance
245 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
246 $this->fragmenterInstance = $fragmenterInstance;
250 * Getter for fragmenter instance
252 * @return $fragmenterInstance A Fragmentable instance
254 protected final function getFragmenterInstance () {
255 return $this->fragmenterInstance;
259 * Setter for decoder instance
261 * @param $decoderInstance A Decodeable instance
264 protected final function setDecoderInstance (Decodeable $decoderInstance) {
265 $this->decoderInstance = $decoderInstance;
269 * Getter for decoder instance
271 * @return $decoderInstance A Decodeable instance
273 protected final function getDecoderInstance () {
274 return $this->decoderInstance;
278 * Setter for assembler instance
280 * @param $assemblerInstance A Decodeable instance
283 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
284 $this->assemblerInstance = $assemblerInstance;
288 * Getter for assembler instance
290 * @return $assemblerInstance A Decodeable instance
292 protected final function getAssemblerInstance () {
293 return $this->assemblerInstance;
299 * @param $nodeId The new node id
302 protected final function setNodeId ($nodeId) {
304 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
310 * @return $nodeId Current node id
312 public final function getNodeId () {
313 // Get it from config
314 return $this->getConfigInstance()->getConfigEntry('node_id');
318 * Setter for private key
320 * @param $privateKey The new private key
323 protected final function setPrivateKey ($privateKey) {
325 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
329 * Getter for private key
331 * @return $privateKey Current private key
333 public final function getPrivateKey () {
334 // Get it from config
335 return $this->getConfigInstance()->getConfigEntry('private_key');
339 * Setter for private key hash
341 * @param $privateKeyHash The new private key hash
344 protected final function setPrivateKeyHash ($privateKeyHash) {
346 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
350 * Getter for private key hash
352 * @return $privateKeyHash Current private key hash
354 public final function getPrivateKeyHash () {
355 // Get it from config
356 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
360 * Setter for session id
362 * @param $sessionId The new session id
365 protected final function setSessionId ($sessionId) {
366 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
370 * Getter for session id
372 * @return $sessionId Current session id
374 public final function getSessionId () {
375 return $this->getConfigInstance()->getConfigEntry('session_id');
379 * Constructs a callable method name from given socket error code. If the
380 * method is not found, a generic one is used.
382 * @param $errorCode Error code from socket_last_error()
383 * @return $handlerName Call-back method name for the error handler
384 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
386 protected function getSocketErrorHandlerFromCode ($errorCode) {
387 // Create a name from translated error code
388 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
390 // Is the call-back method there?
391 if (!method_exists($this, $handlerName)) {
392 // Please implement this
393 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
401 * Handles socket error for given socket resource and peer data. This method
402 * validates $socketResource if it is a valid resource (see is_resource())
403 * but assumes valid data in array $recipientData, except that
404 * count($recipientData) is always 2.
406 * @param $method Value of __METHOD__ from calling method
407 * @param $line Value of __LINE__ from calling method
408 * @param $socketResource A valid socket resource
409 * @param $recipientData An array with two elements: 0=IP number, 1=port number
411 * @throws InvalidSocketException If $socketResource is no socket resource
412 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
414 protected final function handleSocketError ($method, $line, $socketResource, array $recipientData) {
415 // This method handles only socket resources
416 if (!is_resource($socketResource)) {
417 // No resource, abort here
418 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
421 // Check count of array, should be two
422 assert(count($recipientData) == 2);
424 // Get error code for first validation (0 is not an error)
425 $errorCode = socket_last_error($socketResource);
427 // If the error code is zero, someone called this method without an error
428 if ($errorCode == 0) {
429 // No error detected (or previously cleared outside this method)
430 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
433 // Get handler (method) name
434 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
436 // Call-back the error handler method
437 call_user_func_array(array($this, $handlerName), array($socketResource, $recipientData));
439 // Finally clear the error because it has been handled
440 socket_clear_error($socketResource);
444 * Checks whether the final (last) chunk is valid
446 * @param $chunks An array with chunks and (hopefully) a valid final chunk
447 * @return $isValid Whether the final (last) chunk is valid
449 protected function isValidFinalChunk (array $chunks) {
450 // Default is all fine
453 // Split the (possible) EOP chunk
454 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
456 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
457 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits, TRUE));
458 assert(count($chunkSplits) == 3);
460 // Validate final chunk
461 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
464 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
465 // CHUNK_HASH_SEPARATOR shall only be found once
474 * Translates socket error codes into our own internal names which can be
475 * used for call-backs.
477 * @param $errorCode The error code from socket_last_error() to be translated
478 * @return $errorName The translated name (all lower-case, with underlines)
480 public function translateSocketErrorCodeToName ($errorCode) {
481 // Nothing bad happened by default
482 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
484 // Is the code a number, then we have to change it
485 switch ($errorCode) {
486 case 0: // Silently ignored, the socket is connected
489 case 11: // "Resource temporary unavailable"
490 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
493 case 104: // "Connection reset by peer"
494 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
497 case 107: // "Transport end-point not connected"
498 case 134: // On some (?) systems for 'transport end-point not connected'
499 // @TODO On some systems it is 134, on some 107?
500 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
503 case 110: // "Connection timed out"
504 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
507 case 111: // "Connection refused"
508 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
511 case 113: // "No route to host"
512 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
515 case 114: // "Operation already in progress"
516 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
519 case 115: // "Operation now in progress"
520 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
523 default: // Everything else <> 0
524 // Unhandled error code detected, so first debug it because we may want to handle it like the others
525 self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
527 // Change it only in this class
528 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
532 // Return translated name
537 * Shuts down a given socket resource. This method does only ease calling
540 * @param $socketResource A valid socket resource
543 public function shutdownSocket ($socketResource) {
545 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
547 // Set socket resource
548 $this->setSocketResource($socketResource);
550 // Get a visitor instance
551 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
554 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
557 $this->accept($visitorInstance);
561 * Half-shuts down a given socket resource. This method does only ease calling
562 * an other visitor than shutdownSocket() does.
564 * @param $socketResource A valid socket resource
567 public function halfShutdownSocket ($socketResource) {
569 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
571 // Set socket resource
572 $this->setSocketResource($socketResource);
574 // Get a visitor instance
575 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
578 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
581 $this->accept($visitorInstance);
585 * "Getter" for a printable state name
587 * @return $stateName Name of the node's state in a printable format
589 public final function getPrintableState () {
593 // Get the state instance
594 $stateInstance = $this->getStateInstance();
596 // Is it an instance of Stateable?
597 if ($stateInstance instanceof Stateable) {
598 // Then use that state name
599 $stateName = $stateInstance->getStateName();