]> git.mxchange.org Git - hub.git/blobdiff - application/hub/main/helper/connection/class_BaseConnectionHelper.php
The final hash must be used as an array key for serial numbers, else some packages...
[hub.git] / application / hub / main / helper / connection / class_BaseConnectionHelper.php
index a98242238a796dd2e60f41d36d58498e726fc047..5391983364c8047f12f80e58a9dc6fd27f2eaa33 100644 (file)
@@ -2,11 +2,11 @@
 /**
  * A general ConnectionHelper class
  *
- * @author             Roland Haeder <webmaster@ship-simu.org>
+ * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
  * @license            GNU GPL 3.0 or any newer version
- * @link               http://www.ship-simu.org
+ * @link               http://www.shipsimu.org
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * 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 BaseConnectionHelper extends BaseHubHelper implements Registerable, ProtocolHandler {
+class BaseConnectionHelper extends BaseHubSystemHelper implements Registerable, ProtocolHandler {
        // Exception codes
-       const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x900;
+       const EXCEPTION_UNSUPPORTED_ERROR_HANDLER = 0x9100;
+
+       /**
+        * Connection type 'incoming'
+        */
+       const CONNECTION_TYPE_INCOMING = 'incoming';
+
+       /**
+        * Connection type 'outgoing'
+        */
+       const CONNECTION_TYPE_OUTGOING = 'outgoing';
+
+       /**
+        * Connection type 'server'
+        */
+       const CONNECTION_TYPE_SERVER   = 'server';
 
        /**
         * Protocol used
@@ -53,12 +68,12 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
        /**
         * Whether this connection is initialized
         */
-       private $isInitialized = false;
+       private $isInitialized = FALSE;
 
        /**
-        * Wether this connection is shutted down
+        * Whether this connection is shutted down
         */
-       private $shuttedDown = false;
+       private $shuttedDown = FALSE;
 
        /**
         * Currently queued chunks
@@ -91,6 +106,12 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
 
                // Register this connection helper
                Registry::getRegistry()->addInstance('connection', $this);
+
+               // Get the fragmenter instance
+               $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
+
+               // Set it here
+               $this->setFragmenterInstance($fragmenterInstance);
        }
 
        /**
@@ -176,7 +197,7 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                // 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'));
+                       $this->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
 
                        // And throw again
                        // @TODO Move this to the socket error handler
@@ -190,14 +211,14 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                 */
                if (!socket_set_nonblock($socketResource)) {
                        // Handle this socket error with a faked recipientData array
-                       $helperInstance->handleSocketError($socketResource, array('0.0.0.0', '0'));
+                       $helperInstance->handleSocketError(__METHOD__, __LINE__, $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;
+               $this->isInitialized = TRUE;
        }
 
        /**
@@ -205,13 +226,13 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * recipientData array with currently configured timeout.
         *
         * @param       $recipientData  A valid recipient data array, 0=IP; 1=PORT
-        * @return      $isConnected    Wether the connection went fine
+        * @return      $isConnected    Whether 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) {
+       protected function connectToPeerByRecipientData (array $recipientData) {
                // Only call this if the connection is initialized by initConnection()
-               assert($this->isInitialized === true);
+               assert($this->isInitialized === TRUE);
 
                // Get current time
                $time = time();
@@ -220,6 +241,9 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                $socketResource = $this->getSocketResource();
                $timeout = $this->getConfigInstance()->getConfigEntry('socket_timeout_seconds');
 
+               // Debug output
+               self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Trying to connect to ' . $recipientData[0] . ':' . $recipientData[1] . ' with socketResource[' . gettype($socketResource) . ']=' . $socketResource . ' ...');
+
                // Try to connect until it is connected
                while ($isConnected = !@socket_connect($socketResource, $recipientData[0], $recipientData[1])) {
                        // Get last socket error
@@ -230,7 +254,7 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                                // Now, is that attempt within parameters?
                                if ((time() - $time) >= $timeout) {
                                        // Didn't work within timeout
-                                       $isConnected = false;
+                                       $isConnected = FALSE;
                                        break;
                                } // END - if
 
@@ -238,11 +262,23 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                                $this->idle(1000);
                        } elseif ($socketError != 0) {
                                // Stop on everything else pronto
-                               $isConnected = false;
+                               $isConnected = FALSE;
                                break;
                        }
                } // END - while
 
+               // Is the peer connected?
+               if ($isConnected === TRUE) {
+                       // Connection is fully established here, so change the state.
+                       PeerStateFactory::createPeerStateInstanceByName('connected', $this);
+               } else {
+                       /*
+                        * There was a problem connecting to the peer (this state is a meta
+                        * state until the error handler has found the real cause).
+                        */
+                       PeerStateFactory::createPeerStateInstanceByName('problem', $this);
+               }
+
                // Return status
                return $isConnected;
        }
