]> git.mxchange.org Git - hub.git/blob - application/hub/main/tools/class_HubTools.php
Added line numbers to debug lines as this will become the 'norm'
[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@ship-simu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.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::createDhtObjectInstance('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 ip:port combination. The opposite method
90          * is resolveSessionIdByIpPort()
91          *
92          * @param       $sessionId                      A valid session id
93          * @return      $recipientIpPort        Recipient as ip:port combination
94          */
95         protected function resolveIpPortBySessionId ($sessionId) {
96                 // Init variable
97                 $recipientIpPort = 'invalid:invalid';
98
99                 // And ask it for ip:port by given session id
100                 $recipient = $this->getDhtInstance()->findNodeLocalBySessionId($sessionId);
101
102                 // Is the recipient valid?
103                 if ((isset($recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_IP])) && (isset($recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_LISTEN_PORT]))) {
104                         // Then use this
105                         $recipientIpPort = $recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_EXTERNAL_IP] . ':' . $recipient[NodeDistributedHashTableDatabaseWrapper::DB_COLUMN_LISTEN_PORT];
106                 } else {
107                         // Get the instance, this might throw a NPE
108                         $nodeInstance = Registry::getRegistry()->getInstance('node');
109
110                         // Is the session id the same?
111                         if ($nodeInstance->getSessionId() == $sessionId) {
112                                 // Then get the ip:port from it, assume TCP by default
113                                 $recipientIpPort = self::determineOwnExternalIp() . ':' . $nodeInstance->getConfigInstance()->getConfigEntry('node_listen_port');
114                         } // END - if
115                 }
116
117                 // Return result
118                 return $recipientIpPort;
119         }
120
121         /**
122          * Resolves a ip:port combination into a session id. The "opposite" method
123          * is resolveIpPortBySessionId().
124          *
125          * @param       $ipPort         Ip:port combination
126          * @return      $sessionId      Valid session id
127          */
128         public static function resolveSessionIdByIpPort ($ipPort) {
129                 // Get an own instance
130                 $selfInstance = self::getSelfInstance();
131
132                 // And ask it for session id by given ip:port
133                 $recipient = $selfInstance->getDhtInstance()->findNodeByIpPort($ipPort);
134                 die(__METHOD__.':recipient=<pre>'.print_r($recipient, true).'</pre>' . PHP_EOL);
135
136                 // Return result
137                 return $sessionId;
138         }
139
140         /**
141          * Resolves given session id into an ip:port combination, if ip:port is set, it won't be translated
142          *
143          * @param       $sessionId      Session id or ip:port combination
144          * @return      $recipient      Recipient as ip:port combination
145          * @throws      InvalidSessionIdException       If the provided session id is invalid (and no ip:port combination)
146          * @throws      NoValidHostnameException        If the provided hostname cannot be resolved into an IP address
147          */
148         public static function resolveSessionId ($sessionId) {
149                 // Get an own instance
150                 $selfInstance = self::getSelfInstance();
151
152                 // Default is direct ip:port
153                 $recipient = $sessionId;
154
155                 // Does it match a direct ip:port? (hint: see www.regexlib.com for the regular expression)
156                 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)) {
157                         // Direct ip:port found
158                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __LINE__ . ']: Direct ip:port ' . $sessionId . ' detected.');
159                 } elseif (isset($selfInstance->sessionIdCache[$sessionId])) {
160                         // Debug message
161                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __LINE__ . ']: Using entry from sessionIdCache[] array.');
162
163                         // Found in cache!
164                         $recipient = $selfInstance->sessionIdCache[$sessionId];
165
166                         // Debug message
167                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __LINE__ . ']: sessionIdCache[' . $sessionId . ']=' . $recipient);
168                 } 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)) {
169                         // Hostname:port found
170                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __LINE__ . ']: hostname:port ' . $sessionId . ' detected.');
171
172                         // Hostname:port found
173                         $hostnameArray = explode(':', $sessionId);
174
175                         /*
176                          * Try to resolve it and add port again
177                          * @TODO Please try to encapsulate this PHP call into an own class
178                          */
179                         $recipient = gethostbyname($hostnameArray[0]) . ':' . $hostnameArray[1];
180
181                         // Is it valid?
182                         if ($recipient == $sessionId) {
183                                 // Resolving hostname->IP failed!
184                                 throw new NoValidHostnameException($hostnameArray, self::EXCEPTION_HOSTNAME_NOT_FOUND);
185                         } // END - if
186
187                         // Debug message
188                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __LINE__ . ']: hostname:port ' . $sessionId . ' resolved to ' . $recipient);
189                 } elseif (preg_match('/([a-f0-9]{' . $selfInstance->getSessionIdLength() . '})/', $sessionId)) {
190                         // Debug message
191                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __LINE__ . ']: Using internal session id resolver.');
192
193                         // Resolve session id into a ip:port combination
194                         $recipient = $selfInstance->resolveIpPortBySessionId($sessionId);
195
196                         // Debug message
197                         self::createDebugInstance(__CLASS__)->debugOutput('HUB-TOOLS[' . __LINE__ . ']: Session id ' . $sessionId . ' resolved to ' . $recipient);
198                 } else {
199                         // Invalid session id
200                         throw new InvalidSessionIdException($sessionId, self::EXCEPTION_SESSION_ID_IS_INVALID);
201                 }
202
203                 // Return it
204                 return $recipient;
205         }
206
207         /**
208          * Determine IP or 'external_ip' if set
209          *
210          * @return      $ip             The determined external ip of this node
211          */
212         public static function determineOwnExternalIp () {
213                 // Is the external_ip config entry set?
214                 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip') != '') {
215                         // Use it as external ip
216                         $ip = FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip');
217                 } else {
218                         // Determine own external ip by connecting to my (coder) server at 188.138.90.169
219                         $ip = ConsoleTools::determineExternalIp();
220                 }
221
222                 // Return it
223                 return $ip;
224         }
225
226         /**
227          * Determine IP or 'internal_ip' if set
228          *
229          * @return      $ip             The determined external ip of this node
230          */
231         public static function determineOwnInternalIp () {
232                 // Is the internal_ip config entry set?
233                 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('allow_publish_internal_ip') == 'N') {
234                         // Not allowed to publish internal IP, so use external
235                         $ip = self::determineOwnExternalIp();
236                 } elseif (FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_ip') != '') {
237                         // Use it as internal ip
238                         $ip = FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_ip');
239                 } else {
240                         // Determine own internal ip by connecting to my (coder) server at 188.138.90.169
241                         $ip = ConsoleTools::acquireSelfIPAddress();
242                 }
243
244                 // Return it
245                 return $ip;
246         }
247 }
248
249 // [EOF]
250 ?>