3 * This class contains static helper functions for our hub
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Hub Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class HubTools extends BaseHubSystem {
25 // Constants for exceptions
26 const EXCEPTION_SESSION_ID_IS_INVALID = 0x200;
27 const EXCEPTION_HOSTNAME_NOT_FOUND = 0x201;
30 * Cache for session ids
32 private $sessionIdCache = array();
35 * Length for session id (should be 32+salt_length
37 private $sessionIdLength = 0;
42 private static $selfInstance = NULL;
45 * Protected constructor
49 protected function __construct () {
50 // Call parent constructor
51 parent::__construct(__CLASS__);
54 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
57 $this->setDhtInstance($dhtInstance);
60 $this->sessionIdLength = 32 + $this->getConfigInstance()->getConfigEntry('salt_length');
64 * Singleton getter for self instance
66 * @retuen $selfInstance An instance of this class
68 public static final function getSelfInstance () {
69 // Is the instance set
70 if (is_null(self::$selfInstance)) {
72 self::$selfInstance = new HubTools();
75 // Return own instance
76 return self::$selfInstance;
80 * Getter for session id length
82 * @return $sessionIdLength Length of session ids
84 protected final function getSessionIdLength () {
85 return $this->sessionIdLength;
89 * Resolves a session id into an instance of a LocateableNode class. The opposite method
90 * is resolveSessionIdByUniversalNodeLocator()
92 * @param $sessionId A valid session id
93 * @return $recipientUniversalNodeLocator Recipient as Universal Node Locator
95 protected function resolveUniversalNodeLocatorBySessionId ($sessionId) {
97 $recipientUniversalNodeLocator = 'invalid://invalid:invalid';
99 // And ask it for Universal Node Locator by given session id
100 $recipient = $this->getDhtInstance()->findNodeLocalBySessionId($sessionId);
101 //* DEBUG-DIE: */ die(__METHOD__ . ': UNFINISHED: recipient[' . gettype($recipient) . ']=' . print_r($recipient, TRUE) . ',sessionId=' . $sessionId . PHP_EOL);
103 // Is the recipient valid?
104 if (isset($recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_ADDRESS])) {
106 $recipientUniversalNodeLocator = $recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_ADDRESS];
108 // Get the instance, this might throw a NPE
109 $nodeInstance = NodeObjectFactory::createNodeInstance();
111 // Is the session id the same?
112 if ($nodeInstance->getSessionId() == $sessionId) {
113 // Then get an instance of a LocateableNode class from it, assume TCP by default
114 $recipientUniversalNodeLocator = self::determineOwnExternalAddress() . ':' . $nodeInstance->getConfigInstance()->getConfigEntry('node_listen_port');
119 return $recipientUniversalNodeLocator;
123 * Resolves a session id into a node id by asking local DHT.
125 * @param $sessionId Session id
126 * @return $nodeId Node id
128 public static function resolveNodeIdBySessionId ($sessionId) {
129 // Get an own instance
130 $selfInstance = self::getSelfInstance();
132 // And ask it for session id by given Universal Node Locator
133 $nodeData = $selfInstance->getDhtInstance()->findNodeLocalBySessionId($sessionId);
135 // Make sure the node id is there
136 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: sessionId=' . $sessionId . ', nodeData[' . gettype($nodeData) . ']=' . print_r($nodeData, TRUE));
137 assert(isset($nodeData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_NODE_ID]));
140 return $nodeData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_NODE_ID];
144 * Resolves a Universal Node Locator into a session id. The "opposite" method
145 * is resolveUniversalNodeLocatorBySessionId().
147 * @param $unlInstance Universal Node Locator
148 * @return $sessionId Valid session id
150 public static function resolveSessionIdByUniversalNodeLocator (LocateableNode $unlInstance) {
151 // Get an own instance
152 $selfInstance = self::getSelfInstance();
154 // And ask it for session id by given Universal Node Locator
155 $recipient = $selfInstance->getDhtInstance()->findNodeByUniversalNodeLocator($unlInstance);
156 die(__METHOD__.':recipient='.print_r($recipient, TRUE));
163 * Resolves given session id into an instance of a LocateableNode class, if Universal Node Locator is set, it won't be translated
165 * @param $address Session id or Universal Node Locator
166 * @return $recipient Recipient as Universal Node Locator
167 * @throws InvalidSessionIdException If the provided session id is invalid (and no Universal Node Locator)
168 * @throws NoValidHostnameException If the provided hostname cannot be resolved into an IP address
170 public static function resolveSessionId ($address) {
171 // Get an own instance
172 $selfInstance = self::getSelfInstance();
174 // Default is direct Universal Node Locator
175 $recipient = $address;
177 // Does it match a direct Universal Node Locator? (hint: see www.regexlib.com for the regular expression)
178 if (preg_match('/([a-z0-9]{3,10})\/\/:([a-z0-9\.]{5,})/', $address)) {
179 // @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})
180 // Direct Universal Node Locator found
181 self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Direct Universal Node Locator ' . $address . ' detected.');
182 } elseif (isset($selfInstance->sessionIdCache[$address])) {
184 self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Using entry from sessionIdCache[] array.');
187 $recipient = $selfInstance->sessionIdCache[$address];
190 self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: sessionIdCache[' . $address . ']=' . $recipient);
191 } elseif (preg_match('/([a-f0-9]{' . $selfInstance->getSessionIdLength() . '})/', $address)) {
193 self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Using internal session id resolver.');
195 // Resolve session id into an instance of a LocateableNode class
196 $recipient = $selfInstance->resolveUniversalNodeLocatorBySessionId($address);
199 self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Session id ' . $address . ' resolved to ' . $recipient);
201 // Invalid session id/UNL
202 throw new InvalidSessionIdException($address, self::EXCEPTION_SESSION_ID_IS_INVALID);
210 * Determine UNL or 'external_address' if set
212 * @return $unl The determined external UNL of this node
214 public static function determineOwnExternalAddress () {
215 // Is the external_address config entry set?
216 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_address') != '') {
217 // Use it as external address
218 $unl = FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_address');
220 // Determine own external address by connecting to my (coder) server at 188.138.90.169
221 $unl = self::determineExternalUniversalNodeLocator();
229 * Determine UNL or 'internal_address' if set
231 * @return $unl The determined internal UNL of this node
233 public static function determineOwnInternalAddress () {
235 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
237 // Is the internal_address config entry set?
238 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('allow_publish_internal_address') == 'N') {
240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Calling self::determineOwnExternalAddress() as allow_publish_internal_address=N is set ...');
242 // Not allowed to publish internal address, so use external
243 $unl = self::determineOwnExternalAddress();
244 } elseif (FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_address') != '') {
246 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Getting config entry internal_address ...');
248 // Use it as internal address
249 $unl = FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_address');
252 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Calling self::determineInternalUniversalNodeLocator() ...');
254 // Determine own internal address
255 $unl = self::determineInternalUniversalNodeLocator();
259 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $unl . ' - EXIT!');
266 * Determines the UNL (Universal Node Locator) for the internal address
268 * @return $internalUnl Internal UNL
270 public static function determineInternalUniversalNodeLocator () {
272 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
274 // Is there cache? (This shortens a lot calls)
275 if (!isset($GLOBALS[__METHOD__])) {
276 // Determine UNL based on this node:
277 // 1) Get discovery class
278 $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
281 $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('internal');
283 // Make sure it is valid
284 // @TODO Find a better validation than empty()
285 assert(!empty($GLOBALS[__METHOD__]));
289 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
290 return $GLOBALS[__METHOD__];
294 * Determines the UNL (Universal Node Locator) for the external address
296 * @return $externalUnl External UNL
298 public static function determineExternalUniversalNodeLocator () {
300 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
302 // Is there cache? (This shortens a lot calls)
303 if (!isset($GLOBALS[__METHOD__])) {
304 // Determine UNL based on this node:
305 // 1) Get discovery class
306 $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
309 $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('external');
311 // Make sure it is valid
312 // @TODO Find a better validation than empty()
313 assert(!empty($GLOBALS[__METHOD__]));
317 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
318 return $GLOBALS[__METHOD__];