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\Object\BaseFrameworkSystem;
11 use Org\Mxchange\CoreFramework\Socket\InvalidSocketException;
14 use \InvalidArgumentException;
18 * This class contains static helper functions for console applications
20 * @author Roland Haeder <webmaster@shipsimu.org>
22 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
23 * @license GNU GPL 3.0 or any newer version
24 * @link http://www.shipsimu.org
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.
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.
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/>.
39 class ConsoleTools extends BaseFrameworkSystem {
41 const HTTP_EOL = "\r\n";
42 const HTTP_USER_AGENT = 'ConsoleTools/1.0.1';
45 * Default is that this class is noisy
47 private static $quietResolver = FALSE;
50 * Protected constructor
54 private function __construct () {
55 // Call parent constructor
56 parent::__construct(__CLASS__);
58 // Cache configuration entry
59 self::$quietResolver = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('quiet_dns_resolver');
63 * Checks wether proxy configuration is used
65 * @return $isUsed Wether proxy is used
67 protected function isProxyUsed () {
69 if (!isset($GLOBALS[__METHOD__])) {
71 $GLOBALS[__METHOD__] = (
73 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host') != ''
75 FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port') > 0
81 return $GLOBALS[__METHOD__];
85 * Sets up a proxy tunnel for given hostname and through resource
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
93 protected function setupProxyTunnel (string $host, int $port, $socketResource) {
97 throw new InvalidArgumentException('Parameter "host" is empty');
98 } elseif ($port < 1) {
100 throw new InvalidArgumentException(sprintf('port=%d is not valid', $port));
101 } elseif (!is_resource($socketResource)) {
103 throw new InvalidArgumentException(sprintf('socketResource[]=%s is not valid', gettype($socketResource)));
107 $response = ['', '', ''];
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;
115 // Use login data to proxy? (username at least!)
116 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') != '') {
118 $encodedAuth = base64_encode(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') . ':' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_password'));
119 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
123 $proxyTunnel .= self::HTTP_EOL;
124 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: proxyTunnel=' . $proxyTunnel);
127 fwrite($socketResource, $proxyTunnel);
130 if (feof($socketResource)) {
131 // No response received
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')) {
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
150 * @param $rawData Raw data from /etc/hostname file
151 * @return $hostname Extracted host name
152 * @throws InvalidArgumentException If a parameter is not valid
154 protected function extractHostnameFromRawData (string $rawData) {
155 // Validate parameter
156 if (empty($rawData)) {
158 throw new InvalidArgumentException('Parameter "rawData" is empty');
161 // Default is invalid
162 $hostname = 'invalid';
164 // Try to "explode" it
165 $data = explode(PHP_EOL, $rawData);
168 foreach ($data as $line) {
172 // Begins with a hash (#) = comment?
173 if (substr($line, 0, 1) == '#') {
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);
183 // Make sure only a key=value pair goes through
184 assert(count($hostData) == 2);
186 // Try to get it and abort
187 $hostname = str_replace(
205 * Tries to resolve an IP address from given hostname. Currently only IPv
206 * addresses are resolved.
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
213 public static function resolveIpAddress (string $hostname) {
214 // Validate parameter
215 if (empty($hostname)) {
217 throw new InvalidArgumentException('Parameter "hostname" is empty');
218 } elseif (self::$quietResolver !== TRUE) {
220 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
229 // Is a dot at the end?
230 if (substr($hostname, -1, 1) != '.') {
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.
242 // @TODO Here should the cacher be implemented
243 $ipResolved = gethostbyname($hostname);
246 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
248 $ipAddress = $ipResolved;
251 if (self::$quietResolver !== TRUE) {
253 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
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.',
266 // Return resolved IP
271 * Aquires the IP address of this host by reading the /etc/hostname file
272 * and solving it. It is now stored in configuration
274 * @return $ipAddress Aquired IPv4 address
276 public static function acquireSelfIpAddress () {
277 // Local IP by default
278 $ipAddress = '127.0.0.1';
280 // Get a new instance
281 $helperInstance = new ConsoleTools();
283 // Get SplFileInfo instance
284 $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hostname_file'));
287 // Get a file pointer
288 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
291 $rawData = trim($fileInstance->readFromFile());
294 $fileInstance->closeFile();
296 // Extract hostname from it
297 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
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'])) {
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']);
310 // Could not find our hostname
311 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
312 $helperInstance->__toString()
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(),
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.
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
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
346 public static function determineExternalAddress () {
347 // Get helper instance
348 $helperInstance = new ConsoleTools();
350 // First get a socket
351 // @TODO Add some DNS caching here
354 if ($helperInstance->isProxyUsed() === true) {
355 // Resolve hostname into IP address
356 $ipAddress = self::resolveIpAddress(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host'));
358 // Connect to host through proxy connection
359 $socketResource = fsockopen($ipAddress, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
361 // Connect to host directly
362 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
365 // Check if there was an error else
368 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
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;
378 if ($helperInstance->isProxyUsed() === true) {
380 if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
381 // Setup proxy tunnel
382 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
384 // If the response is invalid, abort
385 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
387 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
390 // Add header for proxy
391 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
396 $request .= self::HTTP_EOL;
398 // Send it to the socket
399 fwrite($socketResource, $request);
401 // Init IP (this will always be the last line)
402 $externalAddress = 'invalid';
404 // And read the reply
405 while (!feof($socketResource)) {
407 $externalAddress = trim(fgets($socketResource, 128));
409 // Detect HTTP response
410 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
417 fclose($socketResource);
419 // Return determined external address
420 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: Resolved external address: ' . $externalAddress);
421 return $externalAddress;
425 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
426 * which indicates clearly that e.g. this script has been executed from
429 * @return $type The analyzed type, can be 'http' or 'console'
431 public static function analyzeEnvironmentForType () {
432 // Default is the console
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
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:
451 * Request type | Class type
452 * -----------------------------
456 * @return $type The analyzed type, can be 'http' or 'console'
458 public static function analyzeEnvironmentForClassType () {
459 // Default is the console
462 // Now, do we have a request method, or query string set?
463 if (self::analyzeEnvironmentForType() == 'http') {
464 // Possibly HTTP request