3 * This class contains static helper functions for console applications
5 * @author Roland Haeder <webmaster@shipsimu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2013 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.shipsimu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class ConsoleTools extends BaseFrameworkSystem {
26 const HTTP_EOL = "\r\n";
27 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
30 * Protected constructor
34 protected function __construct () {
35 // Call parent constructor
36 parent::__construct(__CLASS__);
40 * Tries to resolve an IP address from given hostname. Currently only IPv
41 * addresses are resolved.
43 * @param $hostname Host name we shall resolve
44 * @return $ip IP address resolved from host name
45 * @todo We should connect this to a caching class to cache DNS requests
47 protected function resolveIpAddress ($hostname) {
49 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
54 // Default is an invalid one
58 // @TODO Here should the cacher be implemented
59 $ipResolved = gethostbyname($hostname);
62 if (($ipResolved !== FALSE) && ($ipResolved != $hostname)) {
67 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
72 // Problem while resolving IP address
73 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
84 * Checks wether proxy configuration is used
86 * @return $isUsed Wether proxy is used
88 protected function isProxyUsed () {
90 if (!isset($GLOBALS[__METHOD__])) {
92 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
96 return $GLOBALS[__METHOD__];
100 * Sets up a proxy tunnel for given hostname and through resource
102 * @param $host Host to connect to
103 * @param $port Port number to connect to
104 * @param $socketResource Resource of a socket
105 * @return $response Response array
107 protected function setupProxyTunnel ($host, $port, $socketResource) {
109 $response = array('', '', '');
112 // Generate CONNECT request header
113 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
114 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
115 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
117 // Use login data to proxy? (username at least!)
118 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
120 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
121 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
125 $proxyTunnel .= self::HTTP_EOL;
126 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONSOLE-TOOLS[' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
129 fwrite($socketResource, $proxyTunnel);
132 if (feof($socketResource)) {
133 // No response received
137 // Read the first line
138 $resp = trim(fgets($socketResource, 10240));
139 $respArray = explode(' ', $resp);
140 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
150 * 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
152 * @param $rawData Raw data from /etc/hostname file
153 * @return $hostname Extracted host name
155 protected function extractHostnameFromRawData ($rawData) {
156 // Default is invalid
157 $hostname = 'invalid';
159 // Try to "explode" it
160 $data = explode(PHP_EOL, $rawData);
163 foreach ($data as $line) {
167 // Begins with a hash (#) = comment?
168 if (substr($line, 0, 1) == '#') {
173 // Has an equals sign?
174 if (strpos($line, '=') !== FALSE) {
175 // Then "explode" it again, right part is hostname in quotes
176 $hostData = explode('=', $line);
178 // Make sure only a key=value pair goes through
179 assert(count($hostData) == 2);
181 // Try to get it and abort
182 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
196 * Aquires the IP address of this host by reading the /etc/hostname file
197 * and solving it. It is now stored in configuration
199 * @return $ip Aquired IP address
201 public static function acquireSelfIPAddress () {
202 // Local IP by default
205 // Get a new instance
206 $helperInstance = new ConsoleTools();
209 // Get a file pointer
210 $io = FrameworkFileInputPointer::createFrameworkFileInputPointer($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
213 $rawData = trim($io->readFromFile());
218 // Extract hostname from it
219 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
221 // Resolve the IP number
222 $ip = $helperInstance->resolveIpAddress($hostname);
223 } catch (FileIoException $e) {
224 // Fall-back to 'SESSION_SVR' which found on my Sun Station
225 if (isset($_SERVER['SESSION_SVR'])) {
227 $ip = $helperInstance->resolveIpAddress($_SERVER['SESSION_SVR']);
228 } elseif (isset($_SERVER['COMPUTERNAME'])) {
229 // May happen on some XP systems, so also try this
230 $ip = $helperInstance->resolveIpAddress($_SERVER['COMPUTERNAME']);
232 // Could not find our hostname
233 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
234 $helperInstance->__toString()
237 } catch (FrameworkException $e) {
238 // Output debug message
239 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
240 $helperInstance->__toString(),
247 // Set it in configuration
248 FrameworkConfiguration::getSelfInstance()->setServerAddress($ip);
255 * Determines own remote IP address (e.g. can be used to probe if we are
256 * reachable from outside by determining external IP and then connect to it.
257 * This is accomblished by connecting to the IP of www.shipsimu.org which
258 * should default to 188.138.90.169 and requesting /ip.php which does only
259 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
260 * requires a working Internet connection.
262 * This method is taken from a user comment on php.net and heavily rewritten.
263 * Compare to following link:
264 * http://de.php.net/manual/en/function.socket-create.php#49368
266 * @return $externalAddress The determined external IP address
267 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
268 * @todo This should be moved out to an external class, e.g. HttpClient
269 * @todo Make IP, host name, port and script name configurable
271 public static function determineExternalIp () {
272 // Get helper instance
273 $helperInstance = new ConsoleTools();
275 // First get a socket
276 // @TODO Add some DNS caching here
279 if ($helperInstance->isProxyUsed() === TRUE) {
280 // Resolve hostname into IP address
281 $ip = $helperInstance->resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
283 // Connect to host through proxy connection
284 $socketResource = fsockopen($ip, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
286 // Connect to host directly
287 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
290 // Check if there was an error else
293 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
296 // Prepare the GET request
297 $request = 'GET ' . ($helperInstance->isProxyUsed() === TRUE ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
298 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
299 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
300 $request .= 'Connection: close' . self::HTTP_EOL;
303 if ($helperInstance->isProxyUsed() === TRUE) {
305 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
306 // Setup proxy tunnel
307 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
309 // If the response is invalid, abort
310 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
312 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, TRUE));
315 // Add header for proxy
316 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
321 $request .= self::HTTP_EOL;
323 // Send it to the socket
324 fwrite($socketResource, $request);
326 // Init IP (this will always be the last line)
327 $externalAddress = 'invalid';
329 // And read the reply
330 while (!feof($socketResource)) {
332 $externalAddress = trim(fgets($socketResource, 128));
334 // Detect HTTP response
335 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
342 fclose($socketResource);
346 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONSOLE-TOOLS[' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
348 // Return determined external IP
349 return $externalAddress;
353 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
354 * which indicates clearly that e.g. this script has been executed from
357 * @return $type The analyzed type, can be 'http' or 'console'
359 public static function analyzeEnvironmentForType () {
360 // Default is the console
363 // Now, do we have a request method, or query string set?
364 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
365 // Possibly HTTP request
374 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
375 * which indicates clearly that e.g. this script has been executed from
376 * console or web. This method should be used for class names, they
377 * currently are named differently. Here is a list to clarify this:
379 * Request type | Class type
380 * -----------------------------
384 * @return $type The analyzed type, can be 'http' or 'console'
386 public static function analyzeEnvironmentForClassType () {
387 // Default is the console
390 // Now, do we have a request method, or query string set?
391 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
392 // Possibly HTTP request