]> git.mxchange.org Git - hub.git/blobdiff - application/hub/main/helper/connection/class_BaseConnectionHelper.php
Continued on development of 'hub' project with many refactorings/addings:
[hub.git] / application / hub / main / helper / connection / class_BaseConnectionHelper.php
index 5a2d92443ff57a945d136057cc1a8c2b746d3df5..27ced2e4224bea69087ff3a90d53af7b89159c1f 100644 (file)
@@ -22,6 +22,9 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 class BaseConnectionHelper extends BaseHubHelper implements Registerable, ProtocolHandler {
+       // Exception codes
+       const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
+
        /**
         * Protocol used
         */
@@ -47,6 +50,11 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         */
        private $diff = 0;
 
+       /**
+        * Whether this connection is initialized
+        */
+       private $isInitialized = false;
+
        /**
         * Wether this connection is shutted down
         */
@@ -72,9 +80,6 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                // Call parent constructor
                parent::__construct($className);
 
-               // Register this connection helper
-               Registry::getRegistry()->addInstance('connection', $this);
-
                // Initialize output stream
                $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_output_stream_class');
 
@@ -83,14 +88,17 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
 
                // Init state which sets the state to 'init'
                $this->initState();
+
+               // Register this connection helper
+               Registry::getRegistry()->addInstance('connection', $this);
        }
 
        /**
-        * Getter for real class name
+        * Getter for real class name, overwrites generic method and is final
         *
         * @return      $class  Name of this class
         */
