3 namespace Org\Mxchange\CoreFramework\Console\Tools;
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;
15 use \InvalidArgumentException;
17 use \UnexpectedValueException;
20 * This class contains static helper functions for console applications
22 * @author Roland Haeder <webmaster@shipsimu.org>
24 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
25 * @license GNU GPL 3.0 or any newer version
26 * @link http://www.shipsimu.org
28 * This program is free software: you can redistribute it and/or modify
29 * it under the terms of the GNU General Public License as published by
30 * the Free Software Foundation, either version 3 of the License, or
31 * (at your option) any later version.
33 * This program is distributed in the hope that it will be useful,
34 * but WITHOUT ANY WARRANTY; without even the implied warranty of
35 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 * GNU General Public License for more details.
38 * You should have received a copy of the GNU General Public License
39 * along with this program. If not, see <http://www.gnu.org/licenses/>.
41 class ConsoleTools extends BaseFrameworkSystem {
43 const HTTP_EOL = "\r\n";
44 const HTTP_USER_AGENT = 'ConsoleTools/1.0.1';
47 * Default is that this class is noisy
49 private static $isQuietResolver = FALSE;
54 private static $cache = [];
57 * Protected constructor
61 private function __construct () {
62 // Call parent constructor
63 parent::__construct(__CLASS__);
65 // Cache configuration entry
66 self::$isQuietResolver = FrameworkBootstrap::getConfigurationInstance()->isEnabled('quiet_dns_resolver');
70 * Checks wether proxy configuration is used
72 * @return $isUsed Wether proxy is used
74 protected function isProxyUsed () {
76 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
77 if (!isset($GLOBALS[__METHOD__])) {
79 $GLOBALS[__METHOD__] = (
81 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host') != ''
83 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port') > 0
89 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: isUsed=%d', $GLOBALS[__METHOD__]));
90 return $GLOBALS[__METHOD__];
94 * Sets up a proxy tunnel for given hostname and through resource
96 * @param $host Host to connect to
97 * @param $port Port number to connect to
98 * @param $socketResource Resource of a socket
99 * @return $response Response array
100 * @throws InvalidArgumentException If a parameter is not valid
102 protected function setupProxyTunnel (string $host, int $port, $socketResource) {
103 // Validate parameter
104 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: host=%s,port=%d,socketResource=%s - CALLED!', $host, $port, $socketResource));
107 throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
108 } elseif ($port < 1) {
110 throw new InvalidArgumentException(sprintf('port=%d is not valid', $port));
111 } elseif (!is_resource($socketResource)) {
113 throw new InvalidArgumentException(sprintf('socketResource[]=%s is not valid', gettype($socketResource)));
117 $response = ['', '', ''];
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;
125 // Use login data to proxy? (username at least!)
126 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') != '') {
128 $encodedAuth = base64_encode(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') . ':' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_password'));
129 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
133 $proxyTunnel .= self::HTTP_EOL;
136 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Sending %d bytes to socketResource=%s (proxy tunnel) ...', strlen($proxyTunnel), $socketResource));
137 fwrite($socketResource, $proxyTunnel);
140 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: feof(%s)=%d', $socketResource, intval(feof($socketResource))));
141 if (feof($socketResource)) {
142 // No response received
143 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: response()=%d, feof! - EXIT!', count($response)));
147 // Read the first line
148 $resp = trim(fgets($socketResource, 10240));
149 $respArray = explode(' ', $resp);
150 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
156 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: respArray()=%d - EXIT!', count($respArray)));
161 * 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
163 * @param $rawData Raw data from /etc/hostname file
164 * @return $hostname Extracted host name
165 * @throws InvalidArgumentException If a parameter is not valid
167 protected function extractHostnameFromRawData (string $rawData) {
168 // Validate parameter
169 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: rawData=%s - CALLED!', $rawData));
170 if (empty($rawData)) {
172 throw new InvalidArgumentException('Parameter "rawData" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
175 // Default is invalid
176 $hostname = 'invalid';
178 // Try to "explode" it
179 $data = explode(PHP_EOL, $rawData);
182 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: data()=%d', count($data)));
183 foreach ($data as $line) {
187 // Begins with a hash (#) = comment?
188 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: line=%s', $line));
189 if (substr($line, 0, 1) == '#') {
191 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: line=%s - SKIPPED!', $line));
195 // Has an equals sign?
196 if (strpos($line, '=') !== false) {
197 // Then "explode" it again, right part is hostname in quotes
198 $hostData = explode('=', $line);
200 // Make sure only a key=value pair goes through
201 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostData()=%d', count($hostData)));
202 if (count($hostData) < 2) {
204 throw new UnexpectedValueException(sprintf('hostData()=%d is unexpected, line=%s', count($hostData), $line), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
207 // Try to get it and abort
208 $hostname = str_replace(
213 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from hostData - BREAK!', $hostname));
218 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from line - BREAK!', $line));
224 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - EXIT!', $hostname));
229 * Tries to resolve an IP address from given hostname. Currently only IPv
230 * addresses are resolved.
232 * @param $hostname Host name we shall resolve
233 * @return $ipAddress IPv4 address resolved from host name
234 * @throws InvalidArgumentException If a parameter is not valid
235 * @todo This should be connected to a caching class to cache DNS requests
237 public static function resolveIpAddress (string $hostname) {
238 // Validate parameter
239 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - CALLED!', $hostname));
240 if (empty($hostname)) {
242 throw new InvalidArgumentException('Parameter "hostname" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
243 } elseif (self::$isQuietResolver !== TRUE) {
245 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Host name to resolve is: %s',
254 // Is a dot at the end?
255 if (substr($hostname, -1, 1) != '.') {
257 * Then append it to prevent lookup of invalid host names through
258 * all search-domains. This will greatly improve lookup performance
259 * and has no disadvantages for anybody. A dot at the end of a
260 * domain btw means full-qualified domain, do not prepend to any
261 * other domain, basically.
267 // @TODO Here should the cacher be implemented
268 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s', $hostname));
269 $ipResolved = gethostbyname($hostname);
272 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: ipResolved[%s]=%s', gettype($ipResolved), $ipResolved));
273 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
275 $ipAddress = $ipResolved;
278 if (self::$isQuietResolver !== TRUE) {
280 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Resolved IP address is: %s',
286 // Problem while resolving IP address
287 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
293 // Return resolved IP
294 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s - EXIT!', $ipAddress));
299 * acquires this host's LAN name. It tries a varity of different source.
301 * @return $hostName The acquired name of this host or something invalid
303 public static function acquireHostname () {
305 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
306 if (!isset(self::$cache[__METHOD__])) {
307 // Get a new instance
308 $toolsInstance = new ConsoleTools();
310 // Get SplFileInfo instance
311 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hostname_file'));
314 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: infoInstance=%s', $infoInstance->__toString()));
315 $hostname = 'host.invalid';
317 // Try to check /etc/hostname first
319 // Get a file pointer
320 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', [$infoInstance]);
323 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: fileInstance=%s', $fileInstance->__toString()));
324 $rawData = trim($fileInstance->readFromFile());
327 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: rawData=%s', $rawData));
328 $fileInstance->closeFile();
330 // Extract hostname from it
331 $hostname = $toolsInstance->extractHostnameFromRawData($rawData);
334 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from /etc/hostname', $hostname));
335 } catch (FileNotFoundException $e) {
336 // Fall-back to 'SESSION_SVR' which found on my Sun Station
337 if (isset($_SERVER['SESSION_SVR'])) {
339 $hostname = $_SERVER['SESSION_SVR'];
340 } elseif (isset($_SERVER['COMPUTERNAME'])) {
341 // May happen on some Windows XP systems, so also try this
342 $hostname = $_SERVER['COMPUTERNAME'];
344 // Could not find our hostname
345 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] WARNING: Cannot acquire my own host name.',
346 $toolsInstance->__toString()
351 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from _SERVER array', $hostname));
352 } catch (FrameworkException $e) {
353 // Output debug message
354 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
355 $toolsInstance->__toString(),
363 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting hostname=%s ...', $hostname));
364 self::$cache[__METHOD__] = $hostname;
367 $hostname = self::$cache[__METHOD__];
371 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - EXIT!', $hostname));
376 * acquires the IP address of this host by reading the /etc/hostname file
377 * and solving it. It is now stored in configuration
379 * @return $ipAddress acquired IPv4 address
381 public static function acquireSelfIpAddress () {
383 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
384 if (!isset(self::$cache[__METHOD__])) {
386 $hostname = self::acquireHostname();
388 // Resolve the IP number
389 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s', $hostname));
390 $ipAddress = self::resolveIpAddress($hostname);
393 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting ipAddress=%s ...', $ipAddress));
394 self::$cache[__METHOD__] = $ipAddress;
397 $ipAddress = self::$cache[__METHOD__];
401 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s - EXIT!', $ipAddress));
406 * Determines own remote IP address (e.g. can be used to probe if we are
407 * reachable from outside by determining external address and then connect to it.
408 * This is accomblished by connecting to the IP of www.shipsimu.org which
409 * should default to 188.138.90.169 and requesting /ip.php which does only
410 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
411 * requires a working Internet connection.
413 * This method is taken from a user comment on php.net and heavily rewritten.
414 * Compare to following link:
415 * http://de.php.net/manual/en/function.socket-create.php#49368
417 * @return $externalAddress The determined external address address
418 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
419 * @todo This should be moved out to an external class, e.g. HttpClient
420 * @todo Make IP, host name, port and script name configurable
422 public static function determineExternalAddress () {
423 // Get helper instance
424 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
425 $toolsInstance = new ConsoleTools();
427 // First get a socket
428 // @TODO Add some DNS caching here
431 if ($toolsInstance->isProxyUsed() === true) {
432 // Resolve hostname into IP address
433 $ipAddress = self::resolveIpAddress(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host'));
435 // Connect to host through proxy connection
436 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s', $ipAddress));
437 $socketResource = fsockopen($ipAddress, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
439 // Connect to host directly
440 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
443 // Check if there was an error else
444 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: socketResource[%s]=%s,errorNo=%d,errorStr=%s', gettype($socketResource), $socketResource, $errorNo, $errorStr));
447 throw new InvalidSocketException([$toolsInstance, $socketResource, $errorNo, $errorStr], BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
450 // Prepare the GET request
451 $request = 'GET ' . ($toolsInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
452 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
453 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
454 $request .= 'Connection: close' . self::HTTP_EOL;
457 if ($toolsInstance->isProxyUsed() === true) {
459 if (FrameworkBootstrap::getConfigurationInstance()->isEnabled('proxy_connect_method')) {
460 // Setup proxy tunnel
461 $response = $toolsInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
463 // If the response is invalid, abort
464 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
466 $toolsInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
469 // Add header for proxy
470 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
475 $request .= self::HTTP_EOL;
477 // Send it to the socket
478 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Writing %d bytes to socketResource=%s ...', strlen($request), $socketResource));
479 fwrite($socketResource, $request);
481 // Init IP (this will always be the last line)
482 $externalAddress = 'invalid';
484 // And read the reply
485 while (!feof($socketResource)) {
487 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: feof()=%d', intval(feof($socketResource))));
488 $externalAddress = trim(fgets($socketResource, 128));
490 // Detect HTTP response
491 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: externalAddress=%s', $externalAddress));
492 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
494 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CONSOLE-TOOLS: BREAK!');
500 fclose($socketResource);
502 // Return determined external address
503 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: externalAddress=%s - EXIT!', $externalAddress));
504 return $externalAddress;
508 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
509 * which indicates clearly that e.g. this script has been executed from
512 * @return $type The analyzed type, can be 'http' or 'console'
514 public static function analyzeEnvironmentForType () {
515 // Default is the console
516 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
519 // Now, do we have a request method, or query string set?
520 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
521 // Possibly HTTP request
526 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: type=%s - EXIT!', $type));
531 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
532 * which indicates clearly that e.g. this script has been executed from
533 * console or web. This method should be used for class names, they
534 * currently are named differently. Here is a list to clarify this:
536 * Request type | Class type
537 * -----------------------------
541 * @return $type The analyzed type, can be 'http' or 'console'
543 public static function analyzeEnvironmentForClassType () {
544 // Default is the console
545 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
548 // Now, do we have a request method, or query string set?
549 if (self::analyzeEnvironmentForType() == 'http') {
550 // Possibly HTTP request
555 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: type=%s - EXIT!', $type));