]> git.mxchange.org Git - hub.git/blobdiff - application/hub/classes/helper/connection/ipv4/tcp/class_TcpConnectionHelper.php
Updated 'core' + renamed 'main' -> 'classes'.
[hub.git] / application / hub / classes / helper / connection / ipv4 / tcp / class_TcpConnectionHelper.php
diff --git a/application/hub/classes/helper/connection/ipv4/tcp/class_TcpConnectionHelper.php b/application/hub/classes/helper/connection/ipv4/tcp/class_TcpConnectionHelper.php
new file mode 100644 (file)
index 0000000..682c181
--- /dev/null
@@ -0,0 +1,188 @@
+<?php
+/**
+ * A TCP connection helper class
+ *
+ * @author             Roland Haeder <webmaster@shipsimu.org>
+ * @version            0.0.0
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Hub Developer Team
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.shipsimu.org
+ * @todo               Find an interface for hub helper
+ *
+ * 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
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * 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 TcpConnectionHelper extends BaseIpV4ConnectionHelper implements ConnectionHelper {
+       /**
+        * Protected constructor
+        *
+        * @return      void
+        */
+       protected function __construct () {
+               // Call parent constructor
+               parent::__construct(__CLASS__);
+
+               // Set protocol
+               $this->setProtocolName('tcp');
+       }
+
+       /**
+        * Creates a half-connected socket resource ("connection") for given
+        * recipient in package data. After you called this method you still need to
+        * connect to the other node.
+        *
+        * @param       $packageData            Raw package data
+        * @return      $socketResource         Socket resource
+        * @throws      SocketCreationException         If the socket could not be created
+        * @throws      SocketOptionException           If a socket option could not be set
+        * @throws      SocketConnectionException       If a connection could not be opened
+        * @todo        $errorCode/-Message are now in handleSocketError()'s call-back methods
+        */
+       public static function createConnectionFromPackageData (array $packageData) {
+               // Create an instance
+               $helperInstance = new TcpConnectionHelper();
+
+               // Create a socket instance
+               $socketResource = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
+
+               // Is the socket resource valid?
+               if (!is_resource($socketResource)) {
+                       /*
+                        * Something bad happened, calling handleSocketError() is not
+                        * possible here because that method would throw an
+                        * InvalidSocketException back.
+                        */
+                       throw new SocketCreationException(array($helperInstance, gettype($socketResource)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
+               } // END - if
+
+               // Get socket error code for verification
+               $socketError = socket_last_error($socketResource);
+
+               // Check if there was an error else
+               if ($socketError > 0) {
+                       // Handle this socket error with a faked recipientData array
+                       $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
+
+                       // Then throw again
+                       throw new SocketCreationException(array($helperInstance, gettype($socketResource), $socketError, socket_strerror($socketError)), BaseListener::EXCEPTION_SOCKET_CREATION_FAILED);
+               } // END - if
+
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting socket resource ... (' . gettype($socketResource) . ')');
+
+               // Set the resource
+               $helperInstance->setSocketResource($socketResource);
+
+               // Init connection
+               $helperInstance->initConnection();
+
+               // @TODO The whole resolving part should be moved out and made more configurable
+               // Init recipient data
+               $unlData = array();
+
+               // Try to solve the recipient
+               try {
+                       // Get protocol handler back from package data
+                       $handlerInstance = ProtocolHandlerFactory::createProtocolHandlerFromPackageData($packageData);
+
+                       // Get UNL data
+                       $unlData = $handlerInstance->getUniversalNodeLocatorDataArray();
+
+                       // Make sure it is a valid Universal Node Locator array (3 elements)
+                       assert(isset($unlData[UniversalNodeLocator::UNL_PART_PROTOCOL]));
+                       assert(isset($unlData[UniversalNodeLocator::UNL_PART_ADDRESS]));
+                       assert(isset($unlData[UniversalNodeLocator::UNL_PART_PORT]));
+
+                       // Set handler instance
+                       $helperInstance->setHandlerInstance($handlerInstance);
+               } catch (NoValidHostnameException $e) {
+                       // Debug message
+                       self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Failed to resolve ' . $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ':' . $e->getMessage());
+
+                       // Is the recipient equal as configured IP
+                       if (substr($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], 0, strlen($helperInstance->getConfigInstance()->getConfigEntry('external_address'))) == $helperInstance->getConfigInstance()->getConfigEntry('external_address')) {
+                               // This may connect to shipsimu.org and requests 'ip.php' which will return our external IP address
+                               $unlData[UniversalNodeLocator::UNL_PART_ADDRESS] = HubTools::determineExternalAddress();
+
+                               // Do we have ip:port match?
+                               // @TODO Rewrite this test for UNLs
+                               if (strpos($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT], ':') === FALSE) {
+                                       // No ip:port!
+                                       $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . ' does not contain ":". Please fix this.');
+                               } // END - if
+
+                               // "explode" the ip:port, so index 1 will be the port number
+                               // @TODO Rewrite this test for UNLs
+                               $recipientArray = explode(':', $packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT]);
+
+                               // Add the port
+                               $unlData[UniversalNodeLocator::UNL_PART_PORT] = $recipientArray[UniversalNodeLocator::UNL_PART_PORT];
+                       } else {
+                               // It doesn't match, we need to take care of this later
+                               $helperInstance->debugInstance($packageData[NetworkPackage::PACKAGE_DATA_RECIPIENT] . '!=' . $helperInstance->getConfigInstance()->getConfigEntry('external_address'));
+                       }
+               }
+
+               // Set address and maybe port
+               $helperInstance->setAddress($unlData[UniversalNodeLocator::UNL_PART_ADDRESS]);
+               $helperInstance->setConnectionPort($unlData[UniversalNodeLocator::UNL_PART_PORT]);
+
+               // Now connect to it
+               if (!$helperInstance->connectToPeerByUnlData($unlData)) {
+                       // Handle socket error
+                       $helperInstance->handleSocketError(__METHOD__, __LINE__, $socketResource, $unlData);
+               } // END - if
+
+               // Okay, that should be it. Return it...
+               return $socketResource;
+       }
+
+       /**
+        * Do the shutdown sequence for this connection helper
+        *
+        * @return      void
+        * @throws      SocketShutdownException         If the current socket could not be shut down
+        * @todo        We may want to implement a filter for ease notification of other objects like our pool
+        */
+       public function doShutdown () {
+               // Debug message
+               self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Shutting down socket resource ' . $this->getSocketResource());
+
+               // Clear any previous errors
+               socket_clear_error($this->getSocketResource());
+
+               // Call the shutdown function on the currently set socket
+               if (!socket_shutdown($this->getSocketResource())) {
+                       // Could not shutdown socket, this is fine if e.g. the other side is not connected, so analyse it
+                       if (socket_last_error($this->getSocketResource()) != 107) {
+                               // Something bad happened while we shutdown a socket
+                               throw new SocketShutdownException($this, BaseListener::EXCEPTION_INVALID_SOCKET);
+                       } // END - if
+               } // END - if
+
+               // Try to make blocking IO for socket_close()
+               socket_set_block($this->getSocketResource());
+
+               // Drop all data (don't sent any on socket closure)
+               socket_set_option($this->getSocketResource(), SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 0));
+
+               // Finally close socket to free some resources
+               socket_close($this->getSocketResource());
+
+               // Mark this connection as shutted down
+               $this->markConnectionShuttedDown();
+       }
+}
+
+// [EOF]
+?>