3 namespace CoreFramework\Console\Tools;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Filesystem\FileNotFoundException;
9 use CoreFramework\Generic\FrameworkException;
10 use CoreFramework\Object\BaseFrameworkSystem;
11 use CoreFramework\Socket\InvalidSocketException;
14 * This class contains static helper functions for console applications
16 * @author Roland Haeder <webmaster@shipsimu.org>
18 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Hub Developer Team
19 * @license GNU GPL 3.0 or any newer version
20 * @link http://www.shipsimu.org
22 * This program is free software: you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License as published by
24 * the Free Software Foundation, either version 3 of the License, or
25 * (at your option) any later version.
27 * This program is distributed in the hope that it will be useful,
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 * GNU General Public License for more details.
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 class ConsoleTools extends BaseFrameworkSystem {
37 const HTTP_EOL = "\r\n";
38 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
41 * Default is that this class is noisy
43 private static $quietResolver = FALSE;
46 * Protected constructor
50 protected function __construct () {
51 // Call parent constructor
52 parent::__construct(__CLASS__);
54 // Cache configuration entry
55 self::$quietResolver = FrameworkConfiguration::getSelfInstance()->getConfigEntry('quiet_dns_resolver');
59 * Checks wether proxy configuration is used
61 * @return $isUsed Wether proxy is used
63 protected function isProxyUsed () {
65 if (!isset($GLOBALS[__METHOD__])) {
67 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
71 return $GLOBALS[__METHOD__];
75 * Sets up a proxy tunnel for given hostname and through resource
77 * @param $host Host to connect to
78 * @param $port Port number to connect to
79 * @param $socketResource Resource of a socket
80 * @return $response Response array
82 protected function setupProxyTunnel ($host, $port, $socketResource) {
84 $response = array('', '', '');
87 // Generate CONNECT request header
88 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
89 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
90 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
92 // Use login data to proxy? (username at least!)
93 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
95 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
96 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
100 $proxyTunnel .= self::HTTP_EOL;
101 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
104 fwrite($socketResource, $proxyTunnel);
107 if (feof($socketResource)) {
108 // No response received
112 // Read the first line
113 $resp = trim(fgets($socketResource, 10240));
114 $respArray = explode(' ', $resp);
115 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
125 * 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
127 * @param $rawData Raw data from /etc/hostname file
128 * @return $hostname Extracted host name
130 protected function extractHostnameFromRawData ($rawData) {
131 // Default is invalid
132 $hostname = 'invalid';
134 // Try to "explode" it
135 $data = explode(PHP_EOL, $rawData);
138 foreach ($data as $line) {
142 // Begins with a hash (#) = comment?
143 if (substr($line, 0, 1) == '#') {
148 // Has an equals sign?
149 if (strpos($line, '=') !== false) {
150 // Then "explode" it again, right part is hostname in quotes
151 $hostData = explode('=', $line);
153 // Make sure only a key=value pair goes through
154 assert(count($hostData) == 2);
156 // Try to get it and abort
157 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
171 * Tries to resolve an IP address from given hostname. Currently only IPv
172 * addresses are resolved.
174 * @param $hostname Host name we shall resolve
175 * @return $ipAddress IPv4 address resolved from host name
176 * @todo This should be connected to a caching class to cache DNS requests
178 public static function resolveIpAddress ($hostname) {
180 if (self::$quietResolver !== TRUE) {
182 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
191 // Is a dot at the end?
192 if (substr($hostname, -1, 1) != '.') {
194 * Then append it to prevent lookup of invalid host names through
195 * all search-domains. This will greatly improve lookup performance
196 * and has no disadvantages for anybody. A dot at the end of a
197 * domain btw means full-qualified domain, do not prepend to any
198 * other domain, basically.
204 // @TODO Here should the cacher be implemented
205 $ipResolved = gethostbyname($hostname);
208 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
210 $ipAddress = $ipResolved;
213 if (self::$quietResolver !== TRUE) {
215 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
221 // Problem while resolving IP address
222 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
228 // Return resolved IP
233 * Aquires the IP address of this host by reading the /etc/hostname file
234 * and solving it. It is now stored in configuration
236 * @return $ipAddress Aquired IPv4 address
238 public static function acquireSelfIpAddress () {
239 // Local IP by default
240 $ipAddress = '127.0.0.1';
242 // Get a new instance
243 $helperInstance = new ConsoleTools();
246 // Get a file pointer
247 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($helperInstance->getConfigInstance()->getConfigEntry('hostname_file')));
250 $rawData = trim($fileInstance->readFromFile());
253 $fileInstance->closeFile();
255 // Extract hostname from it
256 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
258 // Resolve the IP number
259 $ipAddress = self::resolveIpAddress($hostname);
260 } catch (FileNotFoundException $e) {
261 // Fall-back to 'SESSION_SVR' which found on my Sun Station
262 if (isset($_SERVER['SESSION_SVR'])) {
264 $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
265 } elseif (isset($_SERVER['COMPUTERNAME'])) {
266 // May happen on some Windows XP systems, so also try this
267 $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
269 // Could not find our hostname
270 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
271 $helperInstance->__toString()
274 } catch (FrameworkException $e) {
275 // Output debug message
276 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
277 $helperInstance->__toString(),
284 // Set it in configuration
285 FrameworkConfiguration::getSelfInstance()->setServerAddress($ipAddress);
292 * Determines own remote IP address (e.g. can be used to probe if we are
293 * reachable from outside by determining external address and then connect to it.
294 * This is accomblished by connecting to the IP of www.shipsimu.org which
295 * should default to 188.138.90.169 and requesting /ip.php which does only
296 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
297 * requires a working Internet connection.
299 * This method is taken from a user comment on php.net and heavily rewritten.
300 * Compare to following link:
301 * http://de.php.net/manual/en/function.socket-create.php#49368
303 * @return $externalAddress The determined external address address
304 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
305 * @todo This should be moved out to an external class, e.g. HttpClient
306 * @todo Make IP, host name, port and script name configurable
308 public static function determineExternalAddress () {
309 // Get helper instance
310 $helperInstance = new ConsoleTools();
312 // First get a socket
313 // @TODO Add some DNS caching here
316 if ($helperInstance->isProxyUsed() === true) {
317 // Resolve hostname into IP address
318 $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
320 // Connect to host through proxy connection
321 $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
323 // Connect to host directly
324 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
327 // Check if there was an error else
330 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
333 // Prepare the GET request
334 $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
335 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
336 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
337 $request .= 'Connection: close' . self::HTTP_EOL;
340 if ($helperInstance->isProxyUsed() === true) {
342 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
343 // Setup proxy tunnel
344 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
346 // If the response is invalid, abort
347 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
349 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
352 // Add header for proxy
353 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
358 $request .= self::HTTP_EOL;
360 // Send it to the socket
361 fwrite($socketResource, $request);
363 // Init IP (this will always be the last line)
364 $externalAddress = 'invalid';
366 // And read the reply
367 while (!feof($socketResource)) {
369 $externalAddress = trim(fgets($socketResource, 128));
371 // Detect HTTP response
372 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
379 fclose($socketResource);
383 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
385 // Return determined external address
386 return $externalAddress;
390 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
391 * which indicates clearly that e.g. this script has been executed from
394 * @return $type The analyzed type, can be 'http' or 'console'
396 public static function analyzeEnvironmentForType () {
397 // Default is the console
400 // Now, do we have a request method, or query string set?
401 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
402 // Possibly HTTP request
411 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
412 * which indicates clearly that e.g. this script has been executed from
413 * console or web. This method should be used for class names, they
414 * currently are named differently. Here is a list to clarify this:
416 * Request type | Class type
417 * -----------------------------
421 * @return $type The analyzed type, can be 'http' or 'console'
423 public static function analyzeEnvironmentForClassType () {
424 // Default is the console
427 // Now, do we have a request method, or query string set?
428 if (self::analyzeEnvironmentForType() == 'http') {
429 // Possibly HTTP request