]> git.mxchange.org Git - hub.git/blob - application/hub/main/tools/class_HubTools.php
Rewrites, some more methods:
[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                 // Init salt length
54                 $this->sessionIdLength = 32 + $this->getConfigInstance()->getConfigEntry('salt_length');
55         }
56
57         /**
58          * Singleton getter for self instance
59          *
60          * @retuen      $selfInstance   An instance of this class
61          */
62         public static final function getSelfInstance () {
63                 // Is the instance set
64                 if (is_null(self::$selfInstance)) {
65                         // Then set it
66                         self::$selfInstance = new HubTools();
67                 } // END - if
68
69                 // Return own instance
70                 return self::$selfInstance;
71         }
72
73         /**
74          * Getter for session id length
75          *
76          * @return      $sessionIdLength        Length of session ids
77          */
78         protected final function getSessionIdLength () {
79                 return $this->sessionIdLength;
80         }
81
82         /**
83          * Resolves a session id into an ip:port combination. The opposite method
84          * is resolveSessionIdByIpPort()
85          *
86          * @param       $sessionId      A valid session id
87          * @param       $protocol       Name of the used protocol: TCP/UDP
88          * @return      $recipient      Recipient as ip:port combination
89          */
90         protected function resolveIpPortBySessionId ($sessionId, $protocol) {
91                 // Get a DHT instance
92                 $dhtInstance = DhtObjectFactory::createDhtObjectInstance('node');
93
94                 // And ask it for ip:port by given session id
95                 $recipient = $dhtInstance->findNodeBySessionId($sessionId, $protocol);
96                 die(__METHOD__.':recipient=<pre>'.print_r($recipient, true).'</pre>' . PHP_EOL);
97
98                 // Is the recipient invalid?
99                 if ($recipient == 'invalid:invalid') {
100                         // Get the instance, this might throw a NPE
101                         $nodeInstance = Registry::getRegistry()->getInstance('node');
102
103                         // Is the session id the same?
104                         if ($nodeInstance->getSessionId() == $sessionId) {
105                                 // Then get the ip:port from it, assume TCP by default
106                                 $recipient = self::determineOwnExternalIp() . ':' . $nodeInstance->getConfigInstance()->getConfigEntry('node_listen_port');
107                         } // END - if
108                 } // END - if
109
110                 // Return result
111                 return $recipient;
112         }
113
114         /**
115          * Resolves a ip:port combination into a session id. The "opposite" method
116          * is resolveIpPortBySessionId().
117          *
118          * @param       $ipPort         Ip:port combination
119          * @param       $protocol       Name of used protocol (TCP/UDP)
120          * @return      $sessionId      Valid session id
121          */
122         public static function resolveSessionIdByIpPort ($ipPort, $protocol) {
123                 // Get a DHT instance
124                 $dhtInstance = DhtObjectFactory::createDhtObjectInstance('node');
125
126                 // And ask it for session id by given ip:port
127                 $recipient = $dhtInstance->findNodeByIpPort($ipPort, $protocol);
128                 die(__METHOD__.':recipient=<pre>'.print_r($recipient, true).'</pre>' . PHP_EOL);
129
130                 // Return result
131                 return $sessionId;
132         }
133
134         /**
135          * Resolves given session id into an ip:port combination, if ip:port is set, it won't be translated
136          *
137          * @param       $sessionId      Session id or ip:port combination
138          * @param       $protocol       Name of the used protocol (TCP/UDP)
139          * @return      $recipient      Recipient as ip:port combination
140          * @throws      InvalidSessionIdException       If the provided session id is invalid (and no ip:port combination)
141          * @throws      NoValidHostnameException        If the provided hostname cannot be resolved into an IP address
142          */
143         public static function resolveSessionId ($sessionId, $protocol) {
144                 // Get an own instance
145                 $selfInstance = self::getSelfInstance();
146
147                 // Default is direct ip:port
148                 $recipient = $sessionId;
149
150                 // Does it match a direct ip:port? (hint: see www.regexlib.com for the regular expression)
151                 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)) {
152                         // Direct ip:port found
153                         $selfInstance->debugOutput('HUB-TOOLS: Direct ip:port ' . $sessionId . ' detected.');
154                 } elseif (isset($selfInstance->sessionIdCache[$sessionId])) {
155                         // Debug message
156                         $selfInstance->debugOutput('HUB-TOOLS: Using entry from sessionIdCache[] array.');
157
158                         // Found in cache!
159                         $recipient = $selfInstance->sessionIdCache[$sessionId];
160
161                         // Debug message
162                         $selfInstance->debugOutput('HUB-TOOLS: sessionIdCache[' . $sessionId . ']=' . $recipient);
163                 } 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)) {
164                         // Hostname:port found
165                         $selfInstance->debugOutput('HUB-TOOLS: hostname:port ' . $sessionId . ' detected.');
166
167                         // Hostname:port found
168                         $hostnameArray = explode(':', $sessionId);
169
170                         // Try to resolve it and add port again
171                         // @TODO Please try to encapsulate this PHP call into an own class
172                         $recipient = gethostbyname($hostnameArray[0]) . ':' . $hostnameArray[1];
173
174                         // Is it valid?
175                         if ($recipient == $sessionId) {
176                                 // Resolving hostname->IP failed!
177                                 throw new NoValidHostnameException($hostnameArray, self::EXCEPTION_HOSTNAME_NOT_FOUND);
178                         } // END - if
179
180                         // Debug message
181                         $selfInstance->debugOutput('HUB-TOOLS: hostname:port ' . $sessionId . ' resolved to ' . $recipient);
182                 } elseif (preg_match('/([a-f0-9]{' . $selfInstance->getSessionIdLength() . '})/', $sessionId)) {
183                         // Debug message
184                         $selfInstance->debugOutput('HUB-TOOLS: Using internal session id resolver.');
185
186                         // Resolve session id into a ip:port combination
187                         $recipient = $selfInstance->resolveIpPortBySessionId($sessionId, $protocol);
188
189                         // Debug message
190                         $selfInstance->debugOutput('HUB-TOOLS: session id ' . $sessionId . ' resolved to ' . $recipient);
191                 } else {
192                         // Invalid session id
193                         throw new InvalidSessionIdException($sessionId, self::EXCEPTION_SESSION_ID_IS_INVALID);
194                 }
195
196                 // Return it
197                 return $recipient;
198         }
199
200         /**
201          * Determine IP or 'external_ip' if set
202          *
203          * @return      $ip             The determined external ip of this node
204          */
205         public static function determineOwnExternalIp () {
206                 // Is the external_ip config entry set?
207                 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip') != '') {
208                         // Use it as external ip
209                         $ip = FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip');
210                 } else {
211                         // Determine own external ip by connecting to my (coder) server at 188.138.90.169
212                         $ip = ConsoleTools::determineExternalIp();
213                 }
214
215                 // Return it
216                 return $ip;
217         }
218
219         /**
220          * Determine IP or 'internal_ip' if set
221          *
222          * @return      $ip             The determined external ip of this node
223          */
224         public static function determineOwnInternalIp () {
225                 // Is the internal_ip config entry set?
226                 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('allow_publish_internal_ip') == 'N') {
227                         // Not allowed to publish internal IP, so use external
228                         $ip = self::determineOwnExternalIp();
229                 } elseif (FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_ip') != '') {
230                         // Use it as internal ip
231                         $ip = FrameworkConfiguration::getSelfInstance()->getConfigEntry('internal_ip');
232                 } else {
233                         // Determine own internal ip by connecting to my (coder) server at 188.138.90.169
234                         $ip = ConsoleTools::acquireSelfIPAddress();
235                 }
236
237                 // Return it
238                 return $ip;
239         }
240 }
241
242 // [EOF]
243 ?>