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;
33 const EXCEPTION_REQUEST_NOT_ACCEPTED = 0x907;
35 // Message status codes
36 const MESSAGE_STATUS_CODE_OKAY = 'OKAY';
39 * Separator for all bootstrap node entries
41 const BOOTSTRAP_NODES_SEPARATOR = ';';
44 * An instance of a node
46 private $nodeInstance = NULL;
49 * An instance of a cruncher
51 private $cruncherInstance = NULL;
56 private $listenerInstance = NULL;
59 * A network package handler instance
61 private $packageInstance = NULL;
64 * A Receivable instance
66 private $receiverInstance = NULL;
71 private $stateInstance = NULL;
74 * Listener pool instance
76 private $listenerPoolInstance = NULL;
81 private $fragmenterInstance = NULL;
86 private $decoderInstance = NULL;
91 private $assemblerInstance = NULL;
94 * Protected constructor
96 * @param $className Name of the class
99 protected function __construct ($className) {
100 // Call parent constructor
101 parent::__construct($className);
105 * Getter for node instance
107 * @return $nodeInstance An instance of a node node
109 public final function getNodeInstance () {
110 return $this->nodeInstance;
114 * Setter for node instance
116 * @param $nodeInstance An instance of a node node
119 protected final function setNodeInstance (NodeHelper $nodeInstance) {
120 $this->nodeInstance = $nodeInstance;
124 * Getter for cruncher instance
126 * @return $cruncherInstance An instance of a cruncher cruncher
128 public final function getCruncherInstance () {
129 return $this->cruncherInstance;
133 * Setter for cruncher instance
135 * @param $cruncherInstance An instance of a cruncher cruncher
138 protected final function setCruncherInstance (CruncherHelper $cruncherInstance) {
139 $this->cruncherInstance = $cruncherInstance;
143 * Setter for listener instance
145 * @param $listenerInstance A Listenable instance
148 protected final function setListenerInstance (Listenable $listenerInstance) {
149 $this->listenerInstance = $listenerInstance;
153 * Getter for listener instance
155 * @return $listenerInstance A Listenable instance
157 protected final function getListenerInstance () {
158 return $this->listenerInstance;
162 * Setter for network package handler instance
164 * @param $packageInstance The network package instance we shall set
167 protected final function setPackageInstance (Deliverable $packageInstance) {
168 $this->packageInstance = $packageInstance;
172 * Getter for network package handler instance
174 * @return $packageInstance The network package handler instance we shall set
176 protected final function getPackageInstance () {
177 return $this->packageInstance;
181 * Setter for receiver instance
183 * @param $receiverInstance A Receivable instance we shall set
186 protected final function setReceiverInstance (Receivable $receiverInstance) {
187 $this->receiverInstance = $receiverInstance;
191 * Getter for receiver instance
193 * @return $receiverInstance A Receivable instance we shall get
195 protected final function getReceiverInstance () {
196 return $this->receiverInstance;
200 * Setter for state instance
202 * @param $stateInstance A Stateable instance
205 public final function setStateInstance (Stateable $stateInstance) {
206 $this->stateInstance = $stateInstance;
210 * Getter for state instance
212 * @return $stateInstance A Stateable instance
214 public final function getStateInstance () {
215 return $this->stateInstance;
219 * Setter for listener pool instance
221 * @param $listenerPoolInstance The new listener pool instance
224 protected final function setListenerPoolInstance (PoolableListener $listenerPoolInstance) {
225 $this->listenerPoolInstance = $listenerPoolInstance;
229 * Getter for listener pool instance
231 * @return $listenerPoolInstance Our current listener pool instance
233 public final function getListenerPoolInstance () {
234 return $this->listenerPoolInstance;
238 * Setter for fragmenter instance
240 * @param $fragmenterInstance A Fragmentable instance
243 protected final function setFragmenterInstance (Fragmentable $fragmenterInstance) {
244 $this->fragmenterInstance = $fragmenterInstance;
248 * Getter for fragmenter instance
250 * @return $fragmenterInstance A Fragmentable instance
252 protected final function getFragmenterInstance () {
253 return $this->fragmenterInstance;
257 * Setter for decoder instance
259 * @param $decoderInstance A Decodeable instance
262 protected final function setDecoderInstance (Decodeable $decoderInstance) {
263 $this->decoderInstance = $decoderInstance;
267 * Getter for decoder instance
269 * @return $decoderInstance A Decodeable instance
271 protected final function getDecoderInstance () {
272 return $this->decoderInstance;
276 * Setter for assembler instance
278 * @param $assemblerInstance A Decodeable instance
281 protected final function setAssemblerInstance (Assembler $assemblerInstance) {
282 $this->assemblerInstance = $assemblerInstance;
286 * Getter for assembler instance
288 * @return $assemblerInstance A Decodeable instance
290 protected final function getAssemblerInstance () {
291 return $this->assemblerInstance;
297 * @param $nodeId The new node id
300 protected final function setNodeId ($nodeId) {
302 $this->getConfigInstance()->setConfigEntry('node_id', (string) $nodeId);
308 * @return $nodeId Current node id
310 public final function getNodeId () {
311 // Get it from config
312 return $this->getConfigInstance()->getConfigEntry('node_id');
316 * Setter for private key
318 * @param $privateKey The new private key
321 protected final function setPrivateKey ($privateKey) {
323 $this->getConfigInstance()->setConfigEntry('private_key', (string) $privateKey);
327 * Getter for private key
329 * @return $privateKey Current private key
331 public final function getPrivateKey () {
332 // Get it from config
333 return $this->getConfigInstance()->getConfigEntry('private_key');
337 * Setter for private key hash
339 * @param $privateKeyHash The new private key hash
342 protected final function setPrivateKeyHash ($privateKeyHash) {
344 $this->getConfigInstance()->setConfigEntry('private_key_hash', (string) $privateKeyHash);
348 * Getter for private key hash
350 * @return $privateKeyHash Current private key hash
352 public final function getPrivateKeyHash () {
353 // Get it from config
354 return $this->getConfigInstance()->getConfigEntry('private_key_hash');
358 * Setter for session id
360 * @param $sessionId The new session id
363 protected final function setSessionId ($sessionId) {
364 $this->getConfigInstance()->setConfigEntry('session_id', (string) $sessionId);
368 * Getter for session id
370 * @return $sessionId Current session id
372 public final function getSessionId () {
373 return $this->getConfigInstance()->getConfigEntry('session_id');
377 * Constructs a callable method name from given socket error code. If the
378 * method is not found, a generic one is used.
380 * @param $errorCode Error code from socket_last_error()
381 * @return $handlerName Call-back method name for the error handler
382 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
384 protected function getSocketErrorHandlerFromCode ($errorCode) {
385 // Create a name from translated error code
386 $handlerName = 'socketError' . $this->convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
388 // Is the call-back method there?
389 if (!method_exists($this, $handlerName)) {
390 // Please implement this
391 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), self::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
399 * Handles socket error for given socket resource and peer data. This method
400 * validates $socketResource if it is a valid resource (see is_resource())
401 * but assumes valid data in array $recipientData, except that
402 * count($recipientData) is always 2.
404 * @param $method Value of __METHOD__ from calling method
405 * @param $line Value of __LINE__ from calling method
406 * @param $socketResource A valid socket resource
407 * @param $recipientData An array with two elements: 0=IP number, 1=port number
409 * @throws InvalidSocketException If $socketResource is no socket resource
410 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
412 protected final function handleSocketError ($method, $line, $socketResource, array $recipientData) {
413 // This method handles only socket resources
414 if (!is_resource($socketResource)) {
415 // No resource, abort here
416 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
419 // Check count of array, should be two
420 assert(count($recipientData) == 2);
422 // Get error code for first validation (0 is not an error)
423 $errorCode = socket_last_error($socketResource);
425 // If the error code is zero, someone called this method without an error
426 if ($errorCode == 0) {
427 // No error detected (or previously cleared outside this method)
428 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
431 // Get handler (method) name
432 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
434 // Call-back the error handler method
435 call_user_func_array(array($this, $handlerName), array($socketResource, $recipientData));
437 // Finally clear the error because it has been handled
438 socket_clear_error($socketResource);
442 * Checks whether the final (last) chunk is valid
444 * @param $chunks An array with chunks and (hopefully) a valid final chunk
445 * @return $isValid Whether the final (last) chunk is valid
447 protected function isValidFinalChunk (array $chunks) {
448 // Default is all fine
451 // Split the (possible) EOP chunk
452 $chunkSplits = explode(PackageFragmenter::CHUNK_DATA_HASH_SEPARATOR, $chunks[count($chunks) - 1]);
454 // Make sure chunks with only 3 elements are parsed (for details see ChunkHandler)
455 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('eopChunk=' . $chunks[count($chunks) - 1] . ',chunkSplits=' . print_r($chunkSplits, true));
456 assert(count($chunkSplits) == 3);
458 // Validate final chunk
459 if (substr($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], 0, strlen(PackageFragmenter::END_OF_PACKAGE_IDENTIFIER)) != PackageFragmenter::END_OF_PACKAGE_IDENTIFIER) {
462 } elseif (substr_count($chunkSplits[ChunkHandler::CHUNK_SPLITS_INDEX_RAW_DATA], PackageFragmenter::CHUNK_HASH_SEPARATOR) != 1) {
463 // CHUNK_HASH_SEPARATOR shall only be found once
472 * Translates socket error codes into our own internal names which can be
473 * used for call-backs.
475 * @param $errorCode The error code from socket_last_error() to be translated
476 * @return $errorName The translated name (all lower-case, with underlines)
478 public function translateSocketErrorCodeToName ($errorCode) {
479 // Nothing bad happened by default
480 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
482 // Is the code a number, then we have to change it
483 switch ($errorCode) {
484 case 0: // Silently ignored, the socket is connected
487 case 11: // "Resource temporary unavailable"
488 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
491 case 107: // "Transport end-point not connected"
492 case 134: // On some (?) systems for 'transport end-point not connected'
493 // @TODO On some systems it is 134, on some 107?
494 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
497 case 110: // "Connection timed out"
498 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
501 case 111: // "Connection refused"
502 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
505 case 113: // "No route to host"
506 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
509 case 114: // "Operation already in progress"
510 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
513 case 115: // "Operation now in progress"
514 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
517 default: // Everything else <> 0
518 // Unhandled error code detected, so first debug it because we may want to handle it like the others
519 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
521 // Change it only in this class
522 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
526 // Return translated name
531 * Shuts down a given socket resource. This method does only ease calling
534 * @param $socketResource A valid socket resource
537 public function shutdownSocket ($socketResource) {
539 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
541 // Set socket resource
542 $this->setSocketResource($socketResource);
544 // Get a visitor instance
545 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
548 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
551 $this->accept($visitorInstance);
555 * Half-shuts down a given socket resource. This method does only ease calling
556 * an other visitor than shutdownSocket() does.
558 * @param $socketResource A valid socket resource
561 public function halfShutdownSocket ($socketResource) {
563 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
565 // Set socket resource
566 $this->setSocketResource($socketResource);
568 // Get a visitor instance
569 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
572 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
575 $this->accept($visitorInstance);
579 * "Getter" for a printable state name
581 * @return $stateName Name of the node's state in a printable format
583 public final function getPrintableState () {
587 // Get the state instance
588 $stateInstance = $this->getStateInstance();
590 // Is it an instance of Stateable?
591 if ($stateInstance instanceof Stateable) {
592 // Then use that state name
593 $stateName = $stateInstance->getStateName();