]> git.mxchange.org Git - hub.git/blobdiff - application/hub/main/tools/class_HubTools.php
Updated 'core'.
[hub.git] / application / hub / main / tools / class_HubTools.php
index 0d8b4f0d9ce5c9e4ed3a56ba274143def0e7d2dd..988fa7a4d2ece5a8f8f40da31fb47e5891aef722 100644 (file)
@@ -2,11 +2,11 @@
 /**
  * This class contains static helper functions for our hub
  *
- * @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 - 2012 Hub Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 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
@@ -50,6 +50,12 @@ class HubTools extends BaseHubSystem {
                // Call parent constructor
                parent::__construct(__CLASS__);
 
+               // Get a DHT instance
+               $dhtInstance = DhtObjectFactory::createDhtInstance('node');
+
+               // Set it here
+               $this->setDhtInstance($dhtInstance);
+
                // Init salt length
                $this->sessionIdLength = 32 + $this->getConfigInstance()->getConfigEntry('salt_length');
        }
@@ -80,113 +86,120 @@ class HubTools extends BaseHubSystem {
        }
 
        /**
-        * Resolves a session id into an ip:port combination
+        * Resolves a session id into an instance of a LocateableNode class. The opposite method
+        * is resolveSessionIdByUniversalNodeLocator()
         *
-        * @param       $sessionId      A valid session id
-        * @param       $protocol       Name of the used protocol: TCP/UDP
-        * @return      $recipient      Recipient as ip:port combination
+        * @param       $sessionId                      A valid session id
+        * @return      $recipientUniversalNodeLocator  Recipient as Universal Node Locator
         */
-       protected function resolveIpPortBySessionId ($sessionId, $protocol) {
-               // Get a wrapper instance
-               $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_list_db_wrapper_class');
-
-               // And ask it for the session id
-               $recipient = $wrapperInstance->resolveIpPortBySessionId($sessionId, $protocol);
-
-               // Is the recipient invalid?
-               if ($recipient == 'invalid:invalid') {
+       protected function resolveUniversalNodeLocatorBySessionId ($sessionId) {
+               // Init variable
+               $recipientUniversalNodeLocator = 'invalid://invalid:invalid';
+
+               // And ask it for Universal Node Locator by given session id
+               $recipient = $this->getDhtInstance()->findNodeLocalBySessionId($sessionId);
+               //* DEBUG-DIE: */ die(__METHOD__ . ': UNFINISHED: recipient[' . gettype($recipient) . ']=' . print_r($recipient, TRUE) . ',sessionId=' . $sessionId . PHP_EOL);
+
+               // Is the recipient valid?
+               if (isset($recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_ADDRESS])) {
+                       // Then use this
+                       $recipientUniversalNodeLocator = $recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_ADDRESS];
+               } else {
                        // Get the instance, this might throw a NPE
-                       $nodeInstance = Registry::getRegistry()->getInstance('node');
+                       $nodeInstance = NodeObjectFactory::createNodeInstance();
 
                        // Is the session id the same?
                        if ($nodeInstance->getSessionId() == $sessionId) {
-                               // Then get the ip:port from it, assume TCP by default
-                               $recipient = self::determineOwnExternalIp() . ':' . $nodeInstance->getConfigInstance()->getConfigEntry('node_' . strtolower($protocol) . '_listen_port');
+                               // Then get an instance of a LocateableNode class from it, assume TCP by default
+                               $recipientUniversalNodeLocator = self::determineOwnExternalAddress() . ':' . $nodeInstance->getConfigInstance()->getConfigEntry('node_listen_port');
                        } // END - if
-               } // END - if
+               }
 
                // Return result
-               return $recipient;
+               return $recipientUniversalNodeLocator;
+       }
+
+       /**
+        * Resolves a session id into a node id by asking local DHT.
+        *
+        * @param       $sessionId      Session id
+        * @return      $nodeId         Node id
+        */
+       public static function resolveNodeIdBySessionId ($sessionId) {
+               // Get an own instance
+               $selfInstance = self::getSelfInstance();
+
+               // And ask it for session id by given Universal Node Locator
+               $nodeData = $selfInstance->getDhtInstance()->findNodeLocalBySessionId($sessionId);
+
+               // Make sure the node id is there
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: sessionId=' . $sessionId . ', nodeData[' . gettype($nodeData) . ']=' . print_r($nodeData, TRUE));
+               assert(isset($nodeData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_NODE_ID]));
+
+               // Return it
+               return $nodeData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_NODE_ID];
        }
 
        /**
-        * Resolves a ip:port combination into a session id
+        * Resolves a Universal Node Locator into a session id. The "opposite" method
+        * is resolveUniversalNodeLocatorBySessionId().
         *
-        * @param       $ipPort         Ip:port combination
-        * @param       $protocol       Name of used protocol (TCP/UDP)
-        * @return      $sessionId      Valid session id
+        * @param       $unlInstance    Universal Node Locator
+        * @return      $sessionId              Valid session id
         */
