added files for database format-upgrade
[core.git] / inc / main / classes / listener / class_BaseListener.php
index bd807bd7f0abcffd9817554ec55608d981969a7e..e22ceea1d155b851c5f51a815afb663554ebde36 100644 (file)
@@ -4,7 +4,7 @@
  *
  * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2016 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.shipsimu.org
  *
@@ -21,7 +21,7 @@
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
-class BaseListener extends BaseFrameworkSystem implements Visitable {
+abstract class BaseListener extends BaseFrameworkSystem implements Visitable {
        // Exception code constants
        const EXCEPTION_INVALID_SOCKET                   = 0xa00;
        const EXCEPTION_SOCKET_ALREADY_REGISTERED        = 0xa01;
@@ -309,51 +309,6 @@ class BaseListener extends BaseFrameworkSystem implements Visitable {
                return $handlerName;
        }
 
-       /**
-        * Handles socket error for given socket resource and peer data. This method
-        * validates $socketResource if it is a valid resource (see is_resource())
-        * but assumes valid data in array $recipientData, except that
-        * count($recipientData) is always 2.
-        *
-        * @param       $method                         Value of __METHOD__ from calling method
-        * @param       $line                           Value of __LINE__ from calling method
-        * @param       $socketResource         A valid socket resource
-        * @param       $socketData                     A valid socket data array (0 = IP/file name, 1 = port)
-        * @return      void
-        * @throws      InvalidSocketException  If $socketResource is no socket resource
-        * @throws      NoSocketErrorDetectedException  If socket_last_error() gives zero back
-        */
-       protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
-               // This method handles only socket resources
-               if (!is_resource($socketResource)) {
-                       // No resource, abort here
-                       throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
-               } // END - if
-
-               // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
-               //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
-               assert(isset($socketData[0]));
-               assert(isset($socketData[1]));
-
-               // Get error code for first validation (0 is not an error)
-               $errorCode = socket_last_error($socketResource);
-
-               // If the error code is zero, someone called this method without an error
-               if ($errorCode == 0) {
-                       // No error detected (or previously cleared outside this method)
-                       throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
-               } // END - if
-
-               // Get handler (method) name
-               $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
-
-               // Call-back the error handler method
-               call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
-
-               // Finally clear the error because it has been handled
-               socket_clear_error($socketResource);
-       }
-
        /**
         * Translates socket error codes into our own internal names which can be
         * used for call-backs.
@@ -499,7 +454,142 @@ class BaseListener extends BaseFrameworkSystem implements Visitable {
                // Throw it again
                throw new SocketBindingException(array($this, $socketData, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
        }
-}
 
-// [EOF]
-?>
+       /**
+        * "Listens" for incoming network packages
+        *
+        * @param       $peerSuffix             Suffix for peer name (e.g. :0 for TCP(/UDP?) connections)
+        * @return      void
+        * @throws      InvalidSocketException  If an invalid socket resource has been found
+        */
+       protected function doListenSocketSelect ($peerSuffix) {
+               // Check on all instances
+               assert($this->getPoolInstance() instanceof Poolable);
+               assert(is_resource($this->getSocketResource()));
+
+               // Get all readers
+               $readers = $this->getPoolInstance()->getAllSingleSockets();
+               $writers = array();
+               $excepts = array();
+
+               // Check if we have some peers left
+               $left = socket_select(
+                       $readers,
+                       $writers,
+                       $excepts,
+                       0,
+                       150
+               );
+
+               // Some new peers found?
+               if ($left < 1) {
+                       // Debug message
+                       //* EXTREME-NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: left=' . $left . ',serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
+
+                       // Nothing new found
+                       return;
+               } // END - if
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: serverSocket=' . $this->getSocketResource() . ',readers=' . print_r($readers, TRUE));
+
+               // Do we have changed peers?
+               if (in_array($this->getSocketResource(), $readers)) {
+                       /*
+                        * Then accept it, if this socket is set to non-blocking IO and the
+                        * connection is NOT sending any data, socket_read() may throw
+                        * error 11 (Resource temporary unavailable). This really nasty
+                        * because if you have blocking IO socket_read() will wait and wait
+                        * and wait ...
+                        */
+                       $newSocket = socket_accept($this->getSocketResource());
+
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: newSocket=' . $newSocket . ',serverSocket=' .$this->getSocketResource());
+
+                       // Array for timeout settings
+                       $options  = array(
+                               // Seconds
+                               'sec'  => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_sec'),
+                               // Milliseconds
+                               'usec' => $this->getConfigInstance()->getConfigEntry('tcp_socket_accept_wait_usec')
+                       );
+
+                       // Set timeout to configured seconds
+                       // @TODO Does this work on Windozer boxes???
+                       if (!socket_set_option($newSocket, SOL_SOCKET, SO_RCVTIMEO, $options)) {
+                               // Handle this socket error with a faked recipientData array
+                               $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
+                       } // END - if
+
+                       // Output result (only for debugging!)
+                       /*
+                       $option = socket_get_option($newSocket, SOL_SOCKET, SO_RCVTIMEO);
+                       self::createDebugInstance(__CLASS__)->debugOutput('SO_RCVTIMEO[' . gettype($option) . ']=' . print_r($option, TRUE));
+                       */
+
+                       // Enable SO_OOBINLINE
+                       if (!socket_set_option($newSocket, SOL_SOCKET, SO_OOBINLINE ,1)) {
+                               // Handle this socket error with a faked recipientData array
+                               $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
+                       } // END - if
+
+                       // Set non-blocking
+                       if (!socket_set_nonblock($newSocket)) {
+                               // Handle this socket error with a faked recipientData array
+                               $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
+                       } // END - if
+
+                       // Add it to the peers
+                       $this->getPoolInstance()->addPeer($newSocket, BaseConnectionHelper::CONNECTION_TYPE_INCOMING);
+
+                       // Get peer name
+                       if (!socket_getpeername($newSocket, $peerName)) {
+                               // Handle this socket error with a faked recipientData array
+                               $this->handleSocketError(__METHOD__, __LINE__, $newSocket, array('0.0.0.0', '0'));
+                       } // END - if
+
+                       // Get node instance
+                       $nodeInstance = NodeObjectFactory::createNodeInstance();
+
+                       // Create a faked package data array
+                       $packageData = array(
+                               NetworkPackage::PACKAGE_DATA_SENDER    => $peerName . $peerSuffix,
+                               NetworkPackage::PACKAGE_DATA_RECIPIENT => $nodeInstance->getSessionId(),
+                               NetworkPackage::PACKAGE_DATA_STATUS    => NetworkPackage::PACKAGE_STATUS_FAKED
+                       );
+
+                       // Get a connection info instance
+                       $infoInstance = ConnectionInfoFactory::createConnectionInfoInstance($this->getProtocolName(), 'listener');
+
+                       // Will the info instance with listener data
+                       $infoInstance->fillWithListenerInformation($this);
+
+                       // Get a socket registry
+                       $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
+
+                       // Register the socket with the registry and with the faked array
+                       $registryInstance->registerSocket($infoInstance, $newSocket, $packageData);
+               } // END - if
+
+               // Do we have to rewind?
+               if (!$this->getIteratorInstance()->valid()) {
+                       // Rewind the list
+                       $this->getIteratorInstance()->rewind();
+               } // END - if
+
+               // Get the current value
+               $currentSocket = $this->getIteratorInstance()->current();
+
+               // Handle it here, if not main server socket
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('TCP-LISTENER[' . __METHOD__ . ':' . __LINE__ . ']: currentSocket=' . $currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] . ',type=' . $currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] . ',serverSocket=' . $this->getSocketResource());
+               if (($currentSocket[BasePool::SOCKET_ARRAY_CONN_TYPE] != BaseConnectionHelper::CONNECTION_TYPE_SERVER) && ($currentSocket[BasePool::SOCKET_ARRAY_RESOURCE] != $this->getSocketResource())) {
+                       // ... or else it will raise warnings like 'Transport endpoint is not connected'
+                       $this->getHandlerInstance()->processRawDataFromResource($currentSocket);
+               } // END - if
+
+               // Advance to next entry. This should be the last line.
+               $this->getIteratorInstance()->next();
+       }
+
+}