3 namespace CoreFramework\Listener;
5 // Import framework stuff
6 use CoreFramework\Factory\ObjectFactory;
7 use CoreFramework\Object\BaseFrameworkSystem;
8 use CoreFramework\Visitor\Visitor;
11 * A general listener class
13 * @author Roland Haeder <webmaster@shipsimu.org>
15 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
16 * @license GNU GPL 3.0 or any newer version
17 * @link http://www.shipsimu.org
19 * This program is free software: you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation, either version 3 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 class BaseListener extends BaseFrameworkSystem implements Visitable {
33 // Exception code constants
34 const EXCEPTION_INVALID_SOCKET = 0xa00;
35 const EXCEPTION_SOCKET_ALREADY_REGISTERED = 0xa01;
36 const EXCEPTION_SOCKET_CREATION_FAILED = 0xa02;
37 const EXCEPTION_NO_SOCKET_ERROR = 0xa03;
38 const EXCEPTION_CONNECTION_ALREADY_REGISTERED = 0xa04;
39 const EXCEPTION_UNEXPECTED_PACKAGE_STATUS = 0xa05;
40 const EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER = 0xa06;
41 const EXCEPTION_FINAL_CHUNK_VERIFICATION = 0xa07;
42 const EXCEPTION_INVALID_DATA_CHECKSUM = 0xa08;
45 * Address (IP mostly) we shall listen on
47 private $listenAddress = '0.0.0.0'; // This is the default and listens on all interfaces
50 * Port we shall listen on (or wait for incoming data)
52 private $listenPort = 0; // This port MUST be changed by your application
55 * Whether we are in blocking or non-blocking mode (default: non-blocking
57 private $blockingMode = FALSE;
60 * A peer pool instance
62 private $poolInstance = NULL;
65 * Protected constructor
67 * @param $className Name of the class
70 protected function __construct ($className) {
71 // Call parent constructor
72 parent::__construct($className);
76 * Checks whether the given socket resource is a server socket
78 * @param $socketResource A valid socket resource
79 * @return $isServerSocket Whether the socket resource is a server socket
81 protected function isServerSocketResource ($socketResource) {
83 $isServerSocket = ((is_resource($socketResource)) && (!@socket_getpeername($socketResource, $peerName)));
85 // We need to clear the error here if it is a resource
86 if ($isServerSocket === TRUE) {
88 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('socketResource[]=' . gettype($socketResource));
89 socket_clear_error($socketResource);
92 // Check peer name, it must be empty
93 $isServerSocket = (($isServerSocket) && (empty($peerName)));
96 return $isServerSocket;
100 * Setter for listen address
102 * @param $listenAddress The address this listener should listen on
105 protected final function setListenAddress ($listenAddress) {
106 $this->listenAddress = (string) $listenAddress;
110 * Getter for listen address
112 * @return $listenAddress The address this listener should listen on
114 public final function getListenAddress () {
115 return $this->listenAddress;
119 * Setter for listen port
121 * @param $listenPort The port this listener should listen on
124 protected final function setListenPort ($listenPort) {
125 $this->listenPort = (int) $listenPort;
129 * Getter for listen port
131 * @return $listenPort The port this listener should listen on
133 public final function getListenPort () {
134 return $this->listenPort;
138 * "Setter" to set listen address from configuration entry
140 * @param $configEntry The configuration entry holding our listen address
143 public final function setListenAddressByConfiguration ($configEntry) {
144 $this->setListenAddress($this->getConfigInstance()->getConfigEntry($configEntry));
148 * "Setter" to set listen port from configuration entry
150 * @param $configEntry The configuration entry holding our listen port
153 public final function setListenPortByConfiguration ($configEntry) {
154 $this->setListenPort($this->getConfigInstance()->getConfigEntry($configEntry));
158 * Setter for blocking-mode
160 * @param $blockingMode Whether blocking-mode is disabled (default) or enabled
163 protected final function setBlockingMode ($blockingMode) {
164 $this->blockingMode = (boolean) $blockingMode;
168 * Checks whether blocking-mode is enabled or disabled
170 * @return $blockingMode Whether blocking mode is disabled or enabled
172 public final function isBlockingModeEnabled () {
173 return $this->blockingMode;
177 * Setter for peer pool instance
179 * @param $poolInstance The peer pool instance we shall set
182 protected final function setPoolInstance (PoolablePeer $poolInstance) {
183 $this->poolInstance = $poolInstance;
187 * Getter for peer pool instance
189 * @return $poolInstance The peer pool instance we shall set
191 public final function getPoolInstance () {
192 return $this->poolInstance;
196 * Getter for connection type
198 * @return $connectionType Connection type for this listener
200 public final function getConnectionType () {
201 // Wrap the real getter
202 return $this->getProtocolName();
206 * Registeres the given socket resource for "this" listener instance. This
207 * will be done in a seperate class to allow package writers to use it
210 * @param $socketResource A valid server socket resource
212 * @throws InvalidServerSocketException If the given resource is no server socket
213 * @throws SocketAlreadyRegisteredException If the given resource is already registered
215 protected function registerServerSocketResource ($socketResource) {
216 // First check if it is valid
217 if (!$this->isServerSocketResource($socketResource)) {
219 throw new InvalidServerSocketException(array($this, $socketResource), self::EXCEPTION_INVALID_SOCKET);
220 } elseif ($this->isServerSocketRegistered($socketResource)) {
221 // Already registered
222 throw new SocketAlreadyRegisteredException($this, self::EXCEPTION_SOCKET_ALREADY_REGISTERED);
225 // Get a socket registry instance (singleton)
226 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
228 // Get a connection info instance
229 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
231 // Will the info instance with listener data
232 $infoInstance->fillWithListenerInformation($this);
234 // Register the socket
235 $registryInstance->registerSocket($infoInstance, $socketResource);
238 $this->setSocketResource($socketResource);
242 * Checks whether given socket resource is registered in socket registry
244 * @param $socketResource A valid server socket resource
245 * @return $isRegistered Whether given server socket is registered
247 protected function isServerSocketRegistered ($socketResource) {
248 // Get a socket registry instance (singleton)
249 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
251 // Get a connection info instance
252 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
254 // Will the info instance with listener data
255 $infoInstance->fillWithListenerInformation($this);
258 $isRegistered = $registryInstance->isSocketRegistered($infoInstance, $socketResource);
261 return $isRegistered;
265 * Accepts the visitor to process the visit "request"
267 * @param $visitorInstance An instance of a Visitor class
270 public function accept (Visitor $visitorInstance) {
272 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - CALLED!');
274 // Visit this listener
275 $visitorInstance->visitListener($this);
277 // Visit the pool if set
278 if ($this->getPoolInstance() instanceof Poolable) {
279 $this->getPoolInstance()->accept($visitorInstance);
283 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(strtoupper($this->getProtocolName()) . '-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited ' . $this->__toString() . ' - EXIT!');
287 * Monitors incoming raw data from the handler and transfers it to the
288 * given receiver instance. This method should not be called, please call
289 * the decorator's version instead to separator node/client traffic.
292 * @throws UnsupportedOperatorException If this method is called by a mistake
294 public function monitorIncomingRawData () {
295 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
299 * Constructs a callable method name from given socket error code. If the
300 * method is not found, a generic one is used.
302 * @param $errorCode Error code from socket_last_error()
303 * @return $handlerName Call-back method name for the error handler
304 * @throws UnsupportedSocketErrorHandlerException If the error handler is not implemented
306 protected function getSocketErrorHandlerFromCode ($errorCode) {
307 // Create a name from translated error code
308 $handlerName = 'socketError' . self::convertToClassName($this->translateSocketErrorCodeToName($errorCode)) . 'Handler';
310 // Is the call-back method there?
311 if (!method_exists($this, $handlerName)) {
312 // Please implement this
313 throw new UnsupportedSocketErrorHandlerException(array($this, $handlerName, $errorCode), BaseConnectionHelper::EXCEPTION_UNSUPPORTED_ERROR_HANDLER);
321 * Translates socket error codes into our own internal names which can be
322 * used for call-backs.
324 * @param $errorCode The error code from socket_last_error() to be translated
325 * @return $errorName The translated name (all lower-case, with underlines)
327 public function translateSocketErrorCodeToName ($errorCode) {
328 // Nothing bad happened by default
329 $errorName = BaseRawDataHandler::SOCKET_CONNECTED;
331 // Is the code a number, then we have to change it
332 switch ($errorCode) {
333 case 0: // Silently ignored, the socket is connected
336 case 11: // "Resource temporary unavailable"
337 $errorName = BaseRawDataHandler::SOCKET_ERROR_RESOURCE_UNAVAILABLE;
340 case 13: // "Permission denied"
341 $errorName = BaseRawDataHandler::SOCKET_ERROR_PERMISSION_DENIED;
344 case 32: // "Broken pipe"
345 $errorName = BaseRawDataHandler::SOCKET_ERROR_BROKEN_PIPE;
348 case 104: // "Connection reset by peer"
349 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_RESET_BY_PEER;
352 case 107: // "Transport end-point not connected"
353 case 134: // On some (?) systems for 'transport end-point not connected'
354 // @TODO On some systems it is 134, on some 107?
355 $errorName = BaseRawDataHandler::SOCKET_ERROR_TRANSPORT_ENDPOINT;
358 case 110: // "Connection timed out"
359 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_TIMED_OUT;
362 case 111: // "Connection refused"
363 $errorName = BaseRawDataHandler::SOCKET_ERROR_CONNECTION_REFUSED;
366 case 113: // "No route to host"
367 $errorName = BaseRawDataHandler::SOCKET_ERROR_NO_ROUTE_TO_HOST;
370 case 114: // "Operation already in progress"
371 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_ALREADY_PROGRESS;
374 case 115: // "Operation now in progress"
375 $errorName = BaseRawDataHandler::SOCKET_ERROR_OPERATION_IN_PROGRESS;
378 default: // Everything else <> 0
379 // Unhandled error code detected, so first debug it because we may want to handle it like the others
380 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-HUB[' . __METHOD__ . ':' . __LINE__ . '] UNKNOWN ERROR CODE = ' . $errorCode . ', MESSAGE = ' . socket_strerror($errorCode));
382 // Change it only in this class
383 $errorName = BaseRawDataHandler::SOCKET_ERROR_UNKNOWN;
387 // Return translated name
392 * Shuts down a given socket resource. This method does only ease calling
395 * @param $socketResource A valid socket resource
398 public function shutdownSocket ($socketResource) {
400 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
402 // Set socket resource
403 $this->setSocketResource($socketResource);
405 // Get a visitor instance
406 $visitorInstance = ObjectFactory::createObjectByConfiguredName('shutdown_socket_visitor_class');
409 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
412 $this->accept($visitorInstance);
416 * Half-shuts down a given socket resource. This method does only ease calling
417 * an other visitor than shutdownSocket() does.
419 * @param $socketResource A valid socket resource
422 public function halfShutdownSocket ($socketResource) {
424 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM: Half-shutting down socket resource ' . $socketResource . ' with state ' . $this->getPrintableState() . ' ...');
426 // Set socket resource
427 $this->setSocketResource($socketResource);
429 // Get a visitor instance
430 $visitorInstance = ObjectFactory::createObjectByConfiguredName('half_shutdown_socket_visitor_class');
433 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('HUB-SYSTEM:' . $this->__toString() . ': visitorInstance=' . $visitorInstance->__toString());
436 $this->accept($visitorInstance);
439 // ************************************************************************
440 // Socket error handler call-back methods
441 // ************************************************************************
444 * Handles socket error 'permission denied', but does not clear it for
445 * later debugging purposes.
447 * @param $socketResource A valid socket resource
448 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
450 * @throws SocketBindingException The socket could not be bind to
452 protected function socketErrorPermissionDeniedHandler ($socketResource, array $socketData) {
453 // Get socket error code for verification
454 $socketError = socket_last_error($socketResource);
457 $errorMessage = socket_strerror($socketError);
459 // Shutdown this socket
460 $this->shutdownSocket($socketResource);
463 throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
467 * "Listens" for incoming network packages
469 * @param $peerSuffix Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
471 * @throws InvalidSocketException If an invalid socket resource has been found
473 protected function doListenSocketSelect ($peerSuffix) {
474 // Check on all instances
475 assert($this->getPoolInstance() instanceof Poolable);
476 assert(is_resource($this->getSocketResource()));
479 $readers = $this->getPoolInstance()->getAllSingleSockets();
483 // Check if we have some peers left
484 $left = socket_select(
492 // Some new peers found?
495 //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
502 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
504 // Do we have changed peers?
505 if (in_array($this->getSocketResource(), $readers)) {
507 * Then accept it, if this socket is set to non-blocking IO and the
508 * connection is NOT sending any data, socket_read() may throw
509 * error 11 (Resource temporary unavailable). This really nasty
510 * because if you have blocking IO socket_read() will wait and wait
513 $newSocket = socket_accept($this->getSocketResource());
516 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
518 // Array for timeout settings
521 'sec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
523 'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
526 // Set timeout to configured seconds
527 // @TODO Does this work on Windozer boxes???
528 if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
529 // Handle this socket error with a faked recipientData array
530 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
533 // Output result (only for debugging!)
535 $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
536 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
539 // Enable SO_OOBINLINE
540 if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
541 // Handle this socket error with a faked recipientData array
542 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
546 if (!socket_set_nonblock($newSocket)) {
547 // Handle this socket error with a faked recipientData array
548 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
551 // Add it to the peers
552 $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
555 if (!socket_getpeername($newSocket, $peerName)) {
556 // Handle this socket error with a faked recipientData array
557 $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
561 $nodeInstance = NodeObjectFactory::createNodeInstance();
563 // Create a faked package data array
564 $packageData = array(
565 NetworkPackage::PACKAGE_DATA_SENDER => $peerName . $peerSuffix,
566 NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
567 NetworkPackage::PACKAGE_DATA_STATUS => NetworkPackage::PACKAGE_STATUS_FAKED
570 // Get a connection info instance
571 $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
573 // Will the info instance with listener data
574 $infoInstance->fillWithListenerInformation($this);
576 // Get a socket registry
577 $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
579 // Register the socket with the registry and with the faked array
580 $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
583 // Do we have to rewind?
584 if (!$this->getIteratorInstance()->valid()) {
586 $this->getIteratorInstance()->rewind();
589 // Get the current value
590 $currentSocket = $this->getIteratorInstance()->current();
592 // Handle it here, if not main server socket
593 //* 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());
594 if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
595 // ... or else it will raise warnings like 'Transport endpoint is not connected'
596 $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
599 // Advance to next entry. This should be the last line.
600 $this->getIteratorInstance()->next();