-       public function __toString () {
+       public final function __toString () {
                // Class name representation
                $class = self::getConnectionClassName($this->getAddress(), $this->getPort(), parent::__toString());
 
@@ -98,6 +106,147 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                return $class;
        }
 
+       /**
+        * Getter for port number to satify ProtocolHandler
+        *
+        * @return      $port   The port number
+        */
+       public final function getPort () {
+               return $this->port;
+       }
+
+       /**
+        * Setter for port number to satify ProtocolHandler
+        *
+        * @param       $port   The port number
+        * @return      void
+        */
+       protected final function setPort ($port) {
+               $this->port = $port;
+       }
+
+       /**
+        * Getter for protocol
+        *
+        * @return      $protocol       Used protocol
+        */
+       public final function getProtocol () {
+               return $this->protocol;
+       }
+
+       /**
+        * Setter for protocol
+        *
+        * @param       $protocol       Used protocol
+        * @return      void
+        */
+       protected final function setProtocol ($protocol) {
+               $this->protocol = $protocol;
+       }
+
+       /**
+        * Getter for IP address
+        *
+        * @return      $address        The IP address
+        */
+       public final function getAddress () {
+               return $this->address;
+       }
+
+       /**
+        * Setter for IP address
+        *
+        * @param       $address        The IP address
+        * @return      void
+        */
+       protected final function setAddress ($address) {
+               $this->address = $address;
+       }
+
+       /**
+        * Initializes the current connection
+        *
+        * @return      void
+        * @throws      SocketOptionException   If setting any socket option fails
+        */
+       protected function initConnection () {
+               // Get socket resource
+               $socketResource = $this->getSocketResource();
+
+               // Set the option to reuse the port
+               if (!socket_set_option($socketResource, SOL_SOCKET, SO_REUSEADDR, 1)) {
+                       // Handle this socket error with a faked recipientData array
+                       $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
+
+                       // And throw again
+                       // @TODO Move this to the socket error handler
+                       throw new SocketOptionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+               } // END - if
+
+               /*
+                * Set socket to non-blocking mode before trying to establish a link to
+                * it. This is now the default behaviour for all connection helpers who
+                * call initConnection(); .
+                */
+               if (!socket_set_nonblock($socketResource)) {
+                       // Handle this socket error with a faked recipientData array
+                       $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
+
+                       // And throw again
+                       throw new SocketOptionException(array($helperInstance, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+               } // END - if
+
+               // Last step: mark connection as initialized
+               $this->isInitialized = true;
+       }
+
+       /**
+        * Attempts to connect to a peer by given IP number and port from a valid
+        * recipientData array with currently configured timeout.
+        *
+        * @param       $recipientData  A valid recipient data array, 0=IP; 1=PORT
+        * @return      $isConnected    Wether the connection went fine
+        * @see         Please see http://de.php.net/manual/en/function.socket-connect.php#84465 for original code
+        * @todo        Rewrite the while() loop to a iterator to not let the software stay very long here
+        */
+       protected function connectToPeerByRecipientDataArray (array $recipientData) {
+               // Only call this if the connection is initialized by initConnection()
+               assert($this->isInitialized === true);
+
+               // Get current time
+               $time = time();
+
+               // "Cache" socket resource and timeout config
+               $socketResource = $this->getSocketResource();
+               $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
+
+               // Try to connect until it is connected
+               while ($isConnected = !@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
+                       // Get last socket error
+                       $socketError = socket_last_error($socketResource);
+
+                       // Skip any errors which may happen on non-blocking connections
+                       if (($socketError == SOCKET_EINPROGRESS) || ($socketError == SOCKET_EALREADY)) {
+                               // Now, is that attempt within parameters?
+                               if ((time() - $time) >= $timeout) {
+                                       // Didn't work within timeout
+                                       $isConnected = false;
+                                       break;
+                               } // END - if
+
+                               // Sleep about one second
+                               $this->idle(1000);
+                       } elseif ($socketError != 0) {
+                               // Stop on everything else pronto
+                               $isConnected = false;
+                               break;
+                       }
+               } // END - while
+
+               // Return status
+               return $isConnected;
+       }
+
        /**
         * Static "getter" for this connection class' name
         *
@@ -176,63 +325,6 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                }
        }
 
-       /**
-        * Getter for port number to satify ProtocolHandler
-        *
-        * @return      $port   The port number
-        */
-       public final function getPort () {
-               return $this->port;
-       }
-
-       /**
-        * Setter for port number to satify ProtocolHandler
-        *
-        * @param       $port   The port number
-        * @return      void
-        */
-       protected final function setPort ($port) {
-               $this->port = $port;
-       }
-
-       /**
-        * Getter for protocol
-        *
-        * @return      $protocol       Used protocol
-        */
-       public final function getProtocol () {
-               return $this->protocol;
-       }
-
-       /**
-        * Setter for protocol
-        *
-        * @param       $protocol       Used protocol
-        * @return      void
-        */
-       protected final function setProtocol ($protocol) {
-               $this->protocol = $protocol;
-       }
-
-       /**
-        * Getter for IP address
-        *
-        * @return      $address        The IP address
-        */
-       public final function getAddress () {
-               return $this->address;
-       }
-
-       /**
-        * Setter for IP address
-        *
-        * @param       $address        The IP address
-        * @return      void
-        */
-       protected final function setAddress ($address) {
-               $this->address = $address;
-       }
-
        /**
         * "Accept" a visitor by simply calling it back
         *
@@ -271,7 +363,7 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                        $rawData .= $dataStream;
                } // END - while
 
-               // Nothing to sent is bad news!
+               // Nothing to sent is bad news, so assert on it
                assert(strlen($rawData) > 0);
 
                // Encode the raw data with our output-stream
@@ -294,24 +386,18 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
 
                        // If there was an error, we don't continue here
                        if ($sentBytes === false) {
-                               // Get socket error code for verification
-                               $socketError = socket_last_error($socketResource);
-
-                               // Get error message
-                               $errorMessage = socket_strerror($socketError);
-
-                               // Shutdown this socket
-                               $this->shutdownSocket($socketResource);
+                               // Handle the error with a faked recipientData array
+                               $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
 
                                // And throw it
-                               throw new InvalidSocketException(array($this, gettype($socketResource), $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+                               throw new InvalidSocketException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
                        } elseif (($sentBytes == 0) && (strlen($encodedData) > 0)) {
                                // Nothing sent means we are done
                                //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
                                break;
                        }
 
-                       // The difference between sent bytes and length of raw data should not be below zero
+                       // The difference between sent bytes and length of raw data should not go below zero
                        assert((strlen($encodedData) - $sentBytes) >= 0);
 
                        // Add total sent bytes
@@ -345,6 +431,9 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
        protected final function markConnectionShuttedDown () {
                /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
                $this->shuttedDown = true;
+
+               // And remove the (now invalid) socket
+               $this->setSocketResource(false);
        }
 
        /**
@@ -356,6 +445,132 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
                return $this->shuttedDown;
        }
+
+       // ************************************************************************
+       //                 Socket error handler call-back methods
+       // ************************************************************************
+
+       /**
+        * Handles socket error 'connection timed out', but does not clear it for
+        * later debugging purposes.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
+        */
+       protected function socketErrorConnectionTimedOutHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+       }
+
+       /**
+        * Handles socket error 'resource temporary unavailable', but does not
+        * clear it for later debugging purposes.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
+        */
+       protected function socketErrorResourceUnavailableHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+       }
+
+       /**
+        * Handles socket error 'connection refused', but does not clear it for
+        * later debugging purposes.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
+        */
+       protected function socketErrorConnectionRefusedHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+       }
+
+       /**
+        * Handles socket error 'no route to host', but does not clear it for later
+        * debugging purposes.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
+        */
+       protected function socketErrorNoRouteToHostHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Shutdown this socket
+               $this->shutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+       }
+
+       /**
+        * Handles socket error 'operation already in progress' which happens in
+        * method connectToPeerByRecipientDataArray() on timed out connection
+        * attempts.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        * @throws      SocketConnectionException       The connection attempts fails with a time-out
+        */
+       protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Get error message
+               $errorMessage = socket_strerror($socketError);
+
+               // Half-shutdown this socket (see there for difference to shutdownSocket())
+               $this->halfShutdownSocket($socketResource);
+
+               // Throw it again
+               throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+       }
+
+       /**
+        * Handles socket "error" 'operation now in progress' which can be safely
+        * passed on with non-blocking connections.
+        *
+        * @param       $socketResource         A valid socket resource
+        * @return      void
+        */
+       protected function socketErrorOperationInProgressHandler ($socketResource) {
+               $this->debugOutput('CONNECTION: Operation is now in progress, this is usual for non-blocking connections and no bug.');
+       }
 }
 
 // [EOF]