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