3 * A general hub system class
5 * @author Roland Haeder <webmaster@ship-simu.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.ship-simu.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;
34 // Message status codes
35 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
38 * Separator for all bootstrap node entries
40 const BOOTSTRAP_NODES_SEPARATOR = ';';
43 * An instance of a node
45 private $nodeInstance = NULL;
48 * An instance of a cruncher
50 private $cruncherInstance = NULL;
55 private $listenerInstance = 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 $decoderInstance = NULL;
90 private $assemblerInstance = NULL;
93 * Protected constructor
95 * @param $className Name of the class
98 protected function __construct ($className) {
99 // Call parent constructor
100 parent::__construct($className);
104 * Getter for node instance
106 * @return $nodeInstance An instance of a node node
108 public final function getNodeInstance () {
109 return $this->nodeInstance;
113 * Setter for node instance
115 * @param $nodeInstance An instance of a node node
118 protected final function setNodeInstance (NodeHelper $nodeInstance) {
119 $this->nodeInstance = $nodeInstance;
123 * Getter for cruncher instance
125 * @return $cruncherInstance An instance of a cruncher cruncher
127 public final function getCruncherInstance () {
128 return $this->cruncherInstance;
132 * Setter for cruncher instance
134 * @param $cruncherInstance An instance of a cruncher cruncher
137 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
138 $this->cruncherInstance = $cruncherInstance;
142 * Setter for listener instance
144 * @param $listenerInstance A Listenable instance
147 protected final function setListenerInstance (Listenable $listenerInstance) {
148 $this->listenerInstance = $listenerInstance;
152 * Getter for listener instance
154 * @return $listenerInstance A Listenable instance
156 protected final function getListenerInstance () {
157 return $this->listenerInstance;
161 * Setter for network package handler instance
163 * @param $packageInstance The network package instance we shall set
166 protected final function setPackageInstance (Deliverable $packageInstance) {
167 $this->packageInstance = $packageInstance;
171 * Getter for network package handler instance
173 * @return $packageInstance The network package handler instance we shall set
175 protected final function getPackageInstance () {
176 return $this->packageInstance;
180 * Setter for receiver instance
182 * @param $receiverInstance A Receivable instance we shall set
185 protected final function setReceiverInstance (Receivable $receiverInstance) {
186 $this->receiverInstance = $receiverInstance;
190 * Getter for receiver instance
192 * @return $receiverInstance A Receivable instance we shall get
194 protected final function getReceiverInstance () {
195 return $this->receiverInstance;
199 * Setter for state instance
201 * @param $stateInstance A Stateable instance
204 public final function setStateInstance (Stateable $stateInstance) {
205 $this->stateInstance = $stateInstance;
209 * Getter for state instance
211 * @return $stateInstance A Stateable instance
213 public final function getStateInstance () {
214 return $this->stateInstance;
218 * Setter for listener pool instance
220 * @param $listenerPoolInstance The new listener pool instance
223 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
224 $this->listenerPoolInstance = $listenerPoolInstance;
228 * Getter for listener pool instance
230 * @return $listenerPoolInstance Our current listener pool instance
232 public final function getListenerPoolInstance () {
233 return $this->listenerPoolInstance;
237 * Setter for fragmenter instance
239 * @param $fragmenterInstance A Fragmentable instance
242 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
243 $this->fragmenterInstance = $fragmenterInstance;
247 * Getter for fragmenter instance
249 * @return $fragmenterInstance A Fragmentable instance
251 protected final function getFragmenterInstance () {
252 return $this->fragmenterInstance;
256 * Setter for decoder instance
258 * @param $decoderInstance A Decodeable instance
261 protected final function setDecoderInstance (Decodeable $decoderInstance) {
262 $this->decoderInstance = $decoderInstance;
266 * Getter for decoder instance
268 * @return $decoderInstance A Decodeable instance
270 protected final function getDecoderInstance () {
271 return $this->decoderInstance;
275 * Setter for assembler instance
277 * @param $assemblerInstance A Decodeable instance
280 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
281 $this->assemblerInstance = $assemblerInstance;
285 * Getter for assembler instance
287 * @return $assemblerInstance A Decodeable instance
289 protected final function getAssemblerInstance () {
290 return $this->assemblerInstance;
296 * @param $nodeId The new node id
299 protected final function setNodeId ($nodeId) {
301 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
307 * @return $nodeId Current node id
309 public final function getNodeId () {
310 // Get it from config
311 return $this->getConfigInstance()->getConfigEntry('node_id');
315 * Setter for private key
317 * @param $privateKey The new private key
320 protected final function setPrivateKey ($privateKey) {
322 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
326 * Getter for private key
328 * @return $privateKey Current private key
330 public final function getPrivateKey () {
331 // Get it from config
332 return $this->getConfigInstance()->getConfigEntry('private_key');
336 * Setter for private key hash
338 * @param $privateKeyHash The new private key hash
341 protected final function setPrivateKeyHash ($privateKeyHash) {
343 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
347 * Getter for private key hash
349 * @return $privateKeyHash Current private key hash
351 public final function getPrivateKeyHash () {
352 // Get it from config
353 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
357 * Setter for session id
359 * @param $sessionId The new session id
362 protected final function setSessionId ($sessionId) {
363 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
367 * Getter for session id
369 * @return $sessionId Current session id
371 public final function getSessionId () {
372 return $this->getConfigInstance()->getConfigEntry('session_id');
376 * Constructs a callable method name from given socket error code. If the
377 * method is not found, a generic one is used.
379 * @param $errorCode Error code from socket_last_error()
380 * @return $handlerName Call-back method name for the error handler
381 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
383 protected function getSocketErrorHandlerFromCode ($errorCode) {
384 // Create a name from translated error code
385 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
387 // Is the call-back method there?
388 if (!method_exists($this, $handlerName)) {
389 // Please implement this
390 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
398 * Handles socket error for given socket resource and peer data. This method
399 * validates $socketResource if it is a valid resource (see is_resource())
400 * but assumes valid data in array $recipientData, except that
401 * count($recipientData) is always 2.
403 * @param $method Value of __METHOD__ from calling method
404 * @param $line Value of __LINE__ from calling method
405 * @param $socketResource A valid socket resource
406 * @param $recipientData An array with two elements: 0=IP number, 1=port number
408 * @throws InvalidSocketException If $socketResource is no socket resource
409 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
411 protected final function handleSocketError ($method, $line, $socketResource, array $recipientData) {
412 // This method handles only socket resources
413 if (!is_resource($socketResource)) {
414 // No resource, abort here
415 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
418 // Check count of array, should be two
419 assert(count($recipientData) == 2);
421 // Get error code for first validation (0 is not an error)
422 $errorCode = socket_last_error($socketResource);
424 // If the error code is zero, someone called this method without an error
425 if ($errorCode == 0) {
426 // No error detected (or previously cleared outside this method)
427 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
430 // Get handler (method) name
431 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
433 // Call-back the error handler method
434 call_user_func_array(array($this, $handlerName), array($socketResource, $recipientData));
436 // Finally clear the error because it has been handled
437 socket_clear_error($socketResource);
441 * Checks whether the final (last) chunk is valid
443 * @param $chunks An array with chunks and (hopefully) a valid final chunk
444 * @return $isValid Whether the final (last) chunk is valid
446 protected function isValidFinalChunk (array $chunks) {
447 // Default is all fine
450 // Split the (possible) EOP chunk
451 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
453 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
454 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits, true));
455 assert(count($chunkSplits) == 3);
457 // Validate final chunk
458 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
461 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
462 // CHUNK_HASH_SEPARATOR shall only be found once
471 * Translates socket error codes into our own internal names which can be
472 * used for call-backs.
474 * @param $errorCode The error code from socket_last_error() to be translated
475 * @return $errorName The translated name (all lower-case, with underlines)
477 public function translateSocketErrorCodeToName ($errorCode) {
478 // Nothing bad happened by default
479 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
481 // Is the code a number, then we have to change it
482 switch ($errorCode) {
483 case 0: // Silently ignored, the socket is connected
486 case 11: // "Resource temporary unavailable"
487 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
490 case 107: // "Transport end-point not connected"
491 case 134: // On some (?) systems for 'transport end-point not connected'
492 // @TODO On some systems it is 134, on some 107?
493 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
496 case 110: // "Connection timed out"
497 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
500 case 111: // "Connection refused"
501 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
504 case 113: // "No route to host"
505 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
508 case 114: // "Operation already in progress"
509 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
512 case 115: // "Operation now in progress"
513 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
516 default: // Everything else <> 0
517 // Unhandled error code detected, so first debug it because we may want to handle it like the others
518 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
520 // Change it only in this class
521 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
525 // Return translated name
530 * Shuts down a given socket resource. This method does only ease calling
533 * @param $socketResource A valid socket resource
536 public function shutdownSocket ($socketResource) {
538 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
540 // Set socket resource
541 $this->setSocketResource($socketResource);
543 // Get a visitor instance
544 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
547 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
550 $this->accept($visitorInstance);
554 * Half-shuts down a given socket resource. This method does only ease calling
555 * an other visitor than shutdownSocket() does.
557 * @param $socketResource A valid socket resource
560 public function halfShutdownSocket ($socketResource) {
562 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
564 // Set socket resource
565 $this->setSocketResource($socketResource);
567 // Get a visitor instance
568 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
571 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
574 $this->accept($visitorInstance);
578 * "Getter" for a printable state name
580 * @return $stateName Name of the node's state in a printable format
582 public final function getPrintableState () {
586 // Get the state instance
587 $stateInstance = $this->getStateInstance();
589 // Is it an instance of Stateable?
590 if ($stateInstance instanceof Stateable) {
591 // Then use that state name
592 $stateName = $stateInstance->getStateName();