3 * A general listener class
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core 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 abstract class BaseListener extends BaseFrameworkSystem implements Visitable {
25 // Exception code constants
26 const EXCEPTION_INVALID_SOCKET = 0xa00;
27 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
28 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
29 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
30 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
31 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
32 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
33 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
34 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
37 * Address (IP mostly) we shall listen on
39 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
42 * Port we shall listen on (or wait for incoming data)
44 private $listenPort = 0; // This port MUST be changed by your application
47 * Whether we are in blocking or non-blocking mode (default: non-blocking
49 private $blockingMode = FALSE;
52 * A peer pool instance
54 private $poolInstance = NULL;
57 * Protected constructor
59 * @param $className Name of the class
62 protected function __construct ($className) {
63 // Call parent constructor
64 parent::__construct($className);
68 * Checks whether the given socket resource is a server socket
70 * @param $socketResource A valid socket resource
71 * @return $isServerSocket Whether the socket resource is a server socket
73 protected function isServerSocketResource ($socketResource) {
75 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
77 // We need to clear the error here if it is a resource
78 if ($isServerSocket === TRUE) {
80 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('socketResource[]=' . gettype($socketResource));
81 socket_clear_error($socketResource);
84 // Check peer name, it must be empty
85 $isServerSocket = (($isServerSocket) && (empty($peerName)));
88 return $isServerSocket;
92 * Setter for listen address
94 * @param $listenAddress The address this listener should listen on
97 protected final function setListenAddress ($listenAddress) {
98 $this->listenAddress = (string) $listenAddress;
102 * Getter for listen address
104 * @return $listenAddress The address this listener should listen on
106 public final function getListenAddress () {
107 return $this->listenAddress;
111 * Setter for listen port
113 * @param $listenPort The port this listener should listen on
116 protected final function setListenPort ($listenPort) {
117 $this->listenPort = (int) $listenPort;
121 * Getter for listen port
123 * @return $listenPort The port this listener should listen on
125 public final function getListenPort () {
126 return $this->listenPort;
130 * "Setter" to set listen address from configuration entry
132 * @param $configEntry The configuration entry holding our listen address
135 public final function setListenAddressByConfiguration ($configEntry) {
136 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
140 * "Setter" to set listen port from configuration entry
142 * @param $configEntry The configuration entry holding our listen port
145 public final function setListenPortByConfiguration ($configEntry) {
146 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
150 * Setter for blocking-mode
152 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
155 protected final function setBlockingMode ($blockingMode) {
156 $this->blockingMode = (boolean) $blockingMode;
160 * Checks whether blocking-mode is enabled or disabled
162 * @return $blockingMode Whether blocking mode is disabled or enabled
164 public final function isBlockingModeEnabled () {
165 return $this->blockingMode;
169 * Setter for peer pool instance
171 * @param $poolInstance The peer pool instance we shall set
174 protected final function setPoolInstance (PoolablePeer $poolInstance) {
175 $this->poolInstance = $poolInstance;
179 * Getter for peer pool instance
181 * @return $poolInstance The peer pool instance we shall set
183 public final function getPoolInstance () {
184 return $this->poolInstance;
188 * Getter for connection type
190 * @return $connectionType Connection type for this listener
192 public final function getConnectionType () {
193 // Wrap the real getter
194 return $this->getProtocolName();
198 * Registeres the given socket resource for "this" listener instance. This
199 * will be done in a seperate class to allow package writers to use it
202 * @param $socketResource A valid server socket resource
204 * @throws InvalidServerSocketException If the given resource is no server socket
205 * @throws SocketAlreadyRegisteredException If the given resource is already registered
207 protected function registerServerSocketResource ($socketResource) {
208 // First check if it is valid
209 if (!$this->isServerSocketResource($socketResource)) {
211 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
212 } elseif ($this->isServerSocketRegistered($socketResource)) {
213 // Already registered
214 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
217 // Get a socket registry instance (singleton)
218 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
220 // Get a connection info instance
221 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
223 // Will the info instance with listener data
224 $infoInstance->fillWithListenerInformation($this);
226 // Register the socket
227 $registryInstance->registerSocket($infoInstance, $socketResource);
230 $this->setSocketResource($socketResource);
234 * Checks whether given socket resource is registered in socket registry
236 * @param $socketResource A valid server socket resource
237 * @return $isRegistered Whether given server socket is registered
239 protected function isServerSocketRegistered ($socketResource) {
240 // Get a socket registry instance (singleton)
241 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
243 // Get a connection info instance
244 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
246 // Will the info instance with listener data
247 $infoInstance->fillWithListenerInformation($this);
250 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
253 return $isRegistered;
257 * Accepts the visitor to process the visit "request"
259 * @param $visitorInstance An instance of a Visitor class
262 public function accept (Visitor $visitorInstance) {
264 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
266 // Visit this listener
267 $visitorInstance->visitListener($this);
269 // Visit the pool if set
270 if ($this->getPoolInstance() instanceof Poolable) {
271 $this->getPoolInstance()->accept($visitorInstance);
275 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
279 * Monitors incoming raw data from the handler and transfers it to the
280 * given receiver instance. This method should not be called, please call
281 * the decorator's version instead to separator node/client traffic.
284 * @throws UnsupportedOperatorException If this method is called by a mistake
286 public function monitorIncomingRawData () {
287 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
291 * Constructs a callable method name from given socket error code. If the
292 * method is not found, a generic one is used.
294 * @param $errorCode Error code from socket_last_error()
295 * @return $handlerName Call-back method name for the error handler
296 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
298 protected function getSocketErrorHandlerFromCode ($errorCode) {
299 // Create a name from translated error code
300 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
302 // Is the call-back method there?
303 if (!method_exists($this, $handlerName)) {
304 // Please implement this
305 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
313 * Translates socket error codes into our own internal names which can be
314 * used for call-backs.
316 * @param $errorCode The error code from socket_last_error() to be translated
317 * @return $errorName The translated name (all lower-case, with underlines)
319 public function translateSocketErrorCodeToName ($errorCode) {
320 // Nothing bad happened by default
321 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
323 // Is the code a number, then we have to change it
324 switch ($errorCode) {
325 case 0: // Silently ignored, the socket is connected
328 case 11: // "Resource temporary unavailable"
329 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
332 case 13: // "Permission denied"
333 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
336 case 32: // "Broken pipe"
337 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
340 case 104: // "Connection reset by peer"
341 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
344 case 107: // "Transport end-point not connected"
345 case 134: // On some (?) systems for 'transport end-point not connected'
346 // @TODO On some systems it is 134, on some 107?
347 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
350 case 110: // "Connection timed out"
351 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
354 case 111: // "Connection refused"
355 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
358 case 113: // "No route to host"
359 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
362 case 114: // "Operation already in progress"
363 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
366 case 115: // "Operation now in progress"
367 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
370 default: // Everything else <> 0
371 // Unhandled error code detected, so first debug it because we may want to handle it like the others
372 self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
374 // Change it only in this class
375 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
379 // Return translated name
384 * Shuts down a given socket resource. This method does only ease calling
387 * @param $socketResource A valid socket resource
390 public function shutdownSocket ($socketResource) {
392 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
394 // Set socket resource
395 $this->setSocketResource($socketResource);
397 // Get a visitor instance
398 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
401 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
404 $this->accept($visitorInstance);
408 * Half-shuts down a given socket resource. This method does only ease calling
409 * an other visitor than shutdownSocket() does.
411 * @param $socketResource A valid socket resource
414 public function halfShutdownSocket ($socketResource) {
416 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
418 // Set socket resource
419 $this->setSocketResource($socketResource);
421 // Get a visitor instance
422 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
425 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
428 $this->accept($visitorInstance);
431 // ************************************************************************
432 // Socket error handler call-back methods
433 // ************************************************************************
436 * Handles socket error 'permission denied', but does not clear it for
437 * later debugging purposes.
439 * @param $socketResource A valid socket resource
440 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
442 * @throws SocketBindingException The socket could not be bind to
444 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
445 // Get socket error code for verification
446 $socketError = socket_last_error($socketResource);
449 $errorMessage = socket_strerror($socketError);
451 // Shutdown this socket
452 $this->shutdownSocket($socketResource);
455 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
459 * "Listens" for incoming network packages
461 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
463 * @throws InvalidSocketException If an invalid socket resource has been found
465 protected function doListenSocketSelect ($peerSuffix) {
466 // Check on all instances
467 assert($this->getPoolInstance() instanceof Poolable);
468 assert(is_resource($this->getSocketResource()));
471 $readers = $this->getPoolInstance()->getAllSingleSockets();
475 // Check if we have some peers left
476 $left = socket_select(
484 // Some new peers found?
487 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
494 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
496 // Do we have changed peers?
497 if (in_array($this->getSocketResource(), $readers)) {
499 * Then accept it, if this socket is set to non-blocking IO and the
500 * connection is NOT sending any data, socket_read() may throw
501 * error 11 (Resource temporary unavailable). This really nasty
502 * because if you have blocking IO socket_read() will wait and wait
505 $newSocket = socket_accept($this->getSocketResource());
508 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
510 // Array for timeout settings
513 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
515 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
518 // Set timeout to configured seconds
519 // @TODO Does this work on Windozer boxes???
520 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
521 // Handle this socket error with a faked recipientData array
522 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
525 // Output result (only for debugging!)
527 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
528 self::createDebugInstance(__CLASS__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
531 // Enable SO_OOBINLINE
532 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
533 // Handle this socket error with a faked recipientData array
534 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
538 if (!socket_set_nonblock($newSocket)) {
539 // Handle this socket error with a faked recipientData array
540 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
543 // Add it to the peers
544 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
547 if (!socket_getpeername($newSocket, $peerName)) {
548 // Handle this socket error with a faked recipientData array
549 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
553 $nodeInstance = NodeObjectFactory::createNodeInstance();
555 // Create a faked package data array
556 $packageData = array(
557 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
558 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
559 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
562 // Get a connection info instance
563 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
565 // Will the info instance with listener data
566 $infoInstance->fillWithListenerInformation($this);
568 // Get a socket registry
569 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
571 // Register the socket with the registry and with the faked array
572 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
575 // Do we have to rewind?
576 if (!$this->getIteratorInstance()->valid()) {
578 $this->getIteratorInstance()->rewind();
581 // Get the current value
582 $currentSocket = $this->getIteratorInstance()->current();
584 // Handle it here, if not main server socket
585 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: currentSocket=' . $currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] . ',type=' . $currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] . ',serverSocket=' . $this->getSocketResource());
586 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
587 // ... or else it will raise warnings like 'Transport endpoint is not connected'
588 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
591 // Advance to next entry. This should be the last line.
592 $this->getIteratorInstance()->next();