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