@@ -292,35 +328,35 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * @return      $chunkData              Raw data chunk
         */
        private function getRawDataFromPackageArray (array $packageData) {
-               // Get the fragmenter instance
-               $fragmenterInstance = FragmenterFactory::createFragmenterInstance('package');
-
-               // Implode the package data array and fragement the resulting string, returns the final hash
-               $finalHash = $fragmenterInstance->fragmentPackageArray($packageData, $this);
-               if ($finalHash !== true) {
-                       $this->currentFinalHash = $finalHash;
-               } // END - if
-
                // Debug message
-               //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: currentFinalHash=' . $this->currentFinalHash);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: currentFinalHash=' . $this->currentFinalHash);
+
+               // Make sure the final hash is set
+               assert((is_string($this->currentFinalHash)) && (!empty($this->currentFinalHash)));
 
                // Get the next raw data chunk from the fragmenter
-               $rawDataChunk = $fragmenterInstance->getNextRawDataChunk($this->currentFinalHash);
+               $rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash);
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: rawDataChunk=' . print_r($rawDataChunk, TRUE));
 
                // Get chunk hashes and chunk data
                $chunkHashes = array_keys($rawDataChunk);
                $chunkData   = array_values($rawDataChunk);
 
                // Is the required data there?
-               //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData));
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: chunkHashes[]=' . count($chunkHashes) . ',chunkData[]=' . count($chunkData));
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('chunkData='.print_r($chunkData, TRUE));
                if ((isset($chunkHashes[0])) && (isset($chunkData[0]))) {
                        // Remember this chunk as queued
                        $this->queuedChunks[$chunkHashes[0]] = $chunkData[0];
 
                        // Return the raw data
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Returning ' . strlen($chunkData[0]) . ' bytes from ' . __METHOD__ . ' ...');
                        return $chunkData[0];
                } else {
                        // Return zero string
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Returning zero bytes from ' . __METHOD__ . '!');
                        return '';
                }
        }
@@ -347,6 +383,19 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                // The helper's state must be 'connected'
                $this->getStateInstance()->validatePeerStateConnected();
 
+               // Implode the package data array and fragement the resulting string, returns the final hash
+               $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageData, $this);
+               if ($finalHash !== TRUE) {
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting finalHash=' . $finalHash . ',currentFinalHash[' . gettype($this->currentFinalHash) . ']=' . $this->currentFinalHash);
+
+                       // Set final hash
+                       $this->currentFinalHash = $finalHash;
+               } // END - if
+
+               // Reset serial number
+               $this->getFragmenterInstance()->resetSerialNumber($this->currentFinalHash);
+
                // Cache buffer length
                $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
 
@@ -356,10 +405,13 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                $totalSentBytes = 0;
 
                // Fill sending buffer with data
-               while ((strlen($rawData) < $bufferSize) && (strlen($dataStream) > 0)) {
+               while (strlen($dataStream) > 0) {
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: packageData=' . print_r($packageData, TRUE));
+
                        // Convert the package data array to a raw data stream
                        $dataStream = $this->getRawDataFromPackageArray($packageData);
-                       //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...');
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Adding ' . strlen($dataStream) . ' bytes to the sending buffer ...');
                        $rawData .= $dataStream;
                } // END - while
 
@@ -369,6 +421,9 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                // Encode the raw data with our output-stream
                $encodedData = $this->getOutputStreamInstance()->streamData($rawData);
 
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: rawData()=' . strlen($rawData) . ',encodedData()=' . strlen($encodedData));
+
                // Calculate difference
                $this->diff = $bufferSize - strlen($encodedData);
 
@@ -379,21 +434,30 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                $sentBytes = 0;
 
                // Deliver all data
-               while ($sentBytes !== false) {
+               while ($sentBytes !== FALSE) {
                        // And deliver it
-                       //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sending out ' . strlen($encodedData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
-                       $sentBytes = @socket_write($socketResource, $encodedData, ($bufferSize - $this->diff));
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sending out ' . strlen($encodedData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
+
+                       if ($this->diff >= 0) {
+                               // Send all out (encodedData is smaller than or equal buffer size)
+                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedData, 0, ($bufferSize - $this->diff))));
+                               $sentBytes = socket_write($socketResource, $encodedData, ($bufferSize - $this->diff));
+                       } else {
+                               // Send buffer size out
+                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedData, 0, $bufferSize)));
+                               $sentBytes = socket_write($socketResource, $encodedData, $bufferSize);
+                       }
 
                        // If there was an error, we don't continue here
-                       if ($sentBytes === false) {
+                       if ($sentBytes === FALSE) {
                                // Handle the error with a faked recipientData array
-                               $this->handleSocketError($socketResource, array('0.0.0.0', '0'));
+                               $this->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
 
                                // And throw it
                                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__ . ')');
+                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
                                break;
                        }
 
