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