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;
19 * This class contains static helper functions for console applications
21 * @author Roland Haeder <webmaster@shipsimu.org>
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
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.
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.
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/>.
40 class ConsoleTools extends BaseFrameworkSystem {
42 const HTTP_EOL = "\r\n";
43 const HTTP_USER_AGENT = 'ConsoleTools/1.0.1';
46 * Default is that this class is noisy
48 private static $isQuietResolver = FALSE;
53 private static $cache = [];
56 * Protected constructor
60 private function __construct () {
61 // Call parent constructor
62 parent::__construct(__CLASS__);
64 // Cache configuration entry
65 self::$isQuietResolver = FrameworkBootstrap::getConfigurationInstance()->isEnabled('quiet_dns_resolver');
69 * Checks wether proxy configuration is used
71 * @return $isUsed Wether proxy is used
73 protected function isProxyUsed () {
75 if (!isset($GLOBALS[__METHOD__])) {
77 $GLOBALS[__METHOD__] = (
79 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host') != ''
81 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port') > 0
87 return $GLOBALS[__METHOD__];
91 * Sets up a proxy tunnel for given hostname and through resource
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
99 protected function setupProxyTunnel (string $host, int $port, $socketResource) {
100 // Validate parameter
103 throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
104 } elseif ($port < 1) {
106 throw new InvalidArgumentException(sprintf('port=%d is not valid', $port));
107 } elseif (!is_resource($socketResource)) {
109 throw new InvalidArgumentException(sprintf('socketResource[]=%s is not valid', gettype($socketResource)));
113 $response = ['', '', ''];
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;
121 // Use login data to proxy? (username at least!)
122 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') != '') {
124 $encodedAuth = base64_encode(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') . ':' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_password'));
125 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
129 $proxyTunnel .= self::HTTP_EOL;
130 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: proxyTunnel=' . $proxyTunnel);
133 fwrite($socketResource, $proxyTunnel);
136 if (feof($socketResource)) {
137 // No response received
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')) {
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
156 * @param $rawData Raw data from /etc/hostname file
157 * @return $hostname Extracted host name
158 * @throws InvalidArgumentException If a parameter is not valid
160 protected function extractHostnameFromRawData (string $rawData) {
161 // Validate parameter
162 if (empty($rawData)) {
164 throw new InvalidArgumentException('Parameter "rawData" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
167 // Default is invalid
168 $hostname = 'invalid';
170 // Try to "explode" it
171 $data = explode(PHP_EOL, $rawData);
174 foreach ($data as $line) {
178 // Begins with a hash (#) = comment?
179 if (substr($line, 0, 1) == '#') {
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);
189 // Make sure only a key=value pair goes through
190 assert(count($hostData) == 2);
192 // Try to get it and abort
193 $hostname = str_replace(
211 * Tries to resolve an IP address from given hostname. Currently only IPv
212 * addresses are resolved.
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
219 public static function resolveIpAddress (string $hostname) {
220 // Validate parameter
221 if (empty($hostname)) {
223 throw new InvalidArgumentException('Parameter "hostname" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
224 } elseif (self::$isQuietResolver !== TRUE) {
226 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
235 // Is a dot at the end?
236 if (substr($hostname, -1, 1) != '.') {
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.
248 // @TODO Here should the cacher be implemented
249 $ipResolved = gethostbyname($hostname);
252 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
254 $ipAddress = $ipResolved;
257 if (self::$isQuietResolver !== TRUE) {
259 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
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.',
272 // Return resolved IP
277 * acquires this host's LAN name. It tries a varity of different source.
279 * @return $hostName The acquired name of this host or something invalid
281 public static function acquireHostname () {
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();
288 // Get SplFileInfo instance
289 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hostname_file'));
292 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: infoInstance=%s', $infoInstance->__toString()));
293 $hostname = 'host.invalid';
295 // Try to check /etc/hostname first
297 // Get a file pointer
298 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', [$infoInstance]);
301 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: fileInstance=%s', $fileInstance->__toString()));
302 $rawData = trim($fileInstance->readFromFile());
305 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: rawData=%s', $rawData));
306 $fileInstance->closeFile();
308 // Extract hostname from it
309 $hostname = $toolsInstance->extractHostnameFromRawData($rawData);
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'])) {
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'];
322 // Could not find our hostname
323 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot acquire my own host name.',
324 $toolsInstance->__toString()
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(),
341 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting hostname=%s ...', $hostname));
342 self::$cache[__METHOD__] = $hostname;
345 $hostname = self::$cache[__METHOD__];
349 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - EXIT!', $hostname));
354 * acquires the IP address of this host by reading the /etc/hostname file
355 * and solving it. It is now stored in configuration
357 * @return $ipAddress acquired IPv4 address
359 public static function acquireSelfIpAddress () {
361 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
362 if (!isset(self::$cache[__METHOD__])) {
364 $hostname = self::acquireHostname();
366 // Resolve the IP number
367 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s', $hostname));
368 $ipAddress = self::resolveIpAddress($hostname);
371 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting ipAddress=%s ...', $ipAddress));
372 self::$cache[__METHOD__] = $ipAddress;
375 $ipAddress = self::$cache[__METHOD__];
379 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s - EXIT!', $ipAddress));
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.
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
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
400 public static function determineExternalAddress () {
401 // Get helper instance
402 $toolsInstance = new ConsoleTools();
404 // First get a socket
405 // @TODO Add some DNS caching here
408 if ($toolsInstance->isProxyUsed() === true) {
409 // Resolve hostname into IP address
410 $ipAddress = self::resolveIpAddress(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host'));
412 // Connect to host through proxy connection
413 $socketResource = fsockopen($ipAddress, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
415 // Connect to host directly
416 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
419 // Check if there was an error else
422 throw new InvalidSocketException(array($toolsInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
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;
432 if ($toolsInstance->isProxyUsed() === true) {
434 if (FrameworkBootstrap::getConfigurationInstance()->isEnabled('proxy_connect_method')) {
435 // Setup proxy tunnel
436 $response = $toolsInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
438 // If the response is invalid, abort
439 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
441 $toolsInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
444 // Add header for proxy
445 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
450 $request .= self::HTTP_EOL;
452 // Send it to the socket
453 fwrite($socketResource, $request);
455 // Init IP (this will always be the last line)
456 $externalAddress = 'invalid';
458 // And read the reply
459 while (!feof($socketResource)) {
461 $externalAddress = trim(fgets($socketResource, 128));
463 // Detect HTTP response
464 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
471 fclose($socketResource);
473 // Return determined external address
474 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: Resolved external address: ' . $externalAddress);
475 return $externalAddress;
479 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
480 * which indicates clearly that e.g. this script has been executed from
483 * @return $type The analyzed type, can be 'http' or 'console'
485 public static function analyzeEnvironmentForType () {
486 // Default is the console
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
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:
505 * Request type | Class type
506 * -----------------------------
510 * @return $type The analyzed type, can be 'http' or 'console'
512 public static function analyzeEnvironmentForClassType () {
513 // Default is the console
516 // Now, do we have a request method, or query string set?
517 if (self::analyzeEnvironmentForType() == 'http') {
518 // Possibly HTTP request