3 namespace CoreFramework\Listener;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Generic\UnsupportedOperationException;
8 use CoreFramework\Object\BaseFrameworkSystem;
9 use CoreFramework\Pool\Poolable;
10 use CoreFramework\Visitor\Visitable;
11 use CoreFramework\Visitor\Visitor;
14 * A general listener class
16 * @author Roland Haeder <webmaster@shipsimu.org>
18 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
19 * @license GNU GPL 3.0 or any newer version
20 * @link http://www.shipsimu.org
22 * This program is free software: you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation, either version 3 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 class BaseListener extends BaseFrameworkSystem implements Visitable {
36 // Exception code constants
37 const EXCEPTION_INVALID_SOCKET = 0xa00;
38 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
39 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
40 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
41 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
42 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
43 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
44 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
45 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
48 * Address (IP mostly) we shall listen on
50 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
53 * Port we shall listen on (or wait for incoming data)
55 private $listenPort = 0; // This port MUST be changed by your application
58 * Whether we are in blocking or non-blocking mode (default: non-blocking
60 private $blockingMode = false;
63 * A peer pool instance
65 private $poolInstance = NULL;
68 * Protected constructor
70 * @param $className Name of the class
73 protected function __construct ($className) {
74 // Call parent constructor
75 parent::__construct($className);
79 * Checks whether the given socket resource is a server socket
81 * @param $socketResource A valid socket resource
82 * @return $isServerSocket Whether the socket resource is a server socket
84 protected function isServerSocketResource ($socketResource) {
86 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
88 // We need to clear the error here if it is a resource
89 if ($isServerSocket === true) {
91 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('socketResource[]=' . gettype($socketResource));
92 socket_clear_error($socketResource);
95 // Check peer name, it must be empty
96 $isServerSocket = (($isServerSocket) && (empty($peerName)));
99 return $isServerSocket;
103 * Setter for listen address
105 * @param $listenAddress The address this listener should listen on
108 protected final function setListenAddress ($listenAddress) {
109 $this->listenAddress = (string) $listenAddress;
113 * Getter for listen address
115 * @return $listenAddress The address this listener should listen on
117 public final function getListenAddress () {
118 return $this->listenAddress;
122 * Setter for listen port
124 * @param $listenPort The port this listener should listen on
127 protected final function setListenPort ($listenPort) {
128 $this->listenPort = (int) $listenPort;
132 * Getter for listen port
134 * @return $listenPort The port this listener should listen on
136 public final function getListenPort () {
137 return $this->listenPort;
141 * "Setter" to set listen address from configuration entry
143 * @param $configEntry The configuration entry holding our listen address
146 public final function setListenAddressByConfiguration ($configEntry) {
147 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
151 * "Setter" to set listen port from configuration entry
153 * @param $configEntry The configuration entry holding our listen port
156 public final function setListenPortByConfiguration ($configEntry) {
157 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
161 * Setter for blocking-mode
163 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
166 protected final function setBlockingMode ($blockingMode) {
167 $this->blockingMode = (boolean) $blockingMode;
171 * Checks whether blocking-mode is enabled or disabled
173 * @return $blockingMode Whether blocking mode is disabled or enabled
175 public final function isBlockingModeEnabled () {
176 return $this->blockingMode;
180 * Setter for peer pool instance
182 * @param $poolInstance The peer pool instance we shall set
185 protected final function setPoolInstance (PoolablePeer $poolInstance) {
186 $this->poolInstance = $poolInstance;
190 * Getter for peer pool instance
192 * @return $poolInstance The peer pool instance we shall set
194 public final function getPoolInstance () {
195 return $this->poolInstance;
199 * Getter for connection type
201 * @return $connectionType Connection type for this listener
203 public final function getConnectionType () {
204 // Wrap the real getter
205 return $this->getProtocolName();
209 * Registeres the given socket resource for "this" listener instance. This
210 * will be done in a seperate class to allow package writers to use it
213 * @param $socketResource A valid server socket resource
215 * @throws InvalidServerSocketException If the given resource is no server socket
216 * @throws SocketAlreadyRegisteredException If the given resource is already registered
218 protected function registerServerSocketResource ($socketResource) {
219 // First check if it is valid
220 if (!$this->isServerSocketResource($socketResource)) {
222 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
223 } elseif ($this->isServerSocketRegistered($socketResource)) {
224 // Already registered
225 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
228 // Get a socket registry instance (singleton)
229 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
231 // Get a connection info instance
232 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
234 // Will the info instance with listener data
235 $infoInstance->fillWithListenerInformation($this);
237 // Register the socket
238 $registryInstance->registerSocket($infoInstance, $socketResource);
241 $this->setSocketResource($socketResource);
245 * Checks whether given socket resource is registered in socket registry
247 * @param $socketResource A valid server socket resource
248 * @return $isRegistered Whether given server socket is registered
250 protected function isServerSocketRegistered ($socketResource) {
251 // Get a socket registry instance (singleton)
252 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
254 // Get a connection info instance
255 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
257 // Will the info instance with listener data
258 $infoInstance->fillWithListenerInformation($this);
261 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
264 return $isRegistered;
268 * Accepts the visitor to process the visit "request"
270 * @param $visitorInstance An instance of a Visitor class
273 public function accept (Visitor $visitorInstance) {
275 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
277 // Visit this listener
278 $visitorInstance->visitListener($this);
280 // Visit the pool if set
281 if ($this->getPoolInstance() instanceof Poolable) {
282 $this->getPoolInstance()->accept($visitorInstance);
286 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
290 * Monitors incoming raw data from the handler and transfers it to the
291 * given receiver instance. This method should not be called, please call
292 * the decorator's version instead to separator node/client traffic.
295 * @throws UnsupportedOperatorException If this method is called by a mistake
297 public function monitorIncomingRawData () {
298 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
302 * Constructs a callable method name from given socket error code. If the
303 * method is not found, a generic one is used.
305 * @param $errorCode Error code from socket_last_error()
306 * @return $handlerName Call-back method name for the error handler
307 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
309 protected function getSocketErrorHandlerFromCode ($errorCode) {
310 // Create a name from translated error code
311 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
313 // Is the call-back method there?
314 if (!method_exists($this, $handlerName)) {
315 // Please implement this
316 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
324 * Translates socket error codes into our own internal names which can be
325 * used for call-backs.
327 * @param $errorCode The error code from socket_last_error() to be translated
328 * @return $errorName The translated name (all lower-case, with underlines)
330 public function translateSocketErrorCodeToName ($errorCode) {
331 // Nothing bad happened by default
332 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
334 // Is the code a number, then we have to change it
335 switch ($errorCode) {
336 case 0: // Silently ignored, the socket is connected
339 case 11: // "Resource temporary unavailable"
340 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
343 case 13: // "Permission denied"
344 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
347 case 32: // "Broken pipe"
348 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
351 case 104: // "Connection reset by peer"
352 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
355 case 107: // "Transport end-point not connected"
356 case 134: // On some (?) systems for 'transport end-point not connected'
357 // @TODO On some systems it is 134, on some 107?
358 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
361 case 110: // "Connection timed out"
362 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
365 case 111: // "Connection refused"
366 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
369 case 113: // "No route to host"
370 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
373 case 114: // "Operation already in progress"
374 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
377 case 115: // "Operation now in progress"
378 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
381 default: // Everything else <> 0
382 // Unhandled error code detected, so first debug it because we may want to handle it like the others
383 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
385 // Change it only in this class
386 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
390 // Return translated name
395 * Shuts down a given socket resource. This method does only ease calling
398 * @param $socketResource A valid socket resource
401 public function shutdownSocket ($socketResource) {
403 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
405 // Set socket resource
406 $this->setSocketResource($socketResource);
408 // Get a visitor instance
409 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
412 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
415 $this->accept($visitorInstance);
419 * Half-shuts down a given socket resource. This method does only ease calling
420 * an other visitor than shutdownSocket() does.
422 * @param $socketResource A valid socket resource
425 public function halfShutdownSocket ($socketResource) {
427 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
429 // Set socket resource
430 $this->setSocketResource($socketResource);
432 // Get a visitor instance
433 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
436 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
439 $this->accept($visitorInstance);
442 // ************************************************************************
443 // Socket error handler call-back methods
444 // ************************************************************************
447 * Handles socket error 'permission denied', but does not clear it for
448 * later debugging purposes.
450 * @param $socketResource A valid socket resource
451 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
453 * @throws SocketBindingException The socket could not be bind to
455 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
456 // Get socket error code for verification
457 $socketError = socket_last_error($socketResource);
460 $errorMessage = socket_strerror($socketError);
462 // Shutdown this socket
463 $this->shutdownSocket($socketResource);
466 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
470 * "Listens" for incoming network packages
472 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
474 * @throws InvalidSocketException If an invalid socket resource has been found
476 protected function doListenSocketSelect ($peerSuffix) {
477 // Check on all instances
478 assert($this->getPoolInstance() instanceof Poolable);
479 assert(is_resource($this->getSocketResource()));
482 $readers = $this->getPoolInstance()->getAllSingleSockets();
486 // Check if we have some peers left
487 $left = socket_select(
495 // Some new peers found?
498 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, true));
505 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, true));
507 // Do we have changed peers?
508 if (in_array($this->getSocketResource(), $readers)) {
510 * Then accept it, if this socket is set to non-blocking IO and the
511 * connection is NOT sending any data, socket_read() may throw
512 * error 11 (Resource temporary unavailable). This really nasty
513 * because if you have blocking IO socket_read() will wait and wait
516 $newSocket = socket_accept($this->getSocketResource());
519 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
521 // Array for timeout settings
524 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
526 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
529 // Set timeout to configured seconds
530 // @TODO Does this work on Windozer boxes???
531 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
532 // Handle this socket error with a faked recipientData array
533 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
536 // Output result (only for debugging!)
538 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
539 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, true));
542 // Enable SO_OOBINLINE
543 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
544 // Handle this socket error with a faked recipientData array
545 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
549 if (!socket_set_nonblock($newSocket)) {
550 // Handle this socket error with a faked recipientData array
551 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
554 // Add it to the peers
555 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
558 if (!socket_getpeername($newSocket, $peerName)) {
559 // Handle this socket error with a faked recipientData array
560 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
564 $nodeInstance = NodeObjectFactory::createNodeInstance();
566 // Create a faked package data array
567 $packageData = array(
568 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
569 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
570 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
573 // Get a connection info instance
574 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
576 // Will the info instance with listener data
577 $infoInstance->fillWithListenerInformation($this);
579 // Get a socket registry
580 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
582 // Register the socket with the registry and with the faked array
583 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
586 // Do we have to rewind?
587 if (!$this->getIteratorInstance()->valid()) {
589 $this->getIteratorInstance()->rewind();
592 // Get the current value
593 $currentSocket = $this->getIteratorInstance()->current();
595 // Handle it here, if not main server socket
596 //* 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());
597 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
598 // ... or else it will raise warnings like 'Transport endpoint is not connected'
599 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
602 // Advance to next entry. This should be the last line.
603 $this->getIteratorInstance()->next();