@@ -404,7 +468,7 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                        $totalSentBytes += $sentBytes;
 
                        // Cut out the last unsent bytes
-                       //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: Sent out ' . $sentBytes . ' of ' . strlen($encodedData) . ' bytes ...');
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedData) . ' bytes ...');
                        $encodedData = substr($encodedData, $sentBytes);
 
                        // Calculate difference again
@@ -413,13 +477,13 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
                        // Can we abort?
                        if (strlen($encodedData) <= 0) {
                                // Abort here, all sent!
-                               //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: All sent! (' . __LINE__ . ')');
+                               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
                                break;
                        } // END - if
                } // END - while
 
                // Return sent bytes
-               //* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: totalSentBytes=' . $totalSentBytes);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: totalSentBytes=' . $totalSentBytes . ',diff=' . $this->diff);
                return $totalSentBytes;
        }
 
@@ -429,20 +493,20 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * @return      void
         */
        protected final function markConnectionShuttedDown () {
-               /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ' has been marked as shutted down');
-               $this->shuttedDown = true;
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $this->__toString() . ' has been marked as shutted down');
+               $this->shuttedDown = TRUE;
 
                // And remove the (now invalid) socket
-               $this->setSocketResource(false);
+               $this->setSocketResource(FALSE);
        }
 
        /**
         * Getter for shuttedDown
         *
-        * @return      $shuttedDown    Wether this connection is shutted down
+        * @return      $shuttedDown    Whether this connection is shutted down
         */
        public final function isShuttedDown () {
-               /* NOISY-DEBUG: */ $this->debugOutput('CONNECTION: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: ' . $this->__toString() . ',shuttedDown=' . intval($this->shuttedDown));
                return $this->shuttedDown;
        }
 
@@ -455,10 +519,11 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * later debugging purposes.
         *
         * @param       $socketResource         A valid socket resource
+        * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
         * @return      void
         * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       protected function socketErrorConnectionTimedOutHandler ($socketResource) {
+       protected function socketErrorConnectionTimedOutHandler ($socketResource, array $recipientData) {
                // Get socket error code for verification
                $socketError = socket_last_error($socketResource);
 
@@ -477,10 +542,11 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * clear it for later debugging purposes.
         *
         * @param       $socketResource         A valid socket resource
+        * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
         * @return      void
         * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       protected function socketErrorResourceUnavailableHandler ($socketResource) {
+       protected function socketErrorResourceUnavailableHandler ($socketResource, array $recipientData) {
                // Get socket error code for verification
                $socketError = socket_last_error($socketResource);
 
@@ -499,10 +565,11 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * later debugging purposes.
         *
         * @param       $socketResource         A valid socket resource
+        * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
         * @return      void
         * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       protected function socketErrorConnectionRefusedHandler ($socketResource) {
+       protected function socketErrorConnectionRefusedHandler ($socketResource, array $recipientData) {
                // Get socket error code for verification
                $socketError = socket_last_error($socketResource);
 
@@ -521,10 +588,11 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * debugging purposes.
         *
         * @param       $socketResource         A valid socket resource
+        * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
         * @return      void
         * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       protected function socketErrorNoRouteToHostHandler ($socketResource) {
+       protected function socketErrorNoRouteToHostHandler ($socketResource, array $recipientData) {
                // Get socket error code for verification
                $socketError = socket_last_error($socketResource);
 
@@ -540,14 +608,15 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
 
        /**
         * Handles socket error 'operation already in progress' which happens in
-        * method connectToPeerByRecipientDataArray() on timed out connection
+        * method connectToPeerByRecipientData() on timed out connection
         * attempts.
         *
         * @param       $socketResource         A valid socket resource
+        * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
         * @return      void
         * @throws      SocketConnectionException       The connection attempts fails with a time-out
         */
-       protected function socketErrorOperationAlreadyProgressHandler ($socketResource) {
+       protected function socketErrorOperationAlreadyProgressHandler ($socketResource, array $recipientData) {
                // Get socket error code for verification
                $socketError = socket_last_error($socketResource);
 
@@ -566,10 +635,11 @@ class BaseConnectionHelper extends BaseHubHelper implements Registerable, Protoc
         * passed on with non-blocking connections.
         *
         * @param       $socketResource         A valid socket resource
+        * @param       $recipientData          An array with two elements: 0=IP number, 1=port number
         * @return      void
         */
-       protected function socketErrorOperationInProgressHandler ($socketResource) {
-               $this->debugOutput('CONNECTION: Operation is now in progress, this is usual for non-blocking connections and is no bug.');
+       protected function socketErrorOperationInProgressHandler ($socketResource, array $recipientData) {
+               self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Operation is now in progress, this is usual for non-blocking connections and is no bug.');
        }
 }