3 namespace CoreFramework\Listener;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Object\BaseFrameworkSystem;
10 * A general listener class
12 * @author Roland Haeder <webmaster@shipsimu.org>
14 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15 * @license GNU GPL 3.0 or any newer version
16 * @link http://www.shipsimu.org
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 class BaseListener extends BaseFrameworkSystem implements Visitable {
32 // Exception code constants
33 const EXCEPTION_INVALID_SOCKET = 0xa00;
34 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
35 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
36 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
37 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
38 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
39 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
40 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
41 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
44 * Address (IP mostly) we shall listen on
46 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
49 * Port we shall listen on (or wait for incoming data)
51 private $listenPort = 0; // This port MUST be changed by your application
54 * Whether we are in blocking or non-blocking mode (default: non-blocking
56 private $blockingMode = FALSE;
59 * A peer pool instance
61 private $poolInstance = NULL;
64 * Protected constructor
66 * @param $className Name of the class
69 protected function __construct ($className) {
70 // Call parent constructor
71 parent::__construct($className);
75 * Checks whether the given socket resource is a server socket
77 * @param $socketResource A valid socket resource
78 * @return $isServerSocket Whether the socket resource is a server socket
80 protected function isServerSocketResource ($socketResource) {
82 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
84 // We need to clear the error here if it is a resource
85 if ($isServerSocket === TRUE) {
87 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('socketResource[]=' . gettype($socketResource));
88 socket_clear_error($socketResource);
91 // Check peer name, it must be empty
92 $isServerSocket = (($isServerSocket) && (empty($peerName)));
95 return $isServerSocket;
99 * Setter for listen address
101 * @param $listenAddress The address this listener should listen on
104 protected final function setListenAddress ($listenAddress) {
105 $this->listenAddress = (string) $listenAddress;
109 * Getter for listen address
111 * @return $listenAddress The address this listener should listen on
113 public final function getListenAddress () {
114 return $this->listenAddress;
118 * Setter for listen port
120 * @param $listenPort The port this listener should listen on
123 protected final function setListenPort ($listenPort) {
124 $this->listenPort = (int) $listenPort;
128 * Getter for listen port
130 * @return $listenPort The port this listener should listen on
132 public final function getListenPort () {
133 return $this->listenPort;
137 * "Setter" to set listen address from configuration entry
139 * @param $configEntry The configuration entry holding our listen address
142 public final function setListenAddressByConfiguration ($configEntry) {
143 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
147 * "Setter" to set listen port from configuration entry
149 * @param $configEntry The configuration entry holding our listen port
152 public final function setListenPortByConfiguration ($configEntry) {
153 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
157 * Setter for blocking-mode
159 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
162 protected final function setBlockingMode ($blockingMode) {
163 $this->blockingMode = (boolean) $blockingMode;
167 * Checks whether blocking-mode is enabled or disabled
169 * @return $blockingMode Whether blocking mode is disabled or enabled
171 public final function isBlockingModeEnabled () {
172 return $this->blockingMode;
176 * Setter for peer pool instance
178 * @param $poolInstance The peer pool instance we shall set
181 protected final function setPoolInstance (PoolablePeer $poolInstance) {
182 $this->poolInstance = $poolInstance;
186 * Getter for peer pool instance
188 * @return $poolInstance The peer pool instance we shall set
190 public final function getPoolInstance () {
191 return $this->poolInstance;
195 * Getter for connection type
197 * @return $connectionType Connection type for this listener
199 public final function getConnectionType () {
200 // Wrap the real getter
201 return $this->getProtocolName();
205 * Registeres the given socket resource for "this" listener instance. This
206 * will be done in a seperate class to allow package writers to use it
209 * @param $socketResource A valid server socket resource
211 * @throws InvalidServerSocketException If the given resource is no server socket
212 * @throws SocketAlreadyRegisteredException If the given resource is already registered
214 protected function registerServerSocketResource ($socketResource) {
215 // First check if it is valid
216 if (!$this->isServerSocketResource($socketResource)) {
218 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
219 } elseif ($this->isServerSocketRegistered($socketResource)) {
220 // Already registered
221 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
224 // Get a socket registry instance (singleton)
225 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
227 // Get a connection info instance
228 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
230 // Will the info instance with listener data
231 $infoInstance->fillWithListenerInformation($this);
233 // Register the socket
234 $registryInstance->registerSocket($infoInstance, $socketResource);
237 $this->setSocketResource($socketResource);
241 * Checks whether given socket resource is registered in socket registry
243 * @param $socketResource A valid server socket resource
244 * @return $isRegistered Whether given server socket is registered
246 protected function isServerSocketRegistered ($socketResource) {
247 // Get a socket registry instance (singleton)
248 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
250 // Get a connection info instance
251 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
253 // Will the info instance with listener data
254 $infoInstance->fillWithListenerInformation($this);
257 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
260 return $isRegistered;
264 * Accepts the visitor to process the visit "request"
266 * @param $visitorInstance An instance of a Visitor class
269 public function accept (Visitor $visitorInstance) {
271 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
273 // Visit this listener
274 $visitorInstance->visitListener($this);
276 // Visit the pool if set
277 if ($this->getPoolInstance() instanceof Poolable) {
278 $this->getPoolInstance()->accept($visitorInstance);
282 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
286 * Monitors incoming raw data from the handler and transfers it to the
287 * given receiver instance. This method should not be called, please call
288 * the decorator's version instead to separator node/client traffic.
291 * @throws UnsupportedOperatorException If this method is called by a mistake
293 public function monitorIncomingRawData () {
294 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
298 * Constructs a callable method name from given socket error code. If the
299 * method is not found, a generic one is used.
301 * @param $errorCode Error code from socket_last_error()
302 * @return $handlerName Call-back method name for the error handler
303 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
305 protected function getSocketErrorHandlerFromCode ($errorCode) {
306 // Create a name from translated error code
307 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
309 // Is the call-back method there?
310 if (!method_exists($this, $handlerName)) {
311 // Please implement this
312 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
320 * Translates socket error codes into our own internal names which can be
321 * used for call-backs.
323 * @param $errorCode The error code from socket_last_error() to be translated
324 * @return $errorName The translated name (all lower-case, with underlines)
326 public function translateSocketErrorCodeToName ($errorCode) {
327 // Nothing bad happened by default
328 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
330 // Is the code a number, then we have to change it
331 switch ($errorCode) {
332 case 0: // Silently ignored, the socket is connected
335 case 11: // "Resource temporary unavailable"
336 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
339 case 13: // "Permission denied"
340 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
343 case 32: // "Broken pipe"
344 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
347 case 104: // "Connection reset by peer"
348 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
351 case 107: // "Transport end-point not connected"
352 case 134: // On some (?) systems for 'transport end-point not connected'
353 // @TODO On some systems it is 134, on some 107?
354 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
357 case 110: // "Connection timed out"
358 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
361 case 111: // "Connection refused"
362 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
365 case 113: // "No route to host"
366 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
369 case 114: // "Operation already in progress"
370 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
373 case 115: // "Operation now in progress"
374 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
377 default: // Everything else <> 0
378 // Unhandled error code detected, so first debug it because we may want to handle it like the others
379 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
381 // Change it only in this class
382 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
386 // Return translated name
391 * Shuts down a given socket resource. This method does only ease calling
394 * @param $socketResource A valid socket resource
397 public function shutdownSocket ($socketResource) {
399 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
401 // Set socket resource
402 $this->setSocketResource($socketResource);
404 // Get a visitor instance
405 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
408 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
411 $this->accept($visitorInstance);
415 * Half-shuts down a given socket resource. This method does only ease calling
416 * an other visitor than shutdownSocket() does.
418 * @param $socketResource A valid socket resource
421 public function halfShutdownSocket ($socketResource) {
423 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
425 // Set socket resource
426 $this->setSocketResource($socketResource);
428 // Get a visitor instance
429 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
432 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
435 $this->accept($visitorInstance);
438 // ************************************************************************
439 // Socket error handler call-back methods
440 // ************************************************************************
443 * Handles socket error 'permission denied', but does not clear it for
444 * later debugging purposes.
446 * @param $socketResource A valid socket resource
447 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
449 * @throws SocketBindingException The socket could not be bind to
451 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
452 // Get socket error code for verification
453 $socketError = socket_last_error($socketResource);
456 $errorMessage = socket_strerror($socketError);
458 // Shutdown this socket
459 $this->shutdownSocket($socketResource);
462 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
466 * "Listens" for incoming network packages
468 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
470 * @throws InvalidSocketException If an invalid socket resource has been found
472 protected function doListenSocketSelect ($peerSuffix) {
473 // Check on all instances
474 assert($this->getPoolInstance() instanceof Poolable);
475 assert(is_resource($this->getSocketResource()));
478 $readers = $this->getPoolInstance()->getAllSingleSockets();
482 // Check if we have some peers left
483 $left = socket_select(
491 // Some new peers found?
494 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
501 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
503 // Do we have changed peers?
504 if (in_array($this->getSocketResource(), $readers)) {
506 * Then accept it, if this socket is set to non-blocking IO and the
507 * connection is NOT sending any data, socket_read() may throw
508 * error 11 (Resource temporary unavailable). This really nasty
509 * because if you have blocking IO socket_read() will wait and wait
512 $newSocket = socket_accept($this->getSocketResource());
515 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
517 // Array for timeout settings
520 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
522 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
525 // Set timeout to configured seconds
526 // @TODO Does this work on Windozer boxes???
527 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
528 // Handle this socket error with a faked recipientData array
529 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
532 // Output result (only for debugging!)
534 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
535 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
538 // Enable SO_OOBINLINE
539 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
540 // Handle this socket error with a faked recipientData array
541 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
545 if (!socket_set_nonblock($newSocket)) {
546 // Handle this socket error with a faked recipientData array
547 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
550 // Add it to the peers
551 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
554 if (!socket_getpeername($newSocket, $peerName)) {
555 // Handle this socket error with a faked recipientData array
556 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
560 $nodeInstance = NodeObjectFactory::createNodeInstance();
562 // Create a faked package data array
563 $packageData = array(
564 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
565 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
566 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
569 // Get a connection info instance
570 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
572 // Will the info instance with listener data
573 $infoInstance->fillWithListenerInformation($this);
575 // Get a socket registry
576 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
578 // Register the socket with the registry and with the faked array
579 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
582 // Do we have to rewind?
583 if (!$this->getIteratorInstance()->valid()) {
585 $this->getIteratorInstance()->rewind();
588 // Get the current value
589 $currentSocket = $this->getIteratorInstance()->current();
591 // Handle it here, if not main server socket
592 //* 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());
593 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
594 // ... or else it will raise warnings like 'Transport endpoint is not connected'
595 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
598 // Advance to next entry. This should be the last line.
599 $this->getIteratorInstance()->next();