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