]> git.mxchange.org Git - core.git/blob - inc/classes/main/console/class_ConsoleTools.php
Copyright year updated, converted double->single quotes
[core.git] / inc / classes / main / console / class_ConsoleTools.php
1 <?php
2 /**
3  * This class contains static helper functions for console applications
4  *
5  * @author              Roland Haeder <webmaster@shipsimu.org>
6  * @version             0.0.0
7  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core 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 ConsoleTools extends BaseFrameworkSystem {
25         // Constants
26         const HTTP_EOL = "\r\n";
27         const HTTP_USER_AGENT = 'ConsoleTools/1.0';
28
29         /**
30          * Protected constructor
31          *
32          * @return      void
33          */
34         protected function __construct () {
35                 // Call parent constructor
36                 parent::__construct(__CLASS__);
37         }
38
39         /**
40          * Tries to resolve an IP address from given hostname. Currently only IPv
41          * addresses are resolved.
42          *
43          * @param       $hostname       Host name we shall resolve
44          * @return      $ip                     IP address resolved from host name
45          * @todo        We should connect this to a caching class to cache DNS requests
46          */
47         protected function resolveIpAddress ($hostname) {
48                 // Debug message
49                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
50                         $this->__toString(),
51                         $hostname
52                 ));
53
54                 // Default is an invalid one
55                 $ip = '0.0.0.0';
56
57                 // Resolve it
58                 // @TODO Here should the cacher be implemented
59                 $ipResolved = gethostbyname($hostname);
60
61                 // Was it fine?
62                 if (($ipResolved !== FALSE) && ($ipResolved != $hostname)) {
63                         // Okay, this works!
64                         $ip = $ipResolved;
65
66                         // Debug message
67                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
68                                 $this->__toString(),
69                                 $ip
70                         ));
71                 } else {
72                         // Problem while resolving IP address
73                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
74                                 $this->__toString(),
75                                 $hostname
76                         ));
77                 }
78
79                 // Return resolved IP
80                 return $ip;
81         }
82
83         /**
84          * Checks wether proxy configuration is used
85          *
86          * @return      $isUsed         Wether proxy is used
87          */
88         protected function isProxyUsed () {
89                 // Do we have cache?
90                 if (!isset($GLOBALS[__METHOD__])) {
91                         // Determine it
92                         $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
93                 } // END - if
94
95                 // Return cache
96                 return $GLOBALS[__METHOD__];
97         }
98
99         /**
100          * Sets up a proxy tunnel for given hostname and through resource
101          *
102          * @param       $host                           Host to connect to
103          * @param       $port                           Port number to connect to
104          * @param       $socketResource         Resource of a socket
105          * @return      $response                       Response array
106          */
107         protected function setupProxyTunnel ($host, $port, $socketResource) {
108                 // Initialize array
109                 $response = array('', '', '');
110                 $proxyTunnel = '';
111
112                 // Generate CONNECT request header
113                 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
114                 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
115                 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
116
117                 // Use login data to proxy? (username at least!)
118                 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
119                         // Add it as well
120                         $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
121                         $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
122                 } // END - if
123
124                 // Add last new-line
125                 $proxyTunnel .= self::HTTP_EOL;
126                 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONSOLE-TOOLS[' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
127
128                 // Write request
129                 fwrite($socketResource, $proxyTunnel);
130
131                 // Got response?
132                 if (feof($socketResource)) {
133                         // No response received
134                         return $response;
135                 } // END - if
136
137                 // Read the first line
138                 $resp = trim(fgets($socketResource, 10240));
139                 $respArray = explode(' ', $resp);
140                 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
141                         // Invalid response!
142                         return $response;
143                 } // END - if
144
145                 // All fine!
146                 return $respArray;
147         }
148
149         /**
150          * Tried to extract hostname from given raw data. On a Genntoo system, this could be multiple lines with # as comments. So try to get rid of it
151          *
152          * @param       $rawData        Raw data from /etc/hostname file
153          * @return      $hostname       Extracted host name
154          */
155         protected function extractHostnameFromRawData ($rawData) {
156                 // Default is invalid
157                 $hostname = 'invalid';
158
159                 // Try to "explode" it
160                 $data = explode(PHP_EOL, $rawData);
161
162                 // "Walk" through it
163                 foreach ($data as $line) {
164                         // Trim it
165                         $line = trim($line);
166
167                         // Begins with a hash (#) = comment?
168                         if (substr($line, 0, 1) == '#') {
169                                 // Then skip it
170                                 continue;
171                         } // END - if
172
173                         // Has an equals sign?
174                         if (strpos($line, '=') !== FALSE) {
175                                 // Then "explode" it again, right part is hostname in quotes
176                                 $hostData = explode('=', $line);
177
178                                 // Make sure only a key=value pair goes through
179                                 assert(count($hostData) == 2);
180
181                                 // Try to get it and abort
182                                 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
183                                 break;
184                         } else {
185                                 // Use it directly
186                                 $hostname = $line;
187                                 break;
188                         }
189                 } // END - foreach
190
191                 // Return it
192                 return $hostname;
193         }
194
195         /**
196          * Aquires the IP address of this host by reading the /etc/hostname file
197          * and solving it. It is now stored in configuration
198          *
199          * @return      $ip             Aquired IP address
200          */
201         public static function acquireSelfIPAddress () {
202                 // Local IP by default
203                 $ip = '127.0.0.1';
204
205                 // Get a new instance
206                 $helperInstance = new ConsoleTools();
207
208                 try {
209                         // Get a file pointer
210                         $io = FrameworkFileInputPointer::createFrameworkFileInputPointer($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
211
212                         // Read the file
213                         $rawData = trim($io->readFromFile());
214
215                         // Close the file
216                         $io->closeFile();
217
218                         // Extract hostname from it
219                         $hostname = $helperInstance->extractHostnameFromRawData($rawData);
220
221                         // Resolve the IP number
222                         $ip = $helperInstance->resolveIpAddress($hostname);
223                 } catch (FileIoException $e) {
224                         // Fall-back to 'SESSION_SVR' which found on my Sun Station
225                         if (isset($_SERVER['SESSION_SVR'])) {
226                                 // Resolve it
227                                 $ip = $helperInstance->resolveIpAddress($_SERVER['SESSION_SVR']);
228                         } elseif (isset($_SERVER['COMPUTERNAME'])) {
229                                 // May happen on some XP systems, so also try this
230                                 $ip = $helperInstance->resolveIpAddress($_SERVER['COMPUTERNAME']);
231                         } else {
232                                 // Could not find our hostname
233                                 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
234                                         $helperInstance->__toString()
235                                 ));
236                         }
237                 } catch (FrameworkException $e) {
238                         // Output debug message
239                         self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
240                                 $helperInstance->__toString(),
241                                 $e->__toString(),
242                                 $e->getHexCode(),
243                                 $e->getMessage()
244                         ));
245                 }
246
247                 // Set it in configuration
248                 FrameworkConfiguration::getSelfInstance()->setServerAddress($ip);
249
250                 // Return it
251                 return $ip;
252         }
253
254         /**
255          * Determines own remote IP address (e.g. can be used to probe if we are
256          * reachable from outside by determining external IP and then connect to it.
257          * This is accomblished by connecting to the IP of www.shipsimu.org which
258          * should default to 188.138.90.169 and requesting /ip.php which does only
259          * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
260          * requires a working Internet connection.
261          *
262          * This method is taken from a user comment on php.net and heavily rewritten.
263          * Compare to following link:
264          * http://de.php.net/manual/en/function.socket-create.php#49368
265          *
266          * @return      $externalAddress        The determined external IP address
267          * @throws      InvalidSocketException  If socket initialization wents wrong or if an errors occurs
268          * @todo        This should be moved out to an external class, e.g. HttpClient
269          * @todo        Make IP, host name, port and script name configurable
270          */
271         public static function determineExternalIp () {
272                 // Get helper instance
273                 $helperInstance = new ConsoleTools();
274
275                 // First get a socket
276                 // @TODO Add some DNS caching here
277
278                 // Open connection
279                 if ($helperInstance->isProxyUsed() === TRUE) {
280                         // Resolve hostname into IP address
281                         $ip = $helperInstance->resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
282
283                         // Connect to host through proxy connection
284                         $socketResource = fsockopen($ip, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
285                 } else {
286                         // Connect to host directly
287                         $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
288                 }
289
290                 // Check if there was an error else
291                 if ($errorNo > 0) {
292                         // Then throw again
293                         throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
294                 } // END - if
295
296                 // Prepare the GET request
297                 $request  = 'GET ' . ($helperInstance->isProxyUsed() === TRUE ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
298                 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
299                 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
300                 $request .= 'Connection: close' . self::HTTP_EOL;
301
302                 // Do we use proxy?
303                 if ($helperInstance->isProxyUsed() === TRUE) {
304                         // CONNECT method?
305                         if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
306                                 // Setup proxy tunnel
307                                 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
308
309                                 // If the response is invalid, abort
310                                 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
311                                         // Invalid response!
312                                         $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, TRUE));
313                                 } // END - if
314                         } else {
315                                 // Add header for proxy
316                                 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
317                         }
318                 } // END - if
319
320                 // Add last HTTP_EOL
321                 $request .= self::HTTP_EOL;
322
323                 // Send it to the socket
324                 fwrite($socketResource, $request);
325
326                 // Init IP (this will always be the last line)
327                 $externalAddress = 'invalid';
328
329                 // And read the reply
330                 while (!feof($socketResource)) {
331                         // Get line
332                         $externalAddress = trim(fgets($socketResource, 128));
333
334                         // Detect HTTP response
335                         if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
336                                 // Stop processing
337                                 break;
338                         } // END - if
339                 } // END - while
340
341                 // Close socket
342                 fclose($socketResource);
343
344
345                 // Debug message
346                 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONSOLE-TOOLS[' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
347
348                 // Return determined external IP
349                 return $externalAddress;
350         }
351
352         /**
353          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
354          * which indicates clearly that e.g. this script has been executed from
355          * console or web.
356          *
357          * @return      $type   The analyzed type, can be 'http' or 'console'
358          */
359         public static function analyzeEnvironmentForType () {
360                 // Default is the console
361                 $type = 'console';
362
363                 // Now, do we have a request method, or query string set?
364                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
365                         // Possibly HTTP request
366                         $type = 'http';
367                 } // END - if
368
369                 // Return it
370                 return $type;
371         }
372
373         /**
374          * Analyzes the 'environment', mostly $_SERVER, for presence of elements
375          * which indicates clearly that e.g. this script has been executed from
376          * console or web. This method should be used for class names, they
377          * currently are named differently. Here is a list to clarify this:
378          *
379          *   Request type | Class type
380          * -----------------------------
381          *      http      |    web
382          *     console    |  console
383          *
384          * @return      $type   The analyzed type, can be 'http' or 'console'
385          */
386         public static function analyzeEnvironmentForClassType () {
387                 // Default is the console
388                 $type = 'console';
389
390                 // Now, do we have a request method, or query string set?
391                 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
392                         // Possibly HTTP request
393                         $type = 'web';
394                 } // END - if
395
396                 // Return it
397                 return $type;
398         }
399 }
400
401 // [EOF]
402 ?>