X-Git-Url: https://git.mxchange.org/?p=core.git;a=blobdiff_plain;f=inc%2Fclasses%2Fmain%2Fconsole%2Fclass_ConsoleTools.php;h=d5982605f7858ef42557203355324ec323c54c8f;hp=e6fdfda88f226b1485a4470b85da879c99b68848;hb=06f0a4e342028299c40aa7ec42c6a4acdb15a74a;hpb=7c3f349d55ec0eb4cdd4d7a694ccab5214451106 diff --git a/inc/classes/main/console/class_ConsoleTools.php b/inc/classes/main/console/class_ConsoleTools.php index e6fdfda8..d5982605 100644 --- a/inc/classes/main/console/class_ConsoleTools.php +++ b/inc/classes/main/console/class_ConsoleTools.php @@ -4,7 +4,7 @@ * * @author Roland Haeder * @version 0.0.0 - * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Core Developer Team + * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team * @license GNU GPL 3.0 or any newer version * @link http://www.ship-simu.org * @@ -46,7 +46,7 @@ class ConsoleTools extends BaseFrameworkSystem { */ protected function resolveIpAddress ($hostname) { // Debug message - $this->debugOutput(sprintf("[%s:] Our host name is: %s", + self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s', $this->__toString(), $hostname )); @@ -64,13 +64,13 @@ class ConsoleTools extends BaseFrameworkSystem { $ip = $ipResolved; // Debug message - $this->debugOutput(sprintf("[%s:] Resolved IP address is: %s\n", + self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s', $this->__toString(), $ip )); } else { // Problem while resolving IP address - $this->debugOutput(sprintf("[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.", + self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.', $this->__toString(), $hostname )); @@ -80,11 +80,123 @@ class ConsoleTools extends BaseFrameworkSystem { return $ip; } + /** + * Checks wether proxy configuration is used + * + * @return $isUsed Wether proxy is used + */ + protected function isProxyUsed () { + // 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 + + // Return cache + return $GLOBALS[__METHOD__]; + } + + /** + * Sets up a proxy tunnel for given hostname and through resource + * + * @param $host Host to connect to + * @param $port Port number to connect to + * @param $socketResource Resource of a socket + * @return $response Response array + */ + protected function setupProxyTunnel ($host, $port, $socketResource) { + // Initialize array + $response = array('', '', ''); + $proxyTunnel = ''; + + // Generate CONNECT request header + $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL; + $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL; + $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL; + + // Use login data to proxy? (username at least!) + if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') { + // Add it as well + $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->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__)->debugOutput('CONSOLE-TOOLS: proxyTunnel=' . $proxyTunnel); + + // Write request + fwrite($socketResource, $proxyTunnel); + + // Got response? + if (feof($socketResource)) { + // No response received + return $response; + } // END - if + + // Read the first line + $resp = trim(fgets($socketResource, 10240)); + $respArray = explode(' ', $resp); + 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; + } + + /** + * 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 + * + * @param $rawData Raw data from /etc/hostname file + * @return $hostname Extracted host name + */ + protected function extractHostnameFromRawData ($rawData) { + // Default is invalid + $hostname = 'invalid'; + + // Try to "explode" it + $data = explode(PHP_EOL, $rawData); + + // "Walk" through it + foreach ($data as $line) { + // Trim it + $line = trim($line); + + // Begins with a hash (#) = comment? + if (substr($line, 0, 1) == '#') { + // Then skip it + continue; + } // END - if + + // Has an equals sign? + if (strpos($line, '=') !== FALSE) { + // Then "explode" it again, right part is hostname in quotes + $hostData = explode('=', $line); + + // Make sure only a key=value pair goes through + assert(count($hostData) == 2); + + // Try to get it and abort + $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]); + break; + } else { + // Use it directly + $hostname = $line; + break; + } + } // END - foreach + + // Return it + return $hostname; + } + /** * Aquires the IP address of this host by reading the /etc/hostname file * and solving it. It is now stored in configuration * - * @return void + * @return $ip Aquired IP address */ public static function acquireSelfIPAddress () { // Local IP by default @@ -95,14 +207,17 @@ class ConsoleTools extends BaseFrameworkSystem { try { // Get a file pointer - $io = FrameworkFileInputPointer::createFrameworkFileInputPointer('/etc/hostname'); + $io = FrameworkFileInputPointer::createFrameworkFileInputPointer($helperInstance->getConfigInstance()->getConfigEntry('hostname_file')); // Read the file - $hostname = trim($io->readFromFile()); + $rawData = trim($io->readFromFile()); // Close the file $io->closeFile(); + // Extract hostname from it + $hostname = $helperInstance->extractHostnameFromRawData($rawData); + // Resolve the IP number $ip = $helperInstance->resolveIpAddress($hostname); } catch (FileIoException $e) { @@ -115,13 +230,13 @@ class ConsoleTools extends BaseFrameworkSystem { $ip = $helperInstance->resolveIpAddress($_SERVER['COMPUTERNAME']); } else { // Could not find our hostname - $helperInstance->debugOutput(sprintf("[%s:] WARNING: Cannot resolve my own IP address.", + self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.', $helperInstance->__toString() )); } } catch (FrameworkException $e) { // Output debug message - $helperInstance->debugOutput(sprintf("[%s:] Problem while resolving own IP address: [%s|%s]:%s", + self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s', $helperInstance->__toString(), $e->__toString(), $e->getHexCode(), @@ -131,6 +246,9 @@ class ConsoleTools extends BaseFrameworkSystem { // Set it in configuration FrameworkConfiguration::getSelfInstance()->setServerAddress($ip); + + // Return it + return $ip; } /** @@ -156,7 +274,18 @@ class ConsoleTools extends BaseFrameworkSystem { // First get a socket // @TODO Add some DNS caching here - $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 5); + + // Open connection + if ($helperInstance->isProxyUsed() === true) { + // Resolve hostname into IP address + $ip = $helperInstance->resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host')); + + // Connect to host through proxy connection + $socketResource = fsockopen($ip, $helperInstance->getConfigInstance()->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) { @@ -165,10 +294,30 @@ class ConsoleTools extends BaseFrameworkSystem { } // END - if // Prepare the GET request - $request = 'GET /ip.php HTTP/1.0' . self::HTTP_EOL; + $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://ship-simu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL; $request .= 'Host: ship-simu.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) { + // CONNECT method? + if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') { + // Setup proxy tunnel + $response = $helperInstance->setupProxyTunnel('ship-simu.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 + } else { + // Add header for proxy + $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL; + } + } // END - if + + // Add last HTTP_EOL $request .= self::HTTP_EOL; // Send it to the socket @@ -179,12 +328,23 @@ class ConsoleTools extends BaseFrameworkSystem { // And read the reply while (!feof($socketResource)) { - $externalAddress = fgets($socketResource, 128); + // Get line + $externalAddress = trim(fgets($socketResource, 128)); + + // Detect HTTP response + 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__)->debugOutput('CONSOLE-TOOLS: Resolved external address: ' . $externalAddress); + // Return determined external IP return $externalAddress; }