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\Visitor;
12 * A general listener class
14 * @author Roland Haeder <webmaster@shipsimu.org>
16 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
17 * @license GNU GPL 3.0 or any newer version
18 * @link http://www.shipsimu.org
20 * This program is free software: you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation, either version 3 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <http://www.gnu.org/licenses/>.
33 class BaseListener extends BaseFrameworkSystem implements Visitable {
34 // Exception code constants
35 const EXCEPTION_INVALID_SOCKET = 0xa00;
36 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
37 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
38 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
39 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
40 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
41 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
42 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
43 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
46 * Address (IP mostly) we shall listen on
48 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
51 * Port we shall listen on (or wait for incoming data)
53 private $listenPort = 0; // This port MUST be changed by your application
56 * Whether we are in blocking or non-blocking mode (default: non-blocking
58 private $blockingMode = FALSE;
61 * A peer pool instance
63 private $poolInstance = NULL;
66 * Protected constructor
68 * @param $className Name of the class
71 protected function __construct ($className) {
72 // Call parent constructor
73 parent::__construct($className);
77 * Checks whether the given socket resource is a server socket
79 * @param $socketResource A valid socket resource
80 * @return $isServerSocket Whether the socket resource is a server socket
82 protected function isServerSocketResource ($socketResource) {
84 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
86 // We need to clear the error here if it is a resource
87 if ($isServerSocket === TRUE) {
89 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('socketResource[]=' . gettype($socketResource));
90 socket_clear_error($socketResource);
93 // Check peer name, it must be empty
94 $isServerSocket = (($isServerSocket) && (empty($peerName)));
97 return $isServerSocket;
101 * Setter for listen address
103 * @param $listenAddress The address this listener should listen on
106 protected final function setListenAddress ($listenAddress) {
107 $this->listenAddress = (string) $listenAddress;
111 * Getter for listen address
113 * @return $listenAddress The address this listener should listen on
115 public final function getListenAddress () {
116 return $this->listenAddress;
120 * Setter for listen port
122 * @param $listenPort The port this listener should listen on
125 protected final function setListenPort ($listenPort) {
126 $this->listenPort = (int) $listenPort;
130 * Getter for listen port
132 * @return $listenPort The port this listener should listen on
134 public final function getListenPort () {
135 return $this->listenPort;
139 * "Setter" to set listen address from configuration entry
141 * @param $configEntry The configuration entry holding our listen address
144 public final function setListenAddressByConfiguration ($configEntry) {
145 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
149 * "Setter" to set listen port from configuration entry
151 * @param $configEntry The configuration entry holding our listen port
154 public final function setListenPortByConfiguration ($configEntry) {
155 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
159 * Setter for blocking-mode
161 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
164 protected final function setBlockingMode ($blockingMode) {
165 $this->blockingMode = (boolean) $blockingMode;
169 * Checks whether blocking-mode is enabled or disabled
171 * @return $blockingMode Whether blocking mode is disabled or enabled
173 public final function isBlockingModeEnabled () {
174 return $this->blockingMode;
178 * Setter for peer pool instance
180 * @param $poolInstance The peer pool instance we shall set
183 protected final function setPoolInstance (PoolablePeer $poolInstance) {
184 $this->poolInstance = $poolInstance;
188 * Getter for peer pool instance
190 * @return $poolInstance The peer pool instance we shall set
192 public final function getPoolInstance () {
193 return $this->poolInstance;
197 * Getter for connection type
199 * @return $connectionType Connection type for this listener
201 public final function getConnectionType () {
202 // Wrap the real getter
203 return $this->getProtocolName();
207 * Registeres the given socket resource for "this" listener instance. This
208 * will be done in a seperate class to allow package writers to use it
211 * @param $socketResource A valid server socket resource
213 * @throws InvalidServerSocketException If the given resource is no server socket
214 * @throws SocketAlreadyRegisteredException If the given resource is already registered
216 protected function registerServerSocketResource ($socketResource) {
217 // First check if it is valid
218 if (!$this->isServerSocketResource($socketResource)) {
220 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
221 } elseif ($this->isServerSocketRegistered($socketResource)) {
222 // Already registered
223 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
226 // Get a socket registry instance (singleton)
227 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
229 // Get a connection info instance
230 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
232 // Will the info instance with listener data
233 $infoInstance->fillWithListenerInformation($this);
235 // Register the socket
236 $registryInstance->registerSocket($infoInstance, $socketResource);
239 $this->setSocketResource($socketResource);
243 * Checks whether given socket resource is registered in socket registry
245 * @param $socketResource A valid server socket resource
246 * @return $isRegistered Whether given server socket is registered
248 protected function isServerSocketRegistered ($socketResource) {
249 // Get a socket registry instance (singleton)
250 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
252 // Get a connection info instance
253 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
255 // Will the info instance with listener data
256 $infoInstance->fillWithListenerInformation($this);
259 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
262 return $isRegistered;
266 * Accepts the visitor to process the visit "request"
268 * @param $visitorInstance An instance of a Visitor class
271 public function accept (Visitor $visitorInstance) {
273 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
275 // Visit this listener
276 $visitorInstance->visitListener($this);
278 // Visit the pool if set
279 if ($this->getPoolInstance() instanceof Poolable) {
280 $this->getPoolInstance()->accept($visitorInstance);
284 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
288 * Monitors incoming raw data from the handler and transfers it to the
289 * given receiver instance. This method should not be called, please call
290 * the decorator's version instead to separator node/client traffic.
293 * @throws UnsupportedOperatorException If this method is called by a mistake
295 public function monitorIncomingRawData () {
296 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
300 * Constructs a callable method name from given socket error code. If the
301 * method is not found, a generic one is used.
303 * @param $errorCode Error code from socket_last_error()
304 * @return $handlerName Call-back method name for the error handler
305 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
307 protected function getSocketErrorHandlerFromCode ($errorCode) {
308 // Create a name from translated error code
309 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
311 // Is the call-back method there?
312 if (!method_exists($this, $handlerName)) {
313 // Please implement this
314 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
322 * Translates socket error codes into our own internal names which can be
323 * used for call-backs.
325 * @param $errorCode The error code from socket_last_error() to be translated
326 * @return $errorName The translated name (all lower-case, with underlines)
328 public function translateSocketErrorCodeToName ($errorCode) {
329 // Nothing bad happened by default
330 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
332 // Is the code a number, then we have to change it
333 switch ($errorCode) {
334 case 0: // Silently ignored, the socket is connected
337 case 11: // "Resource temporary unavailable"
338 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
341 case 13: // "Permission denied"
342 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
345 case 32: // "Broken pipe"
346 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
349 case 104: // "Connection reset by peer"
350 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
353 case 107: // "Transport end-point not connected"
354 case 134: // On some (?) systems for 'transport end-point not connected'
355 // @TODO On some systems it is 134, on some 107?
356 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
359 case 110: // "Connection timed out"
360 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
363 case 111: // "Connection refused"
364 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
367 case 113: // "No route to host"
368 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
371 case 114: // "Operation already in progress"
372 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
375 case 115: // "Operation now in progress"
376 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
379 default: // Everything else <> 0
380 // Unhandled error code detected, so first debug it because we may want to handle it like the others
381 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
383 // Change it only in this class
384 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
388 // Return translated name
393 * Shuts down a given socket resource. This method does only ease calling
396 * @param $socketResource A valid socket resource
399 public function shutdownSocket ($socketResource) {
401 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
403 // Set socket resource
404 $this->setSocketResource($socketResource);
406 // Get a visitor instance
407 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
410 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
413 $this->accept($visitorInstance);
417 * Half-shuts down a given socket resource. This method does only ease calling
418 * an other visitor than shutdownSocket() does.
420 * @param $socketResource A valid socket resource
423 public function halfShutdownSocket ($socketResource) {
425 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
427 // Set socket resource
428 $this->setSocketResource($socketResource);
430 // Get a visitor instance
431 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
434 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
437 $this->accept($visitorInstance);
440 // ************************************************************************
441 // Socket error handler call-back methods
442 // ************************************************************************
445 * Handles socket error 'permission denied', but does not clear it for
446 * later debugging purposes.
448 * @param $socketResource A valid socket resource
449 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
451 * @throws SocketBindingException The socket could not be bind to
453 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
454 // Get socket error code for verification
455 $socketError = socket_last_error($socketResource);
458 $errorMessage = socket_strerror($socketError);
460 // Shutdown this socket
461 $this->shutdownSocket($socketResource);
464 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
468 * "Listens" for incoming network packages
470 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
472 * @throws InvalidSocketException If an invalid socket resource has been found
474 protected function doListenSocketSelect ($peerSuffix) {
475 // Check on all instances
476 assert($this->getPoolInstance() instanceof Poolable);
477 assert(is_resource($this->getSocketResource()));
480 $readers = $this->getPoolInstance()->getAllSingleSockets();
484 // Check if we have some peers left
485 $left = socket_select(
493 // Some new peers found?
496 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
503 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
505 // Do we have changed peers?
506 if (in_array($this->getSocketResource(), $readers)) {
508 * Then accept it, if this socket is set to non-blocking IO and the
509 * connection is NOT sending any data, socket_read() may throw
510 * error 11 (Resource temporary unavailable). This really nasty
511 * because if you have blocking IO socket_read() will wait and wait
514 $newSocket = socket_accept($this->getSocketResource());
517 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
519 // Array for timeout settings
522 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
524 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
527 // Set timeout to configured seconds
528 // @TODO Does this work on Windozer boxes???
529 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
530 // Handle this socket error with a faked recipientData array
531 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
534 // Output result (only for debugging!)
536 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
537 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
540 // Enable SO_OOBINLINE
541 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
542 // Handle this socket error with a faked recipientData array
543 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
547 if (!socket_set_nonblock($newSocket)) {
548 // Handle this socket error with a faked recipientData array
549 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
552 // Add it to the peers
553 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
556 if (!socket_getpeername($newSocket, $peerName)) {
557 // Handle this socket error with a faked recipientData array
558 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
562 $nodeInstance = NodeObjectFactory::createNodeInstance();
564 // Create a faked package data array
565 $packageData = array(
566 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
567 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
568 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
571 // Get a connection info instance
572 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
574 // Will the info instance with listener data
575 $infoInstance->fillWithListenerInformation($this);
577 // Get a socket registry
578 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
580 // Register the socket with the registry and with the faked array
581 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
584 // Do we have to rewind?
585 if (!$this->getIteratorInstance()->valid()) {
587 $this->getIteratorInstance()->rewind();
590 // Get the current value
591 $currentSocket = $this->getIteratorInstance()->current();
593 // Handle it here, if not main server socket
594 //* 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());
595 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
596 // ... or else it will raise warnings like 'Transport endpoint is not connected'
597 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
600 // Advance to next entry. This should be the last line.
601 $this->getIteratorInstance()->next();