<?php
// Own namespace
-namespace CoreFramework\Console\Tools;
+namespace Org\Mxchange\CoreFramework\Console\Tools;
// Import framework stuff
-use CoreFramework\Bootstrap\FrameworkBootstrap;
-use CoreFramework\Factory\ObjectFactory;
-use CoreFramework\Filesystem\FileNotFoundException;
-use CoreFramework\Generic\FrameworkException;
-use CoreFramework\Object\BaseFrameworkSystem;
-use CoreFramework\Socket\InvalidSocketException;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
+use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Socket\InvalidSocketException;
// Import SPL stuff
+use \InvalidArgumentException;
use \SplFileInfo;
/**
*
* @author Roland Haeder <webmaster@shipsimu.org>
* @version 0.0.0
- * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Hub Developer Team
+ * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
* @license GNU GPL 3.0 or any newer version
* @link http://www.shipsimu.org
*
class ConsoleTools extends BaseFrameworkSystem {
// Constants
const HTTP_EOL = "\r\n";
- const HTTP_USER_AGENT = 'ConsoleTools/1.0';
+ const HTTP_USER_AGENT = 'ConsoleTools/1.0.1';
/**
* Default is that this class is noisy
*/
- private static $quietResolver = FALSE;
+ private static $isQuietResolver = FALSE;
+
+ /**
+ * Cached values
+ */
+ private static $cache = [];
/**
* Protected constructor
*
* @return void
*/
- protected function __construct () {
+ private function __construct () {
// Call parent constructor
parent::__construct(__CLASS__);
// Cache configuration entry
- self::$quietResolver = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('quiet_dns_resolver');
+ self::$isQuietResolver = FrameworkBootstrap::getConfigurationInstance()->isEnabled('quiet_dns_resolver');
}
/**
// Do we have cache?
if (!isset($GLOBALS[__METHOD__])) {
// Determine it
- $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
- } // END - if
+ $GLOBALS[__METHOD__] = (
+ (
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host') != ''
+ ) && (
+ FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port') > 0
+ )
+ );
+ }
// Return cache
return $GLOBALS[__METHOD__];
* @param $port Port number to connect to
* @param $socketResource Resource of a socket
* @return $response Response array
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected function setupProxyTunnel ($host, $port, $socketResource) {
+ protected function setupProxyTunnel (string $host, int $port, $socketResource) {
+ // Validate parameter
+ if (empty($host)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif ($port < 1) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('port=%d is not valid', $port));
+ } elseif (!is_resource($socketResource)) {
+ // Throw IAE
+ throw new InvalidArgumentException(sprintf('socketResource[]=%s is not valid', gettype($socketResource)));
+ }
+
// Initialize array
- $response = array('', '', '');
+ $response = ['', '', ''];
$proxyTunnel = '';
// Generate CONNECT request header
$proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
// Use login data to proxy? (username at least!)
- if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
+ if (FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') != '') {
// Add it as well
- $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
+ $encodedAuth = base64_encode(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_username') . ':' . FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_password'));
$proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
- } // END - if
+ }
// Add last new-line
$proxyTunnel .= self::HTTP_EOL;
- //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
+ //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: proxyTunnel=' . $proxyTunnel);
// Write request
fwrite($socketResource, $proxyTunnel);
if (feof($socketResource)) {
// No response received
return $response;
- } // END - if
+ }
// Read the first line
$resp = trim(fgets($socketResource, 10240));
if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
// Invalid response!
return $response;
- } // END - if
+ }
// All fine!
return $respArray;
*
* @param $rawData Raw data from /etc/hostname file
* @return $hostname Extracted host name
+ * @throws InvalidArgumentException If a parameter is not valid
*/
- protected function extractHostnameFromRawData ($rawData) {
+ protected function extractHostnameFromRawData (string $rawData) {
+ // Validate parameter
+ if (empty($rawData)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "rawData" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ }
+
// Default is invalid
$hostname = 'invalid';
if (substr($line, 0, 1) == '#') {
// Then skip it
continue;
- } // END - if
+ }
// Has an equals sign?
if (strpos($line, '=') !== false) {
assert(count($hostData) == 2);
// Try to get it and abort
- $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
+ $hostname = str_replace(
+ ['"', chr(39)],
+ ['', ''],
+ $hostData[1]
+ );
break;
} else {
// Use it directly
$hostname = $line;
break;
}
- } // END - foreach
+ }
// Return it
return $hostname;
*
* @param $hostname Host name we shall resolve
* @return $ipAddress IPv4 address resolved from host name
+ * @throws InvalidArgumentException If a parameter is not valid
* @todo This should be connected to a caching class to cache DNS requests
*/
- public static function resolveIpAddress ($hostname) {
- // Quiet?
- if (self::$quietResolver !== TRUE) {
+ public static function resolveIpAddress (string $hostname) {
+ // Validate parameter
+ if (empty($hostname)) {
+ // Throw IAE
+ throw new InvalidArgumentException('Parameter "hostname" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+ } elseif (self::$isQuietResolver !== TRUE) {
// Debug message
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
__CLASS__,
$hostname
));
- } // END - if
+ }
// Default is false
$ipAddress = false;
* other domain, basically.
*/
$hostname .= '.';
- } // END - if
+ }
// Resolve it
// @TODO Here should the cacher be implemented
$ipAddress = $ipResolved;
// Quiet?
- if (self::$quietResolver !== TRUE) {
+ if (self::$isQuietResolver !== TRUE) {
// Debug message
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
__CLASS__,
$ipAddress
));
- } // END - if
+ }
} else {
// Problem while resolving IP address
self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
}
/**
- * Aquires the IP address of this host by reading the /etc/hostname file
- * and solving it. It is now stored in configuration
+ * acquires this host's LAN name. It tries a varity of different source.
*
- * @return $ipAddress Aquired IPv4 address
+ * @return $hostName The acquired name of this host or something invalid
*/
- public static function acquireSelfIpAddress () {
- // Local IP by default
- $ipAddress = '127.0.0.1';
+ public static function acquireHostname () {
+ // Is cache there?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
+ if (!isset(self::$cache[__METHOD__])) {
+ // Get a new instance
+ $toolsInstance = new ConsoleTools();
- // Get a new instance
- $helperInstance = new ConsoleTools();
+ // Get SplFileInfo instance
+ $infoInstance = new SplFileInfo(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('hostname_file'));
- // Get SplFileInfo instance
- $infoInstance = new SplFileInfo($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
+ // Init host name
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: infoInstance=%s', $infoInstance->__toString()));
+ $hostname = 'host.invalid';
- try {
- // Get a file pointer
- $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
+ // Try to check /etc/hostname first
+ try {
+ // Get a file pointer
+ $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', [$infoInstance]);
- // Read the file
- $rawData = trim($fileInstance->readFromFile());
+ // Read the file
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: fileInstance=%s', $fileInstance->__toString()));
+ $rawData = trim($fileInstance->readFromFile());
- // Close the file
- $fileInstance->closeFile();
+ // Close the file
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: rawData=%s', $rawData));
+ $fileInstance->closeFile();
- // Extract hostname from it
- $hostname = $helperInstance->extractHostnameFromRawData($rawData);
+ // Extract hostname from it
+ $hostname = $toolsInstance->extractHostnameFromRawData($rawData);
- // Resolve the IP number
- $ipAddress = self::resolveIpAddress($hostname);
- } catch (FileNotFoundException $e) {
- // Fall-back to 'SESSION_SVR' which found on my Sun Station
- if (isset($_SERVER['SESSION_SVR'])) {
- // Resolve it
- $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
- } elseif (isset($_SERVER['COMPUTERNAME'])) {
- // May happen on some Windows XP systems, so also try this
- $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
- } else {
- // Could not find our hostname
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
- $helperInstance->__toString()
+ // Debug message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from /etc/hostname', $hostname));
+ } catch (FileNotFoundException $e) {
+ // Fall-back to 'SESSION_SVR' which found on my Sun Station
+ if (isset($_SERVER['SESSION_SVR'])) {
+ // Resolve it
+ $hostname = $_SERVER['SESSION_SVR'];
+ } elseif (isset($_SERVER['COMPUTERNAME'])) {
+ // May happen on some Windows XP systems, so also try this
+ $hostname = $_SERVER['COMPUTERNAME'];
+ } else {
+ // Could not find our hostname
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot acquire my own host name.',
+ $toolsInstance->__toString()
+ ));
+ }
+
+ // Debug message
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from _SERVER array', $hostname));
+ } catch (FrameworkException $e) {
+ // Output debug message
+ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
+ $toolsInstance->__toString(),
+ $e->__toString(),
+ $e->getHexCode(),
+ $e->getMessage()
));
}
- } catch (FrameworkException $e) {
- // Output debug message
- self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
- $helperInstance->__toString(),
- $e->__toString(),
- $e->getHexCode(),
- $e->getMessage()
- ));
+
+ // Set cache
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting hostname=%s ...', $hostname));
+ self::$cache[__METHOD__] = $hostname;
+ } else {
+ // Get from cache
+ $hostname = self::$cache[__METHOD__];
}
// Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: hostname=%s - EXIT!', $hostname));
+ return $hostname;
+ }
+
+ /**
+ * acquires the IP address of this host by reading the /etc/hostname file
+ * and solving it. It is now stored in configuration
+ *
+ * @return $ipAddress acquired IPv4 address
+ */
+ public static function acquireSelfIpAddress () {
+ // Is cache there?
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!');
+ if (!isset(self::$cache[__METHOD__])) {
+ // Get host name
+ $hostname = self::acquireHostname();
+
+ // Resolve the IP number
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s', $hostname));
+ $ipAddress = self::resolveIpAddress($hostname);
+
+ // Set cache
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Setting ipAddress=%s ...', $ipAddress));
+ self::$cache[__METHOD__] = $ipAddress;
+ } else {
+ // Get it from cache
+ $ipAddress = self::$cache[__METHOD__];
+ }
+
+ // Return it
+ /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s - EXIT!', $ipAddress));
return $ipAddress;
}
*/
public static function determineExternalAddress () {
// Get helper instance
- $helperInstance = new ConsoleTools();
+ $toolsInstance = new ConsoleTools();
// First get a socket
// @TODO Add some DNS caching here
// Open connection
- if ($helperInstance->isProxyUsed() === true) {
+ if ($toolsInstance->isProxyUsed() === true) {
// Resolve hostname into IP address
- $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
+ $ipAddress = self::resolveIpAddress(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host'));
// Connect to host through proxy connection
- $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
+ $socketResource = fsockopen($ipAddress, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
} else {
// Connect to host directly
$socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
// Check if there was an error else
if ($errorNo > 0) {
// Then throw again
- throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
- } // END - if
+ throw new InvalidSocketException(array($toolsInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
+ }
// Prepare the GET request
- $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
+ $request = 'GET ' . ($toolsInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
$request .= 'Host: shipsimu.org' . self::HTTP_EOL;
$request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
$request .= 'Connection: close' . self::HTTP_EOL;
// Do we use proxy?
- if ($helperInstance->isProxyUsed() === true) {
+ if ($toolsInstance->isProxyUsed() === true) {
// CONNECT method?
- if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
+ if (FrameworkBootstrap::getConfigurationInstance()->isEnabled('proxy_connect_method')) {
// Setup proxy tunnel
- $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
+ $response = $toolsInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
// If the response is invalid, abort
if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
// Invalid response!
- $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
- } // END - if
+ $toolsInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
+ }
} else {
// Add header for proxy
$request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
}
- } // END - if
+ }
// Add last HTTP_EOL
$request .= self::HTTP_EOL;
if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
// Stop processing
break;
- } // END - if
- } // END - while
+ }
+ }
// Close socket
fclose($socketResource);
-
- // Debug message
- /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
-
// Return determined external address
+ /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: Resolved external address: ' . $externalAddress);
return $externalAddress;
}
if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
// Possibly HTTP request
$type = 'http';
- } // END - if
+ }
// Return it
return $type;
if (self::analyzeEnvironmentForType() == 'http') {
// Possibly HTTP request
$type = 'web';
- } // END - if
+ }
// Return it
return $type;