3 namespace CoreFramework\Listener;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Object\BaseFrameworkSystem;
8 use CoreFramework\Pool\Poolable;
9 use CoreFramework\Visitor\Visitable;
10 use CoreFramework\Visitor\Visitor;
13 * A general listener class
15 * @author Roland Haeder <webmaster@shipsimu.org>
17 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
18 * @license GNU GPL 3.0 or any newer version
19 * @link http://www.shipsimu.org
21 * This program is free software: you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation, either version 3 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 class BaseListener extends BaseFrameworkSystem implements Visitable {
35 // Exception code constants
36 const EXCEPTION_INVALID_SOCKET = 0xa00;
37 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
38 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
39 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
40 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
41 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
42 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
43 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
44 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
47 * Address (IP mostly) we shall listen on
49 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
52 * Port we shall listen on (or wait for incoming data)
54 private $listenPort = 0; // This port MUST be changed by your application
57 * Whether we are in blocking or non-blocking mode (default: non-blocking
59 private $blockingMode = false;
62 * A peer pool instance
64 private $poolInstance = NULL;
67 * Protected constructor
69 * @param $className Name of the class
72 protected function __construct ($className) {
73 // Call parent constructor
74 parent::__construct($className);
78 * Checks whether the given socket resource is a server socket
80 * @param $socketResource A valid socket resource
81 * @return $isServerSocket Whether the socket resource is a server socket
83 protected function isServerSocketResource ($socketResource) {
85 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
87 // We need to clear the error here if it is a resource
88 if ($isServerSocket === true) {
90 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('socketResource[]=' . gettype($socketResource));
91 socket_clear_error($socketResource);
94 // Check peer name, it must be empty
95 $isServerSocket = (($isServerSocket) && (empty($peerName)));
98 return $isServerSocket;
102 * Setter for listen address
104 * @param $listenAddress The address this listener should listen on
107 protected final function setListenAddress ($listenAddress) {
108 $this->listenAddress = (string) $listenAddress;
112 * Getter for listen address
114 * @return $listenAddress The address this listener should listen on
116 public final function getListenAddress () {
117 return $this->listenAddress;
121 * Setter for listen port
123 * @param $listenPort The port this listener should listen on
126 protected final function setListenPort ($listenPort) {
127 $this->listenPort = (int) $listenPort;
131 * Getter for listen port
133 * @return $listenPort The port this listener should listen on
135 public final function getListenPort () {
136 return $this->listenPort;
140 * "Setter" to set listen address from configuration entry
142 * @param $configEntry The configuration entry holding our listen address
145 public final function setListenAddressByConfiguration ($configEntry) {
146 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
150 * "Setter" to set listen port from configuration entry
152 * @param $configEntry The configuration entry holding our listen port
155 public final function setListenPortByConfiguration ($configEntry) {
156 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
160 * Setter for blocking-mode
162 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
165 protected final function setBlockingMode ($blockingMode) {
166 $this->blockingMode = (boolean) $blockingMode;
170 * Checks whether blocking-mode is enabled or disabled
172 * @return $blockingMode Whether blocking mode is disabled or enabled
174 public final function isBlockingModeEnabled () {
175 return $this->blockingMode;
179 * Setter for peer pool instance
181 * @param $poolInstance The peer pool instance we shall set
184 protected final function setPoolInstance (PoolablePeer $poolInstance) {
185 $this->poolInstance = $poolInstance;
189 * Getter for peer pool instance
191 * @return $poolInstance The peer pool instance we shall set
193 public final function getPoolInstance () {
194 return $this->poolInstance;
198 * Getter for connection type
200 * @return $connectionType Connection type for this listener
202 public final function getConnectionType () {
203 // Wrap the real getter
204 return $this->getProtocolName();
208 * Registeres the given socket resource for "this" listener instance. This
209 * will be done in a seperate class to allow package writers to use it
212 * @param $socketResource A valid server socket resource
214 * @throws InvalidServerSocketException If the given resource is no server socket
215 * @throws SocketAlreadyRegisteredException If the given resource is already registered
217 protected function registerServerSocketResource ($socketResource) {
218 // First check if it is valid
219 if (!$this->isServerSocketResource($socketResource)) {
221 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
222 } elseif ($this->isServerSocketRegistered($socketResource)) {
223 // Already registered
224 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
227 // Get a socket registry instance (singleton)
228 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
230 // Get a connection info instance
231 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
233 // Will the info instance with listener data
234 $infoInstance->fillWithListenerInformation($this);
236 // Register the socket
237 $registryInstance->registerSocket($infoInstance, $socketResource);
240 $this->setSocketResource($socketResource);
244 * Checks whether given socket resource is registered in socket registry
246 * @param $socketResource A valid server socket resource
247 * @return $isRegistered Whether given server socket is registered
249 protected function isServerSocketRegistered ($socketResource) {
250 // Get a socket registry instance (singleton)
251 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
253 // Get a connection info instance
254 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
256 // Will the info instance with listener data
257 $infoInstance->fillWithListenerInformation($this);
260 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
263 return $isRegistered;
267 * Accepts the visitor to process the visit "request"
269 * @param $visitorInstance An instance of a Visitor class
272 public function accept (Visitor $visitorInstance) {
274 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
276 // Visit this listener
277 $visitorInstance->visitListener($this);
279 // Visit the pool if set
280 if ($this->getPoolInstance() instanceof Poolable) {
281 $this->getPoolInstance()->accept($visitorInstance);
285 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
289 * Monitors incoming raw data from the handler and transfers it to the
290 * given receiver instance. This method should not be called, please call
291 * the decorator's version instead to separator node/client traffic.
294 * @throws UnsupportedOperatorException If this method is called by a mistake
296 public function monitorIncomingRawData () {
297 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
301 * Constructs a callable method name from given socket error code. If the
302 * method is not found, a generic one is used.
304 * @param $errorCode Error code from socket_last_error()
305 * @return $handlerName Call-back method name for the error handler
306 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
308 protected function getSocketErrorHandlerFromCode ($errorCode) {
309 // Create a name from translated error code
310 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
312 // Is the call-back method there?
313 if (!method_exists($this, $handlerName)) {
314 // Please implement this
315 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
323 * Translates socket error codes into our own internal names which can be
324 * used for call-backs.
326 * @param $errorCode The error code from socket_last_error() to be translated
327 * @return $errorName The translated name (all lower-case, with underlines)
329 public function translateSocketErrorCodeToName ($errorCode) {
330 // Nothing bad happened by default
331 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
333 // Is the code a number, then we have to change it
334 switch ($errorCode) {
335 case 0: // Silently ignored, the socket is connected
338 case 11: // "Resource temporary unavailable"
339 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
342 case 13: // "Permission denied"
343 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
346 case 32: // "Broken pipe"
347 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
350 case 104: // "Connection reset by peer"
351 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
354 case 107: // "Transport end-point not connected"
355 case 134: // On some (?) systems for 'transport end-point not connected'
356 // @TODO On some systems it is 134, on some 107?
357 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
360 case 110: // "Connection timed out"
361 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
364 case 111: // "Connection refused"
365 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
368 case 113: // "No route to host"
369 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
372 case 114: // "Operation already in progress"
373 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
376 case 115: // "Operation now in progress"
377 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
380 default: // Everything else <> 0
381 // Unhandled error code detected, so first debug it because we may want to handle it like the others
382 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
384 // Change it only in this class
385 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
389 // Return translated name
394 * Shuts down a given socket resource. This method does only ease calling
397 * @param $socketResource A valid socket resource
400 public function shutdownSocket ($socketResource) {
402 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
404 // Set socket resource
405 $this->setSocketResource($socketResource);
407 // Get a visitor instance
408 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
411 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
414 $this->accept($visitorInstance);
418 * Half-shuts down a given socket resource. This method does only ease calling
419 * an other visitor than shutdownSocket() does.
421 * @param $socketResource A valid socket resource
424 public function halfShutdownSocket ($socketResource) {
426 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
428 // Set socket resource
429 $this->setSocketResource($socketResource);
431 // Get a visitor instance
432 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
435 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
438 $this->accept($visitorInstance);
441 // ************************************************************************
442 // Socket error handler call-back methods
443 // ************************************************************************
446 * Handles socket error 'permission denied', but does not clear it for
447 * later debugging purposes.
449 * @param $socketResource A valid socket resource
450 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
452 * @throws SocketBindingException The socket could not be bind to
454 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
455 // Get socket error code for verification
456 $socketError = socket_last_error($socketResource);
459 $errorMessage = socket_strerror($socketError);
461 // Shutdown this socket
462 $this->shutdownSocket($socketResource);
465 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
469 * "Listens" for incoming network packages
471 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
473 * @throws InvalidSocketException If an invalid socket resource has been found
475 protected function doListenSocketSelect ($peerSuffix) {
476 // Check on all instances
477 assert($this->getPoolInstance() instanceof Poolable);
478 assert(is_resource($this->getSocketResource()));
481 $readers = $this->getPoolInstance()->getAllSingleSockets();
485 // Check if we have some peers left
486 $left = socket_select(
494 // Some new peers found?
497 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, true));
504 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, true));
506 // Do we have changed peers?
507 if (in_array($this->getSocketResource(), $readers)) {
509 * Then accept it, if this socket is set to non-blocking IO and the
510 * connection is NOT sending any data, socket_read() may throw
511 * error 11 (Resource temporary unavailable). This really nasty
512 * because if you have blocking IO socket_read() will wait and wait
515 $newSocket = socket_accept($this->getSocketResource());
518 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
520 // Array for timeout settings
523 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
525 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
528 // Set timeout to configured seconds
529 // @TODO Does this work on Windozer boxes???
530 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
531 // Handle this socket error with a faked recipientData array
532 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
535 // Output result (only for debugging!)
537 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
538 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, true));
541 // Enable SO_OOBINLINE
542 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
543 // Handle this socket error with a faked recipientData array
544 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
548 if (!socket_set_nonblock($newSocket)) {
549 // Handle this socket error with a faked recipientData array
550 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
553 // Add it to the peers
554 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
557 if (!socket_getpeername($newSocket, $peerName)) {
558 // Handle this socket error with a faked recipientData array
559 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
563 $nodeInstance = NodeObjectFactory::createNodeInstance();
565 // Create a faked package data array
566 $packageData = array(
567 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
568 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
569 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
572 // Get a connection info instance
573 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
575 // Will the info instance with listener data
576 $infoInstance->fillWithListenerInformation($this);
578 // Get a socket registry
579 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
581 // Register the socket with the registry and with the faked array
582 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
585 // Do we have to rewind?
586 if (!$this->getIteratorInstance()->valid()) {
588 $this->getIteratorInstance()->rewind();
591 // Get the current value
592 $currentSocket = $this->getIteratorInstance()->current();
594 // Handle it here, if not main server socket
595 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: currentSocket=' . $currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] . ',type=' . $currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] . ',serverSocket=' . $this->getSocketResource());
596 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
597 // ... or else it will raise warnings like 'Transport endpoint is not connected'
598 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
601 // Advance to next entry. This should be the last line.
602 $this->getIteratorInstance()->next();