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