3 namespace CoreFramework\Tools;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Object\BaseFrameworkSystem;
10 * This class contains static helper functions for console applications
12 * @author Roland Haeder <webmaster@shipsimu.org>
14 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15 * @license GNU GPL 3.0 or any newer version
16 * @link http://www.shipsimu.org
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 class ConsoleTools extends BaseFrameworkSystem {
33 const HTTP_EOL = "\r\n";
34 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
37 * Protected constructor
41 protected function __construct () {
42 // Call parent constructor
43 parent::__construct(__CLASS__);
47 * Tries to resolve an IP address from given hostname. Currently only IPv
48 * addresses are resolved.
50 * @param $hostname Host name we shall resolve
51 * @return $ip IP address resolved from host name
52 * @todo We should connect this to a caching class to cache DNS requests
54 protected function resolveIpAddress ($hostname) {
56 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
61 // Default is an invalid one
65 // @TODO Here should the cacher be implemented
66 $ipResolved = gethostbyname($hostname);
69 if (($ipResolved !== FALSE) && ($ipResolved != $hostname)) {
74 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
79 // Problem while resolving IP address
80 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
91 * Checks wether proxy configuration is used
93 * @return $isUsed Wether proxy is used
95 protected function isProxyUsed () {
97 if (!isset($GLOBALS[__METHOD__])) {
99 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
103 return $GLOBALS[__METHOD__];
107 * Sets up a proxy tunnel for given hostname and through resource
109 * @param $host Host to connect to
110 * @param $port Port number to connect to
111 * @param $socketResource Resource of a socket
112 * @return $response Response array
114 protected function setupProxyTunnel ($host, $port, $socketResource) {
116 $response = array('', '', '');
119 // Generate CONNECT request header
120 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
121 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
122 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
124 // Use login data to proxy? (username at least!)
125 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
127 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
128 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
132 $proxyTunnel .= self::HTTP_EOL;
133 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
136 fwrite($socketResource, $proxyTunnel);
139 if (feof($socketResource)) {
140 // No response received
144 // Read the first line
145 $resp = trim(fgets($socketResource, 10240));
146 $respArray = explode(' ', $resp);
147 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
157 * 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
159 * @param $rawData Raw data from /etc/hostname file
160 * @return $hostname Extracted host name
162 protected function extractHostnameFromRawData ($rawData) {
163 // Default is invalid
164 $hostname = 'invalid';
166 // Try to "explode" it
167 $data = explode(PHP_EOL, $rawData);
170 foreach ($data as $line) {
174 // Begins with a hash (#) = comment?
175 if (substr($line, 0, 1) == '#') {
180 // Has an equals sign?
181 if (strpos($line, '=') !== FALSE) {
182 // Then "explode" it again, right part is hostname in quotes
183 $hostData = explode('=', $line);
185 // Make sure only a key=value pair goes through
186 assert(count($hostData) == 2);
188 // Try to get it and abort
189 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
203 * Aquires the IP address of this host by reading the /etc/hostname file
204 * and solving it. It is now stored in configuration
206 * @return $ip Aquired IP address
208 public static function acquireSelfIPAddress () {
209 // Local IP by default
212 // Get a new instance
213 $helperInstance = new ConsoleTools();
216 // Get a file pointer
217 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($helperInstance->getConfigInstance()->getConfigEntry('hostname_file')));
220 $rawData = trim($fileInstance->readFromFile());
223 $fileInstance->closeFile();
225 // Extract hostname from it
226 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
228 // Resolve the IP number
229 $ip = $helperInstance->resolveIpAddress($hostname);
230 } catch (FileNotFoundException $e) {
231 // Fall-back to 'SESSION_SVR' which found on my Sun Station
232 if (isset($_SERVER['SESSION_SVR'])) {
234 $ip = $helperInstance->resolveIpAddress($_SERVER['SESSION_SVR']);
235 } elseif (isset($_SERVER['COMPUTERNAME'])) {
236 // May happen on some XP systems, so also try this
237 $ip = $helperInstance->resolveIpAddress($_SERVER['COMPUTERNAME']);
239 // Could not find our hostname
240 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
241 $helperInstance->__toString()
244 } catch (FrameworkException $e) {
245 // Output debug message
246 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
247 $helperInstance->__toString(),
254 // Set it in configuration
255 FrameworkConfiguration::getSelfInstance()->setServerAddress($ip);
262 * Determines own remote IP address (e.g. can be used to probe if we are
263 * reachable from outside by determining external address and then connect to it.
264 * This is accomblished by connecting to the IP of www.shipsimu.org which
265 * should default to 188.138.90.169 and requesting /ip.php which does only
266 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
267 * requires a working Internet connection.
269 * This method is taken from a user comment on php.net and heavily rewritten.
270 * Compare to following link:
271 * http://de.php.net/manual/en/function.socket-create.php#49368
273 * @return $externalAddress The determined external address address
274 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
275 * @todo This should be moved out to an external class, e.g. HttpClient
276 * @todo Make IP, host name, port and script name configurable
278 public static function determineExternalAddress () {
279 // Get helper instance
280 $helperInstance = new ConsoleTools();
282 // First get a socket
283 // @TODO Add some DNS caching here
286 if ($helperInstance->isProxyUsed() === TRUE) {
287 // Resolve hostname into IP address
288 $ip = $helperInstance->resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
290 // Connect to host through proxy connection
291 $socketResource = fsockopen($ip, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
293 // Connect to host directly
294 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
297 // Check if there was an error else
300 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
303 // Prepare the GET request
304 $request = 'GET ' . ($helperInstance->isProxyUsed() === TRUE ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
305 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
306 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
307 $request .= 'Connection: close' . self::HTTP_EOL;
310 if ($helperInstance->isProxyUsed() === TRUE) {
312 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
313 // Setup proxy tunnel
314 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
316 // If the response is invalid, abort
317 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
319 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, TRUE));
322 // Add header for proxy
323 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
328 $request .= self::HTTP_EOL;
330 // Send it to the socket
331 fwrite($socketResource, $request);
333 // Init IP (this will always be the last line)
334 $externalAddress = 'invalid';
336 // And read the reply
337 while (!feof($socketResource)) {
339 $externalAddress = trim(fgets($socketResource, 128));
341 // Detect HTTP response
342 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
349 fclose($socketResource);
353 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
355 // Return determined external address
356 return $externalAddress;
360 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
361 * which indicates clearly that e.g. this script has been executed from
364 * @return $type The analyzed type, can be 'http' or 'console'
366 public static function analyzeEnvironmentForType () {
367 // Default is the console
370 // Now, do we have a request method, or query string set?
371 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
372 // Possibly HTTP request
381 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
382 * which indicates clearly that e.g. this script has been executed from
383 * console or web. This method should be used for class names, they
384 * currently are named differently. Here is a list to clarify this:
386 * Request type | Class type
387 * -----------------------------
391 * @return $type The analyzed type, can be 'http' or 'console'
393 public static function analyzeEnvironmentForClassType () {
394 // Default is the console
397 // Now, do we have a request method, or query string set?
398 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
399 // Possibly HTTP request