-       public static function resolveSessionIdByIpPort ($ipPort, $protocol) {
-               // Get a wrapper instance
-               $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_list_db_wrapper_class');
+       public static function resolveSessionIdByUniversalNodeLocator (LocateableNode $unlInstance) {
+               // Get an own instance
+               $selfInstance = self::getSelfInstance();
 
-               // And ask it for the session id
-               $sessionId = $wrapperInstance->resolveSessionIdByIpPort($ipPort, $protocol);
+               // And ask it for session id by given Universal Node Locator
+               $recipient = $selfInstance->getDhtInstance()->findNodeByUniversalNodeLocator($unlInstance);
+               die(__METHOD__.':recipient='.print_r($recipient, TRUE));
 
                // Return result
                return $sessionId;
        }
 
        /**
-        * Resolves given session id into an ip:port combination, if ip:port is set, it won't be translated
+        * Resolves given session id into an instance of a LocateableNode class, if Universal Node Locator is set, it won't be translated
         *
-        * @param       $sessionId      Session id or ip:port combination
-        * @param       $protocol       Name of the used protocol (TCP/UDP)
-        * @return      $recipient      Recipient as ip:port combination
-        * @throws      InvalidSessionIdException       If the provided session id is invalid (and no ip:port combination)
+        * @param       $address        Session id or Universal Node Locator
+        * @return      $recipient      Recipient as Universal Node Locator
+        * @throws      InvalidSessionIdException       If the provided session id is invalid (and no Universal Node Locator)
         * @throws      NoValidHostnameException        If the provided hostname cannot be resolved into an IP address
         */
-       public static function resolveSessionId ($sessionId, $protocol) {
+       public static function resolveSessionId ($address) {
                // Get an own instance
                $selfInstance = self::getSelfInstance();
 
-               // Default is direct ip:port
-               $recipient = $sessionId;
+               // Default is direct Universal Node Locator
+               $recipient = $address;
 
-               // Does it match a direct ip:port? (hint: see www.regexlib.com for the regular expression)
-               if (preg_match('/((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])):([0-9]{3,5})/', $sessionId)) {
-                       // Direct ip:port found
-                       $selfInstance->debugOutput('HUB-TOOLS: Direct ip:port ' . $sessionId . ' detected.');
-               } elseif (isset($selfInstance->sessionIdCache[$sessionId])) {
+               // Does it match a direct Universal Node Locator? (hint: see www.regexlib.com for the regular expression)
+               if (preg_match('/([a-z0-9]{3,10})\/\/:([a-z0-9\.]{5,})/', $address)) {
+                       // @TODO ((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])):([0-9]{3,5})
+                       // Direct Universal Node Locator found
+                       self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Direct Universal Node Locator ' . $address . ' detected.');
+               } elseif (isset($selfInstance->sessionIdCache[$address])) {
                        // Debug message
-                       $selfInstance->debugOutput('HUB-TOOLS: Using entry from sessionIdCache[] array.');
+                       self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Using entry from sessionIdCache[] array.');
 
                        // Found in cache!
-                       $recipient = $selfInstance->sessionIdCache[$sessionId];
-
-                       // Debug message
-                       $selfInstance->debugOutput('HUB-TOOLS: sessionIdCache[' . $sessionId . ']=' . $recipient);
-               } elseif (preg_match('/([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}:([0-9]{3,5})/', $sessionId)) {
-                       // Hostname:port found
-                       $selfInstance->debugOutput('HUB-TOOLS: hostname:port ' . $sessionId . ' detected.');
-
-                       // Hostname:port found
-                       $hostnameArray = explode(':', $sessionId);
-
-                       // Try to resolve it and add port again
-                       // @TODO Please try to encapsulate this PHP call into an own class
-                       $recipient = gethostbyname($hostnameArray[0]) . ':' . $hostnameArray[1];
-
-                       // Is it valid?
-                       if ($recipient == $sessionId) {
-                               // Resolving hostname->IP failed!
-                               throw new NoValidHostnameException($hostnameArray, self::EXCEPTION_HOSTNAME_NOT_FOUND);
-                       } // END - if
+                       $recipient = $selfInstance->sessionIdCache[$address];
 
                        // Debug message
-                       $selfInstance->debugOutput('HUB-TOOLS: hostname:port ' . $sessionId . ' resolved to ' . $recipient);
-               } elseif (preg_match('/([a-f0-9]{' . $selfInstance->getSessionIdLength() . '})/', $sessionId)) {
+                       self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: sessionIdCache[' . $address . ']=' . $recipient);
+               } elseif (preg_match('/([a-f0-9]{' . $selfInstance->getSessionIdLength() . '})/', $address)) {
                        // Debug message
-                       $selfInstance->debugOutput('HUB-TOOLS: Using internal session id resolver.');
+                       self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Using internal session id resolver.');
 
-                       // Resolve session id into a ip:port combination
-                       $recipient = $selfInstance->resolveIpPortBySessionId($sessionId, $protocol);
+                       // Resolve session id into an instance of a LocateableNode class
+                       $recipient = $selfInstance->resolveUniversalNodeLocatorBySessionId($address);
 
                        // Debug message
-                       $selfInstance->debugOutput('HUB-TOOLS: session id ' . $sessionId . ' resolved to ' . $recipient);
+                       self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Session id ' . $address . ' resolved to ' . $recipient);
                } else {
-                       // Invalid session id
-                       throw new InvalidSessionIdException($sessionId, self::EXCEPTION_SESSION_ID_IS_INVALID);
+                       // Invalid session id/UNL
+                       throw new InvalidSessionIdException($address, self::EXCEPTION_SESSION_ID_IS_INVALID);
                }
 
                // Return it
@@ -194,44 +207,115 @@ class HubTools extends BaseHubSystem {
        }
 
        /**
-        * Determine IP or 'external_ip' if set
+        * Determine UNL or 'external_address' if set
         *
-        * @return      $ip             The determined external ip of this node
+        * @return      $unl    The determined external UNL of this node
         */
-       public static function determineOwnExternalIp () {
-               // Is the external_ip config entry set?
-               if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip') != '') {
-                       // Use it as external ip
-                       $ip = FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip');
+       public static function determineOwnExternalAddress () {
+               // Is the external_address config entry set?
+               if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_address') != '') {
+                       // Use it as external address
+                       $unl = FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_address');
                } else {
-                       // Determine own external ip by connecting to my (coder) server at 188.138.90.169
-                       $ip = ConsoleTools::determineExternalIp();
+                       // Determine own external address by connecting to my (coder) server at 188.138.90.169
+                       $unl = self::determineExternalUniversalNodeLocator();
                }
 
                // Return it
-               return $ip;
+               return $unl;
        }
 
        /**
-        * Determine IP or 'internal_ip' if set
+        * Determine UNL or 'internal_address' if set
         *
-        * @return      $ip             The determined external ip of this node
+        * @return      $unl    The determined internal UNL of this node
         */
-       public static function determineOwnInternalIp () {
-               // Is the internal_ip config entry set?
-               if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('allow_publish_internal_ip') == 'N') {
-                       // Not allowed to publish internal IP, so use external
-                       $ip = self::determineOwnExternalIp();
-               } elseif (FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_ip') != '') {
-                       // Use it as internal ip
-                       $ip = FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_ip');
+       public static function determineOwnInternalAddress () {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
+
+               // Is the internal_address config entry set?
+               if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('allow_publish_internal_address') == 'N') {
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Calling self::determineOwnExternalAddress() as allow_publish_internal_address=N is set ...');
+
+                       // Not allowed to publish internal address, so use external
+                       $unl = self::determineOwnExternalAddress();
+               } elseif (FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_address') != '') {
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Getting config entry internal_address ...');
+
+                       // Use it as internal address
+                       $unl = FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_address');
                } else {
-                       // Determine own internal ip by connecting to my (coder) server at 188.138.90.169
-                       $ip = ConsoleTools::acquireSelfIPAddress();
+                       // Debug message
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Calling self::determineInternalUniversalNodeLocator() ...');
+
+                       // Determine own internal address
+                       $unl = self::determineInternalUniversalNodeLocator();
                }
 
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $unl . ' - EXIT!');
+
+               // Return it
+               return $unl;
+       }
+
+       /**
+        * Determines the UNL (Universal Node Locator) for the internal address
+        *
+        * @return      $internalUnl    Internal UNL
+        */
+       public static function determineInternalUniversalNodeLocator () {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
+
+               // Is there cache? (This shortens a lot calls)
+               if (!isset($GLOBALS[__METHOD__])) {
+                       // Determine UNL based on this node:
+                       // 1) Get discovery class
+                       $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
+
+                       // 2) "Determine" it
+                       $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('internal');
+
+                       // Make sure it is valid
+                       // @TODO Find a better validation than empty()
+                       assert(!empty($GLOBALS[__METHOD__]));
+               } // END - if
+
+               // Return it
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
+               return $GLOBALS[__METHOD__];
+       }
+
+       /**
+        * Determines the UNL (Universal Node Locator) for the external address
+        *
+        * @return      $externalUnl    External UNL
+        */
+       public static function determineExternalUniversalNodeLocator () {
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
+
+               // Is there cache? (This shortens a lot calls)
+               if (!isset($GLOBALS[__METHOD__])) {
+                       // Determine UNL based on this node:
+                       // 1) Get discovery class
+                       $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
+
+                       // 2) "Determine" it
+                       $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('external');
+
+                       // Make sure it is valid
+                       // @TODO Find a better validation than empty()
+                       assert(!empty($GLOBALS[__METHOD__]));
+               } // END - if
+
                // Return it
-               return $ip;
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
+               return $GLOBALS[__METHOD__];
        }
 }