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\Listener\BaseListener;
10 use CoreFramework\Object\BaseFrameworkSystem;
13 * This class contains static helper functions for console applications
15 * @author Roland Haeder <webmaster@shipsimu.org>
17 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
18 * @license GNU GPL 3.0 or any newer version
19 * @link http://www.shipsimu.org
21 * This program is free software: you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation, either version 3 of the License, or
24 * (at your option) any later version.
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <http://www.gnu.org/licenses/>.
34 class ConsoleTools extends BaseFrameworkSystem {
36 const HTTP_EOL = "\r\n";
37 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
40 * Protected constructor
44 protected function __construct () {
45 // Call parent constructor
46 parent::__construct(__CLASS__);
50 * Checks wether proxy configuration is used
52 * @return $isUsed Wether proxy is used
54 protected function isProxyUsed () {
56 if (!isset($GLOBALS[__METHOD__])) {
58 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
62 return $GLOBALS[__METHOD__];
66 * Sets up a proxy tunnel for given hostname and through resource
68 * @param $host Host to connect to
69 * @param $port Port number to connect to
70 * @param $socketResource Resource of a socket
71 * @return $response Response array
73 protected function setupProxyTunnel ($host, $port, $socketResource) {
75 $response = array('', '', '');
78 // Generate CONNECT request header
79 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
80 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
81 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
83 // Use login data to proxy? (username at least!)
84 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
86 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
87 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
91 $proxyTunnel .= self::HTTP_EOL;
92 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
95 fwrite($socketResource, $proxyTunnel);
98 if (feof($socketResource)) {
99 // No response received
103 // Read the first line
104 $resp = trim(fgets($socketResource, 10240));
105 $respArray = explode(' ', $resp);
106 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
116 * 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
118 * @param $rawData Raw data from /etc/hostname file
119 * @return $hostname Extracted host name
121 protected function extractHostnameFromRawData ($rawData) {
122 // Default is invalid
123 $hostname = 'invalid';
125 // Try to "explode" it
126 $data = explode(PHP_EOL, $rawData);
129 foreach ($data as $line) {
133 // Begins with a hash (#) = comment?
134 if (substr($line, 0, 1) == '#') {
139 // Has an equals sign?
140 if (strpos($line, '=') !== false) {
141 // Then "explode" it again, right part is hostname in quotes
142 $hostData = explode('=', $line);
144 // Make sure only a key=value pair goes through
145 assert(count($hostData) == 2);
147 // Try to get it and abort
148 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
162 * Tries to resolve an IP address from given hostname. Currently only IPv
163 * addresses are resolved.
165 * @param $hostname Host name we shall resolve
166 * @return $ipAddress IPv4 address resolved from host name
167 * @todo This should be connected to a caching class to cache DNS requests
169 public static function resolveIpAddress ($hostname) {
171 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
179 // Is a dot at the end?
180 if (substr($hostname, -1, 1) != '.') {
182 * Then append it to prevent lookup of invalid host names through
183 * all search-domains. This will greatly improve lookup performance
184 * and has no disadvantages for anybody. A dot at the end of a
185 * domain btw means full-qualified domain, do not prepend to any
186 * other domain, basically.
192 // @TODO Here should the cacher be implemented
193 $ipResolved = gethostbyname($hostname);
196 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
198 $ipAddress = $ipResolved;
201 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
206 // Problem while resolving IP address
207 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
213 // Return resolved IP
218 * Aquires the IP address of this host by reading the /etc/hostname file
219 * and solving it. It is now stored in configuration
221 * @return $ipAddress Aquired IPv4 address
223 public static function acquireSelfIPAddress () {
224 // Local IP by default
225 $ipAddress = '127.0.0.1';
227 // Get a new instance
228 $helperInstance = new ConsoleTools();
231 // Get a file pointer
232 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($helperInstance->getConfigInstance()->getConfigEntry('hostname_file')));
235 $rawData = trim($fileInstance->readFromFile());
238 $fileInstance->closeFile();
240 // Extract hostname from it
241 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
243 // Resolve the IP number
244 $ipAddress = self::resolveIpAddress($hostname);
245 } catch (FileNotFoundException $e) {
246 // Fall-back to 'SESSION_SVR' which found on my Sun Station
247 if (isset($_SERVER['SESSION_SVR'])) {
249 $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
250 } elseif (isset($_SERVER['COMPUTERNAME'])) {
251 // May happen on some Windows XP systems, so also try this
252 $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
254 // Could not find our hostname
255 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
256 $helperInstance->__toString()
259 } catch (FrameworkException $e) {
260 // Output debug message
261 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
262 $helperInstance->__toString(),
269 // Set it in configuration
270 FrameworkConfiguration::getSelfInstance()->setServerAddress($ipAddress);
277 * Determines own remote IP address (e.g. can be used to probe if we are
278 * reachable from outside by determining external address and then connect to it.
279 * This is accomblished by connecting to the IP of www.shipsimu.org which
280 * should default to 188.138.90.169 and requesting /ip.php which does only
281 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
282 * requires a working Internet connection.
284 * This method is taken from a user comment on php.net and heavily rewritten.
285 * Compare to following link:
286 * http://de.php.net/manual/en/function.socket-create.php#49368
288 * @return $externalAddress The determined external address address
289 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
290 * @todo This should be moved out to an external class, e.g. HttpClient
291 * @todo Make IP, host name, port and script name configurable
293 public static function determineExternalAddress () {
294 // Get helper instance
295 $helperInstance = new ConsoleTools();
297 // First get a socket
298 // @TODO Add some DNS caching here
301 if ($helperInstance->isProxyUsed() === true) {
302 // Resolve hostname into IP address
303 $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
305 // Connect to host through proxy connection
306 $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
308 // Connect to host directly
309 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
312 // Check if there was an error else
315 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseListener::EXCEPTION_INVALID_SOCKET);
318 // Prepare the GET request
319 $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
320 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
321 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
322 $request .= 'Connection: close' . self::HTTP_EOL;
325 if ($helperInstance->isProxyUsed() === true) {
327 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
328 // Setup proxy tunnel
329 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
331 // If the response is invalid, abort
332 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
334 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
337 // Add header for proxy
338 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
343 $request .= self::HTTP_EOL;
345 // Send it to the socket
346 fwrite($socketResource, $request);
348 // Init IP (this will always be the last line)
349 $externalAddress = 'invalid';
351 // And read the reply
352 while (!feof($socketResource)) {
354 $externalAddress = trim(fgets($socketResource, 128));
356 // Detect HTTP response
357 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
364 fclose($socketResource);
368 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
370 // Return determined external address
371 return $externalAddress;
375 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
376 * which indicates clearly that e.g. this script has been executed from
379 * @return $type The analyzed type, can be 'http' or 'console'
381 public static function analyzeEnvironmentForType () {
382 // Default is the console
385 // Now, do we have a request method, or query string set?
386 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
387 // Possibly HTTP request
396 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
397 * which indicates clearly that e.g. this script has been executed from
398 * console or web. This method should be used for class names, they
399 * currently are named differently. Here is a list to clarify this:
401 * Request type | Class type
402 * -----------------------------
406 * @return $type The analyzed type, can be 'http' or 'console'
408 public static function analyzeEnvironmentForClassType () {
409 // Default is the console
412 // Now, do we have a request method, or query string set?
413 if (self::analyzeEnvironmentForType() == 'http') {
414 // Possibly HTTP request