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