]> git.mxchange.org Git - hub.git/blob - application/hub/main/tools/class_HubTools.php
Decoding of raw package message basicly finished, external public ip now included...
[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 - 2011 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
84          *
85          * @param       $sessionId      A valid session id
86          * @return      $recipient      Recipient as ip:port combination
87          */
88         protected function resolveIpPortBySessionId ($sessionId) {
89                 // Get a wrapper instance
90                 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_list_db_wrapper_class');
91
92                 // And ask it for the session id
93                 $recipient = $wrapperInstance->resolveIpPortBySessionId($sessionId);
94
95                 // Is the recipient invalid?
96                 if ($recipient == 'invalid:invalid') {
97                         // Get the instance, this might throw a NPE
98                         $nodeInstance = Registry::getRegistry()->getInstance('node');
99
100                         // Is the session id the same?
101                         if ($nodeInstance->getSessionId() == $sessionId) {
102                                 // Then get the ip:port from it, assume TCP by default
103                                 $recipient = self::determineOwnExternalIp() . ':' . $nodeInstance->getConfigInstance()->getConfigEntry('node_tcp_listen_port');
104                         } // END - if
105                 } // END - if
106
107                 // Return result
108                 return $recipient;
109         }
110
111         /**
112          * Resolves a ip:port combination into a session id
113          *
114          * @param       $ipPort         Ip:port combination
115          * @return      $sessionId      Valid session id
116          */
117         public static function resolveSessionIdByIpPort ($ipPort) {
118                 // Get a wrapper instance
119                 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName('node_list_db_wrapper_class');
120
121                 // And ask it for the session id
122                 $sessionId = $wrapperInstance->resolveSessionIdByIpPort($ipPort);
123
124                 // Return result
125                 return $sessionId;
126         }
127
128         /**
129          * Resolves given session id into an ip:port combination, if ip:port is set, it won't be translated
130          *
131          * @param       $sessionId      Session id or ip:port combination
132          * @return      $recipient      Recipient as ip:port combination
133          * @throws      InvalidSessionIdException       If the provided session id is invalid (and no ip:port combination)
134          * @throws      NoValidHostnameException        If the provided hostname cannot be resolved into an IP address
135          */
136         public static function resolveSessionId ($sessionId) {
137                 // Get an own instance
138                 $selfInstance = self::getSelfInstance();
139
140                 // Default is direct ip:port
141                 $recipient = $sessionId;
142
143                 // Does it match a direct ip:port? (hint: see www.regexlib.com for the regular expression)
144                 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)) {
145                         // Direct ip:port found
146                         $selfInstance->debugOutput('HUB-TOOLS: Direct ip:port ' . $sessionId . ' detected.');
147                 } elseif (isset($selfInstance->sessionIdCache[$sessionId])) {
148                         // Debug message
149                         $selfInstance->debugOutput('HUB-TOOLS: Using entry from sessionIdCache[] array.');
150
151                         // Found in cache!
152                         $recipient = $selfInstance->sessionIdCache[$sessionId];
153                 } 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)) {
154                         // Hostname:port found
155                         $hostnameArray = explode(':', $sessionId);
156
157                         // Try to resolve it and add port again
158                         // @TODO We may want to encapsulate this PHP call into an own class
159                         $recipient = gethostbyname($hostnameArray[0]) . ':' . $hostnameArray[1];
160
161                         // Is it valid?
162                         if ($recipient == $sessionId) {
163                                 // Resolving hostname->IP failed!
164                                 throw new NoValidHostnameException($hostnameArray, self::EXCEPTION_HOSTNAME_NOT_FOUND);
165                         } // END - if
166                 } elseif (preg_match('/([a-f0-9]{' . $selfInstance->getSessionIdLength() . '})/', $sessionId)) {
167                         // Debug message
168                         $selfInstance->debugOutput('HUB-TOOLS: Using internal session id resolver.');
169
170                         // Resolve session id into a ip:port combination
171                         $recipient = $selfInstance->resolveIpPortBySessionId($sessionId);
172                 } else {
173                         // Invalid session id
174                         throw new InvalidSessionIdException($sessionId, self::EXCEPTION_SESSION_ID_IS_INVALID);
175                 }
176
177                 // Output message
178                 $selfInstance->debugOutput('HUB-TOOLS: Session id ' . $sessionId . ' resolved to ' . $recipient);
179
180                 // Return it
181                 return $recipient;
182         }
183
184         /**
185          * Determine IP or 'external_ip' if set
186          *
187          * @return      $ip             The determined external ip of this node
188          */
189         public static function determineOwnExternalIp () {
190                 // Is the external_ip config entry set?
191                 if (FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip') != '') {
192                         // Use it as external ip
193                         $ip = FrameworkConfiguration::getSelfInstance()->getConfigEntry('external_ip');
194                 } else {
195                         // Determine own external ip by connecting to my (coder) server at 188.138.90.169
196                         $ip = ConsoleTools::determineExternalIp();
197                 }
198
199                 // Return it
200                 return $ip;
201         }
202 }
203
204 // [EOF]
205 ?>