3 namespace CoreFramework\Console\Tools;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Generic\FrameworkException;
9 use CoreFramework\Object\BaseFrameworkSystem;
12 * This class contains static helper functions for console applications
14 * @author Roland Haeder <webmaster@shipsimu.org>
16 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
17 * @license GNU GPL 3.0 or any newer version
18 * @link http://www.shipsimu.org
20 * This program is free software: you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation, either version 3 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <http://www.gnu.org/licenses/>.
33 class ConsoleTools extends BaseFrameworkSystem {
35 const HTTP_EOL = "\r\n";
36 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
39 * Protected constructor
43 protected function __construct () {
44 // Call parent constructor
45 parent::__construct(__CLASS__);
49 * Checks wether proxy configuration is used
51 * @return $isUsed Wether proxy is used
53 protected function isProxyUsed () {
55 if (!isset($GLOBALS[__METHOD__])) {
57 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
61 return $GLOBALS[__METHOD__];
65 * Sets up a proxy tunnel for given hostname and through resource
67 * @param $host Host to connect to
68 * @param $port Port number to connect to
69 * @param $socketResource Resource of a socket
70 * @return $response Response array
72 protected function setupProxyTunnel ($host, $port, $socketResource) {
74 $response = array('', '', '');
77 // Generate CONNECT request header
78 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
79 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
80 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
82 // Use login data to proxy? (username at least!)
83 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
85 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
86 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
90 $proxyTunnel .= self::HTTP_EOL;
91 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
94 fwrite($socketResource, $proxyTunnel);
97 if (feof($socketResource)) {
98 // No response received
102 // Read the first line
103 $resp = trim(fgets($socketResource, 10240));
104 $respArray = explode(' ', $resp);
105 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
115 * 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
117 * @param $rawData Raw data from /etc/hostname file
118 * @return $hostname Extracted host name
120 protected function extractHostnameFromRawData ($rawData) {
121 // Default is invalid
122 $hostname = 'invalid';
124 // Try to "explode" it
125 $data = explode(PHP_EOL, $rawData);
128 foreach ($data as $line) {
132 // Begins with a hash (#) = comment?
133 if (substr($line, 0, 1) == '#') {
138 // Has an equals sign?
139 if (strpos($line, '=') !== false) {
140 // Then "explode" it again, right part is hostname in quotes
141 $hostData = explode('=', $line);
143 // Make sure only a key=value pair goes through
144 assert(count($hostData) == 2);
146 // Try to get it and abort
147 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
161 * Tries to resolve an IP address from given hostname. Currently only IPv
162 * addresses are resolved.
164 * @param $hostname Host name we shall resolve
165 * @return $ipAddress IPv4 address resolved from host name
166 * @todo This should be connected to a caching class to cache DNS requests
168 public static function resolveIpAddress ($hostname) {
170 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
178 // Is a dot at the end?
179 if (substr($hostname, -1, 1) != '.') {
181 * Then append it to prevent lookup of invalid host names through
182 * all search-domains. This will greatly improve lookup performance
183 * and has no disadvantages for anybody. A dot at the end of a
184 * domain btw means full-qualified domain, do not prepend to any
185 * other domain, basically.
191 // @TODO Here should the cacher be implemented
192 $ipResolved = gethostbyname($hostname);
195 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
197 $ipAddress = $ipResolved;
200 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
205 // Problem while resolving IP address
206 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
212 // Return resolved IP
217 * Aquires the IP address of this host by reading the /etc/hostname file
218 * and solving it. It is now stored in configuration
220 * @return $ipAddress Aquired IPv4 address
222 public static function acquireSelfIPAddress () {
223 // Local IP by default
224 $ipAddress = '127.0.0.1';
226 // Get a new instance
227 $helperInstance = new ConsoleTools();
230 // Get a file pointer
231 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($helperInstance->getConfigInstance()->getConfigEntry('hostname_file')));
234 $rawData = trim($fileInstance->readFromFile());
237 $fileInstance->closeFile();
239 // Extract hostname from it
240 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
242 // Resolve the IP number
243 $ipAddress = self::resolveIpAddress($hostname);
244 } catch (FileNotFoundException $e) {
245 // Fall-back to 'SESSION_SVR' which found on my Sun Station
246 if (isset($_SERVER['SESSION_SVR'])) {
248 $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
249 } elseif (isset($_SERVER['COMPUTERNAME'])) {
250 // May happen on some Windows XP systems, so also try this
251 $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
253 // Could not find our hostname
254 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
255 $helperInstance->__toString()
258 } catch (FrameworkException $e) {
259 // Output debug message
260 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
261 $helperInstance->__toString(),
268 // Set it in configuration
269 FrameworkConfiguration::getSelfInstance()->setServerAddress($ipAddress);
276 * Determines own remote IP address (e.g. can be used to probe if we are
277 * reachable from outside by determining external address and then connect to it.
278 * This is accomblished by connecting to the IP of www.shipsimu.org which
279 * should default to 188.138.90.169 and requesting /ip.php which does only
280 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
281 * requires a working Internet connection.
283 * This method is taken from a user comment on php.net and heavily rewritten.
284 * Compare to following link:
285 * http://de.php.net/manual/en/function.socket-create.php#49368
287 * @return $externalAddress The determined external address address
288 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
289 * @todo This should be moved out to an external class, e.g. HttpClient
290 * @todo Make IP, host name, port and script name configurable
292 public static function determineExternalAddress () {
293 // Get helper instance
294 $helperInstance = new ConsoleTools();
296 // First get a socket
297 // @TODO Add some DNS caching here
300 if ($helperInstance->isProxyUsed() === true) {
301 // Resolve hostname into IP address
302 $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
304 // Connect to host through proxy connection
305 $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
307 // Connect to host directly
308 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
311 // Check if there was an error else
314 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
317 // Prepare the GET request
318 $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
319 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
320 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
321 $request .= 'Connection: close' . self::HTTP_EOL;
324 if ($helperInstance->isProxyUsed() === true) {
326 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
327 // Setup proxy tunnel
328 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
330 // If the response is invalid, abort
331 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
333 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
336 // Add header for proxy
337 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
342 $request .= self::HTTP_EOL;
344 // Send it to the socket
345 fwrite($socketResource, $request);
347 // Init IP (this will always be the last line)
348 $externalAddress = 'invalid';
350 // And read the reply
351 while (!feof($socketResource)) {
353 $externalAddress = trim(fgets($socketResource, 128));
355 // Detect HTTP response
356 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
363 fclose($socketResource);
367 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
369 // Return determined external address
370 return $externalAddress;
374 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
375 * which indicates clearly that e.g. this script has been executed from
378 * @return $type The analyzed type, can be 'http' or 'console'
380 public static function analyzeEnvironmentForType () {
381 // Default is the console
384 // Now, do we have a request method, or query string set?
385 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
386 // Possibly HTTP request
395 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
396 * which indicates clearly that e.g. this script has been executed from
397 * console or web. This method should be used for class names, they
398 * currently are named differently. Here is a list to clarify this:
400 * Request type | Class type
401 * -----------------------------
405 * @return $type The analyzed type, can be 'http' or 'console'
407 public static function analyzeEnvironmentForClassType () {
408 // Default is the console
411 // Now, do we have a request method, or query string set?
412 if (self::analyzeEnvironmentForType() == 'http') {
413 // Possibly HTTP request