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 * Protected constructor
45 protected function __construct () {
46 // Call parent constructor
47 parent::__construct(__CLASS__);
51 * Checks wether proxy configuration is used
53 * @return $isUsed Wether proxy is used
55 protected function isProxyUsed () {
57 if (!isset($GLOBALS[__METHOD__])) {
59 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
63 return $GLOBALS[__METHOD__];
67 * Sets up a proxy tunnel for given hostname and through resource
69 * @param $host Host to connect to
70 * @param $port Port number to connect to
71 * @param $socketResource Resource of a socket
72 * @return $response Response array
74 protected function setupProxyTunnel ($host, $port, $socketResource) {
76 $response = array('', '', '');
79 // Generate CONNECT request header
80 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
81 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
82 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
84 // Use login data to proxy? (username at least!)
85 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
87 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
88 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
92 $proxyTunnel .= self::HTTP_EOL;
93 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
96 fwrite($socketResource, $proxyTunnel);
99 if (feof($socketResource)) {
100 // No response received
104 // Read the first line
105 $resp = trim(fgets($socketResource, 10240));
106 $respArray = explode(' ', $resp);
107 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
117 * 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
119 * @param $rawData Raw data from /etc/hostname file
120 * @return $hostname Extracted host name
122 protected function extractHostnameFromRawData ($rawData) {
123 // Default is invalid
124 $hostname = 'invalid';
126 // Try to "explode" it
127 $data = explode(PHP_EOL, $rawData);
130 foreach ($data as $line) {
134 // Begins with a hash (#) = comment?
135 if (substr($line, 0, 1) == '#') {
140 // Has an equals sign?
141 if (strpos($line, '=') !== false) {
142 // Then "explode" it again, right part is hostname in quotes
143 $hostData = explode('=', $line);
145 // Make sure only a key=value pair goes through
146 assert(count($hostData) == 2);
148 // Try to get it and abort
149 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
163 * Tries to resolve an IP address from given hostname. Currently only IPv
164 * addresses are resolved.
166 * @param $hostname Host name we shall resolve
167 * @return $ipAddress IPv4 address resolved from host name
168 * @todo This should be connected to a caching class to cache DNS requests
170 public static function resolveIpAddress ($hostname) {
172 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
180 // Is a dot at the end?
181 if (substr($hostname, -1, 1) != '.') {
183 * Then append it to prevent lookup of invalid host names through
184 * all search-domains. This will greatly improve lookup performance
185 * and has no disadvantages for anybody. A dot at the end of a
186 * domain btw means full-qualified domain, do not prepend to any
187 * other domain, basically.
193 // @TODO Here should the cacher be implemented
194 $ipResolved = gethostbyname($hostname);
197 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
199 $ipAddress = $ipResolved;
202 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
207 // Problem while resolving IP address
208 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
214 // Return resolved IP
219 * Aquires the IP address of this host by reading the /etc/hostname file
220 * and solving it. It is now stored in configuration
222 * @return $ipAddress Aquired IPv4 address
224 public static function acquireSelfIPAddress () {
225 // Local IP by default
226 $ipAddress = '127.0.0.1';
228 // Get a new instance
229 $helperInstance = new ConsoleTools();
232 // Get a file pointer
233 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($helperInstance->getConfigInstance()->getConfigEntry('hostname_file')));
236 $rawData = trim($fileInstance->readFromFile());
239 $fileInstance->closeFile();
241 // Extract hostname from it
242 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
244 // Resolve the IP number
245 $ipAddress = self::resolveIpAddress($hostname);
246 } catch (FileNotFoundException $e) {
247 // Fall-back to 'SESSION_SVR' which found on my Sun Station
248 if (isset($_SERVER['SESSION_SVR'])) {
250 $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
251 } elseif (isset($_SERVER['COMPUTERNAME'])) {
252 // May happen on some Windows XP systems, so also try this
253 $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
255 // Could not find our hostname
256 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
257 $helperInstance->__toString()
260 } catch (FrameworkException $e) {
261 // Output debug message
262 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
263 $helperInstance->__toString(),
270 // Set it in configuration
271 FrameworkConfiguration::getSelfInstance()->setServerAddress($ipAddress);
278 * Determines own remote IP address (e.g. can be used to probe if we are
279 * reachable from outside by determining external address and then connect to it.
280 * This is accomblished by connecting to the IP of www.shipsimu.org which
281 * should default to 188.138.90.169 and requesting /ip.php which does only
282 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
283 * requires a working Internet connection.
285 * This method is taken from a user comment on php.net and heavily rewritten.
286 * Compare to following link:
287 * http://de.php.net/manual/en/function.socket-create.php#49368
289 * @return $externalAddress The determined external address address
290 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
291 * @todo This should be moved out to an external class, e.g. HttpClient
292 * @todo Make IP, host name, port and script name configurable
294 public static function determineExternalAddress () {
295 // Get helper instance
296 $helperInstance = new ConsoleTools();
298 // First get a socket
299 // @TODO Add some DNS caching here
302 if ($helperInstance->isProxyUsed() === true) {
303 // Resolve hostname into IP address
304 $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
306 // Connect to host through proxy connection
307 $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
309 // Connect to host directly
310 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
313 // Check if there was an error else
316 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
319 // Prepare the GET request
320 $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
321 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
322 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
323 $request .= 'Connection: close' . self::HTTP_EOL;
326 if ($helperInstance->isProxyUsed() === true) {
328 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
329 // Setup proxy tunnel
330 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
332 // If the response is invalid, abort
333 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
335 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
338 // Add header for proxy
339 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
344 $request .= self::HTTP_EOL;
346 // Send it to the socket
347 fwrite($socketResource, $request);
349 // Init IP (this will always be the last line)
350 $externalAddress = 'invalid';
352 // And read the reply
353 while (!feof($socketResource)) {
355 $externalAddress = trim(fgets($socketResource, 128));
357 // Detect HTTP response
358 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
365 fclose($socketResource);
369 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
371 // Return determined external address
372 return $externalAddress;
376 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
377 * which indicates clearly that e.g. this script has been executed from
380 * @return $type The analyzed type, can be 'http' or 'console'
382 public static function analyzeEnvironmentForType () {
383 // Default is the console
386 // Now, do we have a request method, or query string set?
387 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
388 // Possibly HTTP request
397 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
398 * which indicates clearly that e.g. this script has been executed from
399 * console or web. This method should be used for class names, they
400 * currently are named differently. Here is a list to clarify this:
402 * Request type | Class type
403 * -----------------------------
407 * @return $type The analyzed type, can be 'http' or 'console'
409 public static function analyzeEnvironmentForClassType () {
410 // Default is the console
413 // Now, do we have a request method, or query string set?
414 if (self::analyzeEnvironmentForType() == 'http') {
415 // Possibly HTTP request