3 namespace CoreFramework\Listener;
5 // Import framework stuff
6 use CoreFramework\Factory\Connection\ConnectionInfoFactory;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Factory\Registry\Socket\SocketRegistryFactory;
9 use CoreFramework\Generic\UnsupportedOperationException;
10 use CoreFramework\Object\BaseFrameworkSystem;
11 use CoreFramework\Pool\Poolable;
12 use CoreFramework\Visitor\Visitable;
13 use CoreFramework\Visitor\Visitor;
16 * A general listener class
18 * @author Roland Haeder <webmaster@shipsimu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.shipsimu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 class BaseListener extends BaseFrameworkSystem implements Visitable {
38 // Exception code constants
39 const EXCEPTION_INVALID_SOCKET = 0xa00;
40 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
41 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
42 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
43 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
44 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
45 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
46 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
47 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
50 * Address (IP mostly) we shall listen on
52 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
55 * Port we shall listen on (or wait for incoming data)
57 private $listenPort = 0; // This port MUST be changed by your application
60 * Whether we are in blocking or non-blocking mode (default: non-blocking
62 private $blockingMode = false;
65 * A peer pool instance
67 private $poolInstance = NULL;
70 * Protected constructor
72 * @param $className Name of the class
75 protected function __construct ($className) {
76 // Call parent constructor
77 parent::__construct($className);
81 * Checks whether the given socket resource is a server socket
83 * @param $socketResource A valid socket resource
84 * @return $isServerSocket Whether the socket resource is a server socket
86 protected function isServerSocketResource ($socketResource) {
88 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
90 // We need to clear the error here if it is a resource
91 if ($isServerSocket === true) {
93 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('socketResource[]=' . gettype($socketResource));
94 socket_clear_error($socketResource);
97 // Check peer name, it must be empty
98 $isServerSocket = (($isServerSocket) && (empty($peerName)));
101 return $isServerSocket;
105 * Setter for listen address
107 * @param $listenAddress The address this listener should listen on
110 protected final function setListenAddress ($listenAddress) {
111 $this->listenAddress = (string) $listenAddress;
115 * Getter for listen address
117 * @return $listenAddress The address this listener should listen on
119 public final function getListenAddress () {
120 return $this->listenAddress;
124 * Setter for listen port
126 * @param $listenPort The port this listener should listen on
129 protected final function setListenPort ($listenPort) {
130 $this->listenPort = (int) $listenPort;
134 * Getter for listen port
136 * @return $listenPort The port this listener should listen on
138 public final function getListenPort () {
139 return $this->listenPort;
143 * "Setter" to set listen address from configuration entry
145 * @param $configEntry The configuration entry holding our listen address
148 public final function setListenAddressByConfiguration ($configEntry) {
149 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
153 * "Setter" to set listen port from configuration entry
155 * @param $configEntry The configuration entry holding our listen port
158 public final function setListenPortByConfiguration ($configEntry) {
159 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
163 * Setter for blocking-mode
165 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
168 protected final function setBlockingMode ($blockingMode) {
169 $this->blockingMode = (boolean) $blockingMode;
173 * Checks whether blocking-mode is enabled or disabled
175 * @return $blockingMode Whether blocking mode is disabled or enabled
177 public final function isBlockingModeEnabled () {
178 return $this->blockingMode;
182 * Setter for peer pool instance
184 * @param $poolInstance The peer pool instance we shall set
187 protected final function setPoolInstance (PoolablePeer $poolInstance) {
188 $this->poolInstance = $poolInstance;
192 * Getter for peer pool instance
194 * @return $poolInstance The peer pool instance we shall set
196 public final function getPoolInstance () {
197 return $this->poolInstance;
201 * Getter for connection type
203 * @return $connectionType Connection type for this listener
205 public final function getConnectionType () {
206 // Wrap the real getter
207 return $this->getProtocolName();
211 * Registeres the given socket resource for "this" listener instance. This
212 * will be done in a seperate class to allow package writers to use it
215 * @param $socketResource A valid server socket resource
217 * @throws InvalidServerSocketException If the given resource is no server socket
218 * @throws SocketAlreadyRegisteredException If the given resource is already registered
220 protected function registerServerSocketResource ($socketResource) {
221 // First check if it is valid
222 if (!$this->isServerSocketResource($socketResource)) {
224 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
225 } elseif ($this->isServerSocketRegistered($socketResource)) {
226 // Already registered
227 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
230 // Get a socket registry instance (singleton)
231 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
233 // Get a connection info instance
234 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
236 // Will the info instance with listener data
237 $infoInstance->fillWithListenerInformation($this);
239 // Register the socket
240 $registryInstance->registerSocket($infoInstance, $socketResource);
243 $this->setSocketResource($socketResource);
247 * Checks whether given socket resource is registered in socket registry
249 * @param $socketResource A valid server socket resource
250 * @return $isRegistered Whether given server socket is registered
252 protected function isServerSocketRegistered ($socketResource) {
253 // Get a socket registry instance (singleton)
254 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
256 // Get a connection info instance
257 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
259 // Will the info instance with listener data
260 $infoInstance->fillWithListenerInformation($this);
263 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
266 return $isRegistered;
270 * Accepts the visitor to process the visit "request"
272 * @param $visitorInstance An instance of a Visitor class
275 public function accept (Visitor $visitorInstance) {
277 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
279 // Visit this listener
280 $visitorInstance->visitListener($this);
282 // Visit the pool if set
283 if ($this->getPoolInstance() instanceof Poolable) {
284 $this->getPoolInstance()->accept($visitorInstance);
288 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
292 * Monitors incoming raw data from the handler and transfers it to the
293 * given receiver instance. This method should not be called, please call
294 * the decorator's version instead to separator node/client traffic.
297 * @throws UnsupportedOperatorException If this method is called by a mistake
299 public function monitorIncomingRawData () {
300 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
304 * Constructs a callable method name from given socket error code. If the
305 * method is not found, a generic one is used.
307 * @param $errorCode Error code from socket_last_error()
308 * @return $handlerName Call-back method name for the error handler
309 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
311 protected function getSocketErrorHandlerFromCode ($errorCode) {
312 // Create a name from translated error code
313 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
315 // Is the call-back method there?
316 if (!method_exists($this, $handlerName)) {
317 // Please implement this
318 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
326 * Translates socket error codes into our own internal names which can be
327 * used for call-backs.
329 * @param $errorCode The error code from socket_last_error() to be translated
330 * @return $errorName The translated name (all lower-case, with underlines)
332 public function translateSocketErrorCodeToName ($errorCode) {
333 // Nothing bad happened by default
334 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
336 // Is the code a number, then we have to change it
337 switch ($errorCode) {
338 case 0: // Silently ignored, the socket is connected
341 case 11: // "Resource temporary unavailable"
342 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
345 case 13: // "Permission denied"
346 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
349 case 32: // "Broken pipe"
350 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
353 case 104: // "Connection reset by peer"
354 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
357 case 107: // "Transport end-point not connected"
358 case 134: // On some (?) systems for 'transport end-point not connected'
359 // @TODO On some systems it is 134, on some 107?
360 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
363 case 110: // "Connection timed out"
364 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
367 case 111: // "Connection refused"
368 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
371 case 113: // "No route to host"
372 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
375 case 114: // "Operation already in progress"
376 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
379 case 115: // "Operation now in progress"
380 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
383 default: // Everything else <> 0
384 // Unhandled error code detected, so first debug it because we may want to handle it like the others
385 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
387 // Change it only in this class
388 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
392 // Return translated name
397 * Shuts down a given socket resource. This method does only ease calling
400 * @param $socketResource A valid socket resource
403 public function shutdownSocket ($socketResource) {
405 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
407 // Set socket resource
408 $this->setSocketResource($socketResource);
410 // Get a visitor instance
411 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
414 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
417 $this->accept($visitorInstance);
421 * Half-shuts down a given socket resource. This method does only ease calling
422 * an other visitor than shutdownSocket() does.
424 * @param $socketResource A valid socket resource
427 public function halfShutdownSocket ($socketResource) {
429 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
431 // Set socket resource
432 $this->setSocketResource($socketResource);
434 // Get a visitor instance
435 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
438 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
441 $this->accept($visitorInstance);
444 // ************************************************************************
445 // Socket error handler call-back methods
446 // ************************************************************************
449 * Handles socket error 'permission denied', but does not clear it for
450 * later debugging purposes.
452 * @param $socketResource A valid socket resource
453 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
455 * @throws SocketBindingException The socket could not be bind to
457 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
458 // Get socket error code for verification
459 $socketError = socket_last_error($socketResource);
462 $errorMessage = socket_strerror($socketError);
464 // Shutdown this socket
465 $this->shutdownSocket($socketResource);
468 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
472 * "Listens" for incoming network packages
474 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
476 * @throws InvalidSocketException If an invalid socket resource has been found
478 protected function doListenSocketSelect ($peerSuffix) {
479 // Check on all instances
480 assert($this->getPoolInstance() instanceof Poolable);
481 assert(is_resource($this->getSocketResource()));
484 $readers = $this->getPoolInstance()->getAllSingleSockets();
488 // Check if we have some peers left
489 $left = socket_select(
497 // Some new peers found?
500 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, true));
507 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, true));
509 // Do we have changed peers?
510 if (in_array($this->getSocketResource(), $readers)) {
512 * Then accept it, if this socket is set to non-blocking IO and the
513 * connection is NOT sending any data, socket_read() may throw
514 * error 11 (Resource temporary unavailable). This really nasty
515 * because if you have blocking IO socket_read() will wait and wait
518 $newSocket = socket_accept($this->getSocketResource());
521 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
523 // Array for timeout settings
526 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
528 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
531 // Set timeout to configured seconds
532 // @TODO Does this work on Windozer boxes???
533 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
534 // Handle this socket error with a faked recipientData array
535 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
538 // Output result (only for debugging!)
540 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
541 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, true));
544 // Enable SO_OOBINLINE
545 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
546 // Handle this socket error with a faked recipientData array
547 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
551 if (!socket_set_nonblock($newSocket)) {
552 // Handle this socket error with a faked recipientData array
553 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
556 // Add it to the peers
557 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
560 if (!socket_getpeername($newSocket, $peerName)) {
561 // Handle this socket error with a faked recipientData array
562 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
566 $nodeInstance = NodeObjectFactory::createNodeInstance();
568 // Create a faked package data array
569 $packageData = array(
570 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
571 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
572 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
575 // Get a connection info instance
576 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
578 // Will the info instance with listener data
579 $infoInstance->fillWithListenerInformation($this);
581 // Get a socket registry
582 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
584 // Register the socket with the registry and with the faked array
585 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
588 // Do we have to rewind?
589 if (!$this->getIteratorInstance()->valid()) {
591 $this->getIteratorInstance()->rewind();
594 // Get the current value
595 $currentSocket = $this->getIteratorInstance()->current();
597 // Handle it here, if not main server socket
598 //* 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());
599 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
600 // ... or else it will raise warnings like 'Transport endpoint is not connected'
601 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
604 // Advance to next entry. This should be the last line.
605 $this->getIteratorInstance()->next();