]> git.mxchange.org Git - hub.git/blob - application/hub/main/tools/class_HubTools.php
Rewrote processMessage() to accept whole arrays + added filter for handling
[hub.git] / application / hub / main / tools / class_HubTools.php
1 <?php
2 /**
3  * This class contains static helper functions for our hub
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
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
10  *
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.
15  *
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.
20  *
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/>.
23  */
24 class HubTools extends BaseHubSystem {
25         // Constants for exceptions
26         const EXCEPTION_SESSION_ID_IS_INVALID = 0x200;
27         const EXCEPTION_HOSTNAME_NOT_FOUND    = 0x201;
28
29         /**
30          * Cache for session ids
31          */
32         private $sessionIdCache = array();
33
34         /**
35          * Length for session id (should be 32+salt_length
36          */
37         private $sessionIdLength = 0;
38
39         /**
40          * Self instance
41          */
42         private static $selfInstance = NULL;
43
44         /**
45          * Protected constructor
46          *
47          * @return      void
48          */
49         protected function __construct () {
50                 // Call parent constructor
51                 parent::__construct(__CLASS__);
52
53                 // Get a DHT instance
54                 $dhtInstance = DhtObjectFactory::createDhtInstance('node');
55
56                 // Set it here
57                 $this->setDhtInstance($dhtInstance);
58
59                 // Init salt length
60                 $this->sessionIdLength = 32 + $this->getConfigInstance()->getConfigEntry('salt_length');
61         }
62
63         /**
64          * Singleton getter for self instance
65          *
66          * @retuen      $selfInstance   An instance of this class
67          */
68         public static final function getSelfInstance () {
69                 // Is the instance set
70                 if (is_null(self::$selfInstance)) {
71                         // Then set it
72                         self::$selfInstance = new HubTools();
73                 } // END - if
74
75                 // Return own instance
76                 return self::$selfInstance;
77         }
78
79         /**
80          * Getter for session id length
81          *
82          * @return      $sessionIdLength        Length of session ids
83          */
84         protected final function getSessionIdLength () {
85                 return $this->sessionIdLength;
86         }
87
88         /**
89          * Resolves a session id into an instance of a LocateableNode class. The opposite method
90          * is resolveSessionIdByUniversalNodeLocator()
91          *
92          * @param       $sessionId                      A valid session id
93          * @return      $recipientUniversalNodeLocator  Recipient as Universal Node Locator
94          */
95         protected function resolveUniversalNodeLocatorBySessionId ($sessionId) {
96                 // Init variable
97                 $recipientUniversalNodeLocator = 'invalid://invalid:invalid';
98
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);
102
103                 // Is the recipient valid?
104                 if (isset($recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_ADDRESS])) {
105                         // Then use this
106                         $recipientUniversalNodeLocator = $recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_ADDRESS];
107                 } else {
108                         // Get the instance, this might throw a NPE
109                         $nodeInstance = NodeObjectFactory::createNodeInstance();
110
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');
115                         } // END - if
116                 }
117
118                 // Return result
119                 return $recipientUniversalNodeLocator;
120         }
121
122         /**
123          * Resolves a session id into a node id by asking local DHT.
124          *
125          * @param       $sessionId      Session id
126          * @return      $nodeId         Node id
127          */
128         public static function resolveNodeIdBySessionId ($sessionId) {
129                 // Get an own instance
130                 $selfInstance = self::getSelfInstance();
131
132                 // And ask it for session id by given Universal Node Locator
133                 $nodeData = $selfInstance->getDhtInstance()->findNodeLocalBySessionId($sessionId);
134
135                 // Make sure the node id is there
136                 assert(isset($nodeData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_NODE_ID]));
137
138                 // Return it
139                 return $nodeData[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_NODE_ID];
140         }
141
142         /**
143          * Resolves a Universal Node Locator into a session id. The "opposite" method
144          * is resolveUniversalNodeLocatorBySessionId().
145          *
146          * @param       $unlInstance    Universal Node Locator
147          * @return      $sessionId              Valid session id
148          */
149         public static function resolveSessionIdByUniversalNodeLocator (LocateableNode $unlInstance) {
150                 // Get an own instance
151                 $selfInstance = self::getSelfInstance();
152
153                 // And ask it for session id by given Universal Node Locator
154                 $recipient = $selfInstance->getDhtInstance()->findNodeByUniversalNodeLocator($unlInstance);
155                 die(__METHOD__.':recipient='.print_r($recipient, TRUE));
156
157                 // Return result
158                 return $sessionId;
159         }
160
161         /**
162          * Resolves given session id into an instance of a LocateableNode class, if Universal Node Locator is set, it won't be translated
163          *
164          * @param       $address        Session id or Universal Node Locator
165          * @return      $recipient      Recipient as Universal Node Locator
166          * @throws      InvalidSessionIdException       If the provided session id is invalid (and no Universal Node Locator)
167          * @throws      NoValidHostnameException        If the provided hostname cannot be resolved into an IP address
168          */
169         public static function resolveSessionId ($address) {
170                 // Get an own instance
171                 $selfInstance = self::getSelfInstance();
172
173                 // Default is direct Universal Node Locator
174                 $recipient = $address;
175
176                 // Does it match a direct Universal Node Locator? (hint: see www.regexlib.com for the regular expression)
177                 if (preg_match('/([a-z0-9]{3,10})\/\/:([a-z0-9\.]{5,})/', $address)) {
178                         // @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})
179                         // Direct Universal Node Locator found
180                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Direct Universal Node Locator ' . $address . ' detected.');
181                 } elseif (isset($selfInstance->sessionIdCache[$address])) {
182                         // Debug message
183                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Using entry from sessionIdCache[] array.');
184
185                         // Found in cache!
186                         $recipient = $selfInstance->sessionIdCache[$address];
187
188                         // Debug message
189                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: sessionIdCache[' . $address . ']=' . $recipient);
190                 } elseif (preg_match('/([a-f0-9]{' . $selfInstance->getSessionIdLength() . '})/', $address)) {
191                         // Debug message
192                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Using internal session id resolver.');
193
194                         // Resolve session id into an instance of a LocateableNode class
195                         $recipient = $selfInstance->resolveUniversalNodeLocatorBySessionId($address);
196
197                         // Debug message
198                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Session id ' . $address . ' resolved to ' . $recipient);
199                 } else {
200                         // Invalid session id/UNL
201                         throw new InvalidSessionIdException($address, self::EXCEPTION_SESSION_ID_IS_INVALID);
202                 }
203
204                 // Return it
205                 return $recipient;
206         }
207
208         /**
209          * Determine UNL or 'external_address' if set
210          *
211          * @return      $unl    The determined external UNL of this node
212          */
213         public static function determineOwnExternalAddress () {
214                 // Is the external_address config entry set?
215                 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_address') != '') {
216                         // Use it as external address
217                         $unl = FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_address');
218                 } else {
219                         // Determine own external address by connecting to my (coder) server at 188.138.90.169
220                         $unl = self::determineExternalUniversalNodeLocator();
221                 }
222
223                 // Return it
224                 return $unl;
225         }
226
227         /**
228          * Determine UNL or 'internal_address' if set
229          *
230          * @return      $unl    The determined internal UNL of this node
231          */
232         public static function determineOwnInternalAddress () {
233                 // Debug message
234                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
235
236                 // Is the internal_address config entry set?
237                 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('allow_publish_internal_address') == 'N') {
238                         // Debug message
239                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Calling self::determineOwnExternalAddress() as allow_publish_internal_address=N is set ...');
240
241                         // Not allowed to publish internal address, so use external
242                         $unl = self::determineOwnExternalAddress();
243                 } elseif (FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_address') != '') {
244                         // Debug message
245                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Getting config entry internal_address ...');
246
247                         // Use it as internal address
248                         $unl = FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_address');
249                 } else {
250                         // Debug message
251                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: Calling self::determineInternalUniversalNodeLocator() ...');
252
253                         // Determine own internal address
254                         $unl = self::determineInternalUniversalNodeLocator();
255                 }
256
257                 // Debug message
258                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $unl . ' - EXIT!');
259
260                 // Return it
261                 return $unl;
262         }
263
264         /**
265          * Determines the UNL (Universal Node Locator) for the internal address
266          *
267          * @return      $internalUnl    Internal UNL
268          */
269         public static function determineInternalUniversalNodeLocator () {
270                 // Debug message
271                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
272
273                 // Is there cache? (This shortens a lot calls)
274                 if (!isset($GLOBALS[__METHOD__])) {
275                         // Determine UNL based on this node:
276                         // 1) Get discovery class
277                         $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
278
279                         // 2) "Determine" it
280                         $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('internal');
281
282                         // Make sure it is valid
283                         // @TODO Find a better validation than empty()
284                         assert(!empty($GLOBALS[__METHOD__]));
285                 } // END - if
286
287                 // Return it
288                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
289                 return $GLOBALS[__METHOD__];
290         }
291
292         /**
293          * Determines the UNL (Universal Node Locator) for the external address
294          *
295          * @return      $externalUnl    External UNL
296          */
297         public static function determineExternalUniversalNodeLocator () {
298                 // Debug message
299                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: CALLED!');
300
301                 // Is there cache? (This shortens a lot calls)
302                 if (!isset($GLOBALS[__METHOD__])) {
303                         // Determine UNL based on this node:
304                         // 1) Get discovery class
305                         $discoveryInstance = ObjectFactory::createObjectByConfiguredName('unl_discovery_class');
306
307                         // 2) "Determine" it
308                         $GLOBALS[__METHOD__] = $discoveryInstance->discoverUniversalNodeLocatorByConfiguredAddress('external');
309
310                         // Make sure it is valid
311                         // @TODO Find a better validation than empty()
312                         assert(!empty($GLOBALS[__METHOD__]));
313                 } // END - if
314
315                 // Return it
316                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NODE[' . __METHOD__ . ':' . __LINE__ . ']: unl=' . $GLOBALS[__METHOD__] . ' - EXIT!');
317                 return $GLOBALS[__METHOD__];
318         }
319 }
320
321 // [EOF]
322 ?>