3 namespace CoreFramework\Tools;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Object\BaseFrameworkSystem;
11 * This class contains static helper functions for console applications
13 * @author Roland Haeder <webmaster@shipsimu.org>
15 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
16 * @license GNU GPL 3.0 or any newer version
17 * @link http://www.shipsimu.org
19 * This program is free software: you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation, either version 3 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <http://www.gnu.org/licenses/>.
32 class ConsoleTools extends BaseFrameworkSystem {
34 const HTTP_EOL = "\r\n";
35 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
38 * Protected constructor
42 protected function __construct () {
43 // Call parent constructor
44 parent::__construct(__CLASS__);
48 * Tries to resolve an IP address from given hostname. Currently only IPv
49 * addresses are resolved.
51 * @param $hostname Host name we shall resolve
52 * @return $ip IP address resolved from host name
53 * @todo We should connect this to a caching class to cache DNS requests
55 protected function resolveIpAddress ($hostname) {
57 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
62 // Default is an invalid one
66 // @TODO Here should the cacher be implemented
67 $ipResolved = gethostbyname($hostname);
70 if (($ipResolved !== FALSE) && ($ipResolved != $hostname)) {
75 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
80 // Problem while resolving IP address
81 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
92 * Checks wether proxy configuration is used
94 * @return $isUsed Wether proxy is used
96 protected function isProxyUsed () {
98 if (!isset($GLOBALS[__METHOD__])) {
100 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
104 return $GLOBALS[__METHOD__];
108 * Sets up a proxy tunnel for given hostname and through resource
110 * @param $host Host to connect to
111 * @param $port Port number to connect to
112 * @param $socketResource Resource of a socket
113 * @return $response Response array
115 protected function setupProxyTunnel ($host, $port, $socketResource) {
117 $response = array('', '', '');
120 // Generate CONNECT request header
121 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
122 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
123 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
125 // Use login data to proxy? (username at least!)
126 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
128 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
129 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
133 $proxyTunnel .= self::HTTP_EOL;
134 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
137 fwrite($socketResource, $proxyTunnel);
140 if (feof($socketResource)) {
141 // No response received
145 // Read the first line
146 $resp = trim(fgets($socketResource, 10240));
147 $respArray = explode(' ', $resp);
148 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
158 * 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
160 * @param $rawData Raw data from /etc/hostname file
161 * @return $hostname Extracted host name
163 protected function extractHostnameFromRawData ($rawData) {
164 // Default is invalid
165 $hostname = 'invalid';
167 // Try to "explode" it
168 $data = explode(PHP_EOL, $rawData);
171 foreach ($data as $line) {
175 // Begins with a hash (#) = comment?
176 if (substr($line, 0, 1) == '#') {
181 // Has an equals sign?
182 if (strpos($line, '=') !== FALSE) {
183 // Then "explode" it again, right part is hostname in quotes
184 $hostData = explode('=', $line);
186 // Make sure only a key=value pair goes through
187 assert(count($hostData) == 2);
189 // Try to get it and abort
190 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
204 * Aquires the IP address of this host by reading the /etc/hostname file
205 * and solving it. It is now stored in configuration
207 * @return $ip Aquired IP address
209 public static function acquireSelfIPAddress () {
210 // Local IP by default
213 // Get a new instance
214 $helperInstance = new ConsoleTools();
217 // Get a file pointer
218 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($helperInstance->getConfigInstance()->getConfigEntry('hostname_file')));
221 $rawData = trim($fileInstance->readFromFile());
224 $fileInstance->closeFile();
226 // Extract hostname from it
227 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
229 // Resolve the IP number
230 $ip = $helperInstance->resolveIpAddress($hostname);
231 } catch (FileNotFoundException $e) {
232 // Fall-back to 'SESSION_SVR' which found on my Sun Station
233 if (isset($_SERVER['SESSION_SVR'])) {
235 $ip = $helperInstance->resolveIpAddress($_SERVER['SESSION_SVR']);
236 } elseif (isset($_SERVER['COMPUTERNAME'])) {
237 // May happen on some XP systems, so also try this
238 $ip = $helperInstance->resolveIpAddress($_SERVER['COMPUTERNAME']);
240 // Could not find our hostname
241 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
242 $helperInstance->__toString()
245 } catch (FrameworkException $e) {
246 // Output debug message
247 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
248 $helperInstance->__toString(),
255 // Set it in configuration
256 FrameworkConfiguration::getSelfInstance()->setServerAddress($ip);
263 * Determines own remote IP address (e.g. can be used to probe if we are
264 * reachable from outside by determining external address and then connect to it.
265 * This is accomblished by connecting to the IP of www.shipsimu.org which
266 * should default to 188.138.90.169 and requesting /ip.php which does only
267 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
268 * requires a working Internet connection.
270 * This method is taken from a user comment on php.net and heavily rewritten.
271 * Compare to following link:
272 * http://de.php.net/manual/en/function.socket-create.php#49368
274 * @return $externalAddress The determined external address address
275 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
276 * @todo This should be moved out to an external class, e.g. HttpClient
277 * @todo Make IP, host name, port and script name configurable
279 public static function determineExternalAddress () {
280 // Get helper instance
281 $helperInstance = new ConsoleTools();
283 // First get a socket
284 // @TODO Add some DNS caching here
287 if ($helperInstance->isProxyUsed() === TRUE) {
288 // Resolve hostname into IP address
289 $ip = $helperInstance->resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
291 // Connect to host through proxy connection
292 $socketResource = fsockopen($ip, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
294 // Connect to host directly
295 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
298 // Check if there was an error else
301 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
304 // Prepare the GET request
305 $request = 'GET ' . ($helperInstance->isProxyUsed() === TRUE ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
306 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
307 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
308 $request .= 'Connection: close' . self::HTTP_EOL;
311 if ($helperInstance->isProxyUsed() === TRUE) {
313 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
314 // Setup proxy tunnel
315 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
317 // If the response is invalid, abort
318 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
320 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, TRUE));
323 // Add header for proxy
324 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
329 $request .= self::HTTP_EOL;
331 // Send it to the socket
332 fwrite($socketResource, $request);
334 // Init IP (this will always be the last line)
335 $externalAddress = 'invalid';
337 // And read the reply
338 while (!feof($socketResource)) {
340 $externalAddress = trim(fgets($socketResource, 128));
342 // Detect HTTP response
343 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
350 fclose($socketResource);
354 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
356 // Return determined external address
357 return $externalAddress;
361 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
362 * which indicates clearly that e.g. this script has been executed from
365 * @return $type The analyzed type, can be 'http' or 'console'
367 public static function analyzeEnvironmentForType () {
368 // Default is the console
371 // Now, do we have a request method, or query string set?
372 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
373 // Possibly HTTP request
382 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
383 * which indicates clearly that e.g. this script has been executed from
384 * console or web. This method should be used for class names, they
385 * currently are named differently. Here is a list to clarify this:
387 * Request type | Class type
388 * -----------------------------
392 * @return $type The analyzed type, can be 'http' or 'console'
394 public static function analyzeEnvironmentForClassType () {
395 // Default is the console
398 // Now, do we have a request method, or query string set?
399 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
400 // Possibly HTTP request