3 namespace CoreFramework\Listener;
5 // Import framework stuff
6 use CoreFramework\Object\BaseFrameworkSystem;
9 * A general listener class
11 * @author Roland Haeder <webmaster@shipsimu.org>
13 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
14 * @license GNU GPL 3.0 or any newer version
15 * @link http://www.shipsimu.org
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 class BaseListener extends BaseFrameworkSystem implements Visitable {
31 // Exception code constants
32 const EXCEPTION_INVALID_SOCKET = 0xa00;
33 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
34 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
35 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
36 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
37 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
38 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
39 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
40 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
43 * Address (IP mostly) we shall listen on
45 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
48 * Port we shall listen on (or wait for incoming data)
50 private $listenPort = 0; // This port MUST be changed by your application
53 * Whether we are in blocking or non-blocking mode (default: non-blocking
55 private $blockingMode = FALSE;
58 * A peer pool instance
60 private $poolInstance = NULL;
63 * Protected constructor
65 * @param $className Name of the class
68 protected function __construct ($className) {
69 // Call parent constructor
70 parent::__construct($className);
74 * Checks whether the given socket resource is a server socket
76 * @param $socketResource A valid socket resource
77 * @return $isServerSocket Whether the socket resource is a server socket
79 protected function isServerSocketResource ($socketResource) {
81 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
83 // We need to clear the error here if it is a resource
84 if ($isServerSocket === TRUE) {
86 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('socketResource[]=' . gettype($socketResource));
87 socket_clear_error($socketResource);
90 // Check peer name, it must be empty
91 $isServerSocket = (($isServerSocket) && (empty($peerName)));
94 return $isServerSocket;
98 * Setter for listen address
100 * @param $listenAddress The address this listener should listen on
103 protected final function setListenAddress ($listenAddress) {
104 $this->listenAddress = (string) $listenAddress;
108 * Getter for listen address
110 * @return $listenAddress The address this listener should listen on
112 public final function getListenAddress () {
113 return $this->listenAddress;
117 * Setter for listen port
119 * @param $listenPort The port this listener should listen on
122 protected final function setListenPort ($listenPort) {
123 $this->listenPort = (int) $listenPort;
127 * Getter for listen port
129 * @return $listenPort The port this listener should listen on
131 public final function getListenPort () {
132 return $this->listenPort;
136 * "Setter" to set listen address from configuration entry
138 * @param $configEntry The configuration entry holding our listen address
141 public final function setListenAddressByConfiguration ($configEntry) {
142 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
146 * "Setter" to set listen port from configuration entry
148 * @param $configEntry The configuration entry holding our listen port
151 public final function setListenPortByConfiguration ($configEntry) {
152 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
156 * Setter for blocking-mode
158 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
161 protected final function setBlockingMode ($blockingMode) {
162 $this->blockingMode = (boolean) $blockingMode;
166 * Checks whether blocking-mode is enabled or disabled
168 * @return $blockingMode Whether blocking mode is disabled or enabled
170 public final function isBlockingModeEnabled () {
171 return $this->blockingMode;
175 * Setter for peer pool instance
177 * @param $poolInstance The peer pool instance we shall set
180 protected final function setPoolInstance (PoolablePeer $poolInstance) {
181 $this->poolInstance = $poolInstance;
185 * Getter for peer pool instance
187 * @return $poolInstance The peer pool instance we shall set
189 public final function getPoolInstance () {
190 return $this->poolInstance;
194 * Getter for connection type
196 * @return $connectionType Connection type for this listener
198 public final function getConnectionType () {
199 // Wrap the real getter
200 return $this->getProtocolName();
204 * Registeres the given socket resource for "this" listener instance. This
205 * will be done in a seperate class to allow package writers to use it
208 * @param $socketResource A valid server socket resource
210 * @throws InvalidServerSocketException If the given resource is no server socket
211 * @throws SocketAlreadyRegisteredException If the given resource is already registered
213 protected function registerServerSocketResource ($socketResource) {
214 // First check if it is valid
215 if (!$this->isServerSocketResource($socketResource)) {
217 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
218 } elseif ($this->isServerSocketRegistered($socketResource)) {
219 // Already registered
220 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
223 // Get a socket registry instance (singleton)
224 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
226 // Get a connection info instance
227 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
229 // Will the info instance with listener data
230 $infoInstance->fillWithListenerInformation($this);
232 // Register the socket
233 $registryInstance->registerSocket($infoInstance, $socketResource);
236 $this->setSocketResource($socketResource);
240 * Checks whether given socket resource is registered in socket registry
242 * @param $socketResource A valid server socket resource
243 * @return $isRegistered Whether given server socket is registered
245 protected function isServerSocketRegistered ($socketResource) {
246 // Get a socket registry instance (singleton)
247 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
249 // Get a connection info instance
250 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
252 // Will the info instance with listener data
253 $infoInstance->fillWithListenerInformation($this);
256 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
259 return $isRegistered;
263 * Accepts the visitor to process the visit "request"
265 * @param $visitorInstance An instance of a Visitor class
268 public function accept (Visitor $visitorInstance) {
270 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
272 // Visit this listener
273 $visitorInstance->visitListener($this);
275 // Visit the pool if set
276 if ($this->getPoolInstance() instanceof Poolable) {
277 $this->getPoolInstance()->accept($visitorInstance);
281 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
285 * Monitors incoming raw data from the handler and transfers it to the
286 * given receiver instance. This method should not be called, please call
287 * the decorator's version instead to separator node/client traffic.
290 * @throws UnsupportedOperatorException If this method is called by a mistake
292 public function monitorIncomingRawData () {
293 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
297 * Constructs a callable method name from given socket error code. If the
298 * method is not found, a generic one is used.
300 * @param $errorCode Error code from socket_last_error()
301 * @return $handlerName Call-back method name for the error handler
302 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
304 protected function getSocketErrorHandlerFromCode ($errorCode) {
305 // Create a name from translated error code
306 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
308 // Is the call-back method there?
309 if (!method_exists($this, $handlerName)) {
310 // Please implement this
311 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
319 * Translates socket error codes into our own internal names which can be
320 * used for call-backs.
322 * @param $errorCode The error code from socket_last_error() to be translated
323 * @return $errorName The translated name (all lower-case, with underlines)
325 public function translateSocketErrorCodeToName ($errorCode) {
326 // Nothing bad happened by default
327 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
329 // Is the code a number, then we have to change it
330 switch ($errorCode) {
331 case 0: // Silently ignored, the socket is connected
334 case 11: // "Resource temporary unavailable"
335 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
338 case 13: // "Permission denied"
339 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
342 case 32: // "Broken pipe"
343 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
346 case 104: // "Connection reset by peer"
347 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
350 case 107: // "Transport end-point not connected"
351 case 134: // On some (?) systems for 'transport end-point not connected'
352 // @TODO On some systems it is 134, on some 107?
353 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
356 case 110: // "Connection timed out"
357 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
360 case 111: // "Connection refused"
361 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
364 case 113: // "No route to host"
365 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
368 case 114: // "Operation already in progress"
369 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
372 case 115: // "Operation now in progress"
373 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
376 default: // Everything else <> 0
377 // Unhandled error code detected, so first debug it because we may want to handle it like the others
378 self::createDebugInstance(__CLASS__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
380 // Change it only in this class
381 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
385 // Return translated name
390 * Shuts down a given socket resource. This method does only ease calling
393 * @param $socketResource A valid socket resource
396 public function shutdownSocket ($socketResource) {
398 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
400 // Set socket resource
401 $this->setSocketResource($socketResource);
403 // Get a visitor instance
404 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
407 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
410 $this->accept($visitorInstance);
414 * Half-shuts down a given socket resource. This method does only ease calling
415 * an other visitor than shutdownSocket() does.
417 * @param $socketResource A valid socket resource
420 public function halfShutdownSocket ($socketResource) {
422 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
424 // Set socket resource
425 $this->setSocketResource($socketResource);
427 // Get a visitor instance
428 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
431 self::createDebugInstance(__CLASS__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
434 $this->accept($visitorInstance);
437 // ************************************************************************
438 // Socket error handler call-back methods
439 // ************************************************************************
442 * Handles socket error 'permission denied', but does not clear it for
443 * later debugging purposes.
445 * @param $socketResource A valid socket resource
446 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
448 * @throws SocketBindingException The socket could not be bind to
450 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
451 // Get socket error code for verification
452 $socketError = socket_last_error($socketResource);
455 $errorMessage = socket_strerror($socketError);
457 // Shutdown this socket
458 $this->shutdownSocket($socketResource);
461 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
465 * "Listens" for incoming network packages
467 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
469 * @throws InvalidSocketException If an invalid socket resource has been found
471 protected function doListenSocketSelect ($peerSuffix) {
472 // Check on all instances
473 assert($this->getPoolInstance() instanceof Poolable);
474 assert(is_resource($this->getSocketResource()));
477 $readers = $this->getPoolInstance()->getAllSingleSockets();
481 // Check if we have some peers left
482 $left = socket_select(
490 // Some new peers found?
493 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
500 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
502 // Do we have changed peers?
503 if (in_array($this->getSocketResource(), $readers)) {
505 * Then accept it, if this socket is set to non-blocking IO and the
506 * connection is NOT sending any data, socket_read() may throw
507 * error 11 (Resource temporary unavailable). This really nasty
508 * because if you have blocking IO socket_read() will wait and wait
511 $newSocket = socket_accept($this->getSocketResource());
514 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
516 // Array for timeout settings
519 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
521 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
524 // Set timeout to configured seconds
525 // @TODO Does this work on Windozer boxes???
526 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
527 // Handle this socket error with a faked recipientData array
528 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
531 // Output result (only for debugging!)
533 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
534 self::createDebugInstance(__CLASS__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
537 // Enable SO_OOBINLINE
538 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
539 // Handle this socket error with a faked recipientData array
540 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
544 if (!socket_set_nonblock($newSocket)) {
545 // Handle this socket error with a faked recipientData array
546 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
549 // Add it to the peers
550 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
553 if (!socket_getpeername($newSocket, $peerName)) {
554 // Handle this socket error with a faked recipientData array
555 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
559 $nodeInstance = NodeObjectFactory::createNodeInstance();
561 // Create a faked package data array
562 $packageData = array(
563 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
564 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
565 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
568 // Get a connection info instance
569 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
571 // Will the info instance with listener data
572 $infoInstance->fillWithListenerInformation($this);
574 // Get a socket registry
575 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
577 // Register the socket with the registry and with the faked array
578 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
581 // Do we have to rewind?
582 if (!$this->getIteratorInstance()->valid()) {
584 $this->getIteratorInstance()->rewind();
587 // Get the current value
588 $currentSocket = $this->getIteratorInstance()->current();
590 // Handle it here, if not main server socket
591 //* 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());
592 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
593 // ... or else it will raise warnings like 'Transport endpoint is not connected'
594 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
597 // Advance to next entry. This should be the last line.
598 $this->getIteratorInstance()->next();