3 namespace Org\Mxchange\CoreFramework\Console\Tools;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
9 use Org\Mxchange\CoreFramework\Generic\FrameworkException;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
11 use Org\Mxchange\CoreFramework\Socket\InvalidSocketException;
17 * This class contains static helper functions for console applications
19 * @author Roland Haeder <webmaster@shipsimu.org>
21 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Hub Developer Team
22 * @license GNU GPL 3.0 or any newer version
23 * @link http://www.shipsimu.org
25 * This program is free software: you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation, either version 3 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 class ConsoleTools extends BaseFrameworkSystem {
40 const HTTP_EOL = "\r\n";
41 const HTTP_USER_AGENT = 'ConsoleTools/1.0';
44 * Default is that this class is noisy
46 private static $quietResolver = FALSE;
49 * Protected constructor
53 protected function __construct () {
54 // Call parent constructor
55 parent::__construct(__CLASS__);
57 // Cache configuration entry
58 self::$quietResolver = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('quiet_dns_resolver');
62 * Checks wether proxy configuration is used
64 * @return $isUsed Wether proxy is used
66 protected function isProxyUsed () {
68 if (!isset($GLOBALS[__METHOD__])) {
70 $GLOBALS[__METHOD__] = (($this->getConfigInstance()->getConfigEntry('proxy_host') != '') && ($this->getConfigInstance()->getConfigEntry('proxy_port') > 0));
74 return $GLOBALS[__METHOD__];
78 * Sets up a proxy tunnel for given hostname and through resource
80 * @param $host Host to connect to
81 * @param $port Port number to connect to
82 * @param $socketResource Resource of a socket
83 * @return $response Response array
85 protected function setupProxyTunnel ($host, $port, $socketResource) {
87 $response = array('', '', '');
90 // Generate CONNECT request header
91 $proxyTunnel .= 'CONNECT ' . $host . ':' . $port . ' HTTP/1.1' . self::HTTP_EOL;
92 $proxyTunnel .= 'Host: ' . $host . ':' . $port . self::HTTP_EOL;
93 $proxyTunnel .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
95 // Use login data to proxy? (username at least!)
96 if ($this->getConfigInstance()->getConfigEntry('proxy_username') != '') {
98 $encodedAuth = base64_encode($this->getConfigInstance()->getConfigEntry('proxy_username') . ':' . $this->getConfigInstance()->getConfigEntry('proxy_password'));
99 $proxyTunnel .= 'Proxy-Authorization: Basic ' . $encodedAuth . self::HTTP_EOL;
103 $proxyTunnel .= self::HTTP_EOL;
104 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: proxyTunnel=' . $proxyTunnel);
107 fwrite($socketResource, $proxyTunnel);
110 if (feof($socketResource)) {
111 // No response received
115 // Read the first line
116 $resp = trim(fgets($socketResource, 10240));
117 $respArray = explode(' ', $resp);
118 if (((strtolower($respArray[0]) !== 'http/1.0') && (strtolower($respArray[0]) !== 'http/1.1')) || ($respArray[1] != '200')) {
128 * 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
130 * @param $rawData Raw data from /etc/hostname file
131 * @return $hostname Extracted host name
133 protected function extractHostnameFromRawData ($rawData) {
134 // Default is invalid
135 $hostname = 'invalid';
137 // Try to "explode" it
138 $data = explode(PHP_EOL, $rawData);
141 foreach ($data as $line) {
145 // Begins with a hash (#) = comment?
146 if (substr($line, 0, 1) == '#') {
151 // Has an equals sign?
152 if (strpos($line, '=') !== false) {
153 // Then "explode" it again, right part is hostname in quotes
154 $hostData = explode('=', $line);
156 // Make sure only a key=value pair goes through
157 assert(count($hostData) == 2);
159 // Try to get it and abort
160 $hostname = str_replace(array('"', chr(39)), array('', ''), $hostData[1]);
174 * Tries to resolve an IP address from given hostname. Currently only IPv
175 * addresses are resolved.
177 * @param $hostname Host name we shall resolve
178 * @return $ipAddress IPv4 address resolved from host name
179 * @todo This should be connected to a caching class to cache DNS requests
181 public static function resolveIpAddress ($hostname) {
183 if (self::$quietResolver !== TRUE) {
185 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s',
194 // Is a dot at the end?
195 if (substr($hostname, -1, 1) != '.') {
197 * Then append it to prevent lookup of invalid host names through
198 * all search-domains. This will greatly improve lookup performance
199 * and has no disadvantages for anybody. A dot at the end of a
200 * domain btw means full-qualified domain, do not prepend to any
201 * other domain, basically.
207 // @TODO Here should the cacher be implemented
208 $ipResolved = gethostbyname($hostname);
211 if (($ipResolved !== false) && ($ipResolved != $hostname)) {
213 $ipAddress = $ipResolved;
216 if (self::$quietResolver !== TRUE) {
218 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s',
224 // Problem while resolving IP address
225 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.',
231 // Return resolved IP
236 * Aquires the IP address of this host by reading the /etc/hostname file
237 * and solving it. It is now stored in configuration
239 * @return $ipAddress Aquired IPv4 address
241 public static function acquireSelfIpAddress () {
242 // Local IP by default
243 $ipAddress = '127.0.0.1';
245 // Get a new instance
246 $helperInstance = new ConsoleTools();
248 // Get SplFileInfo instance
249 $infoInstance = new SplFileInfo($helperInstance->getConfigInstance()->getConfigEntry('hostname_file'));
252 // Get a file pointer
253 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
256 $rawData = trim($fileInstance->readFromFile());
259 $fileInstance->closeFile();
261 // Extract hostname from it
262 $hostname = $helperInstance->extractHostnameFromRawData($rawData);
264 // Resolve the IP number
265 $ipAddress = self::resolveIpAddress($hostname);
266 } catch (FileNotFoundException $e) {
267 // Fall-back to 'SESSION_SVR' which found on my Sun Station
268 if (isset($_SERVER['SESSION_SVR'])) {
270 $ipAddress = self::resolveIpAddress($_SERVER['SESSION_SVR']);
271 } elseif (isset($_SERVER['COMPUTERNAME'])) {
272 // May happen on some Windows XP systems, so also try this
273 $ipAddress = self::resolveIpAddress($_SERVER['COMPUTERNAME']);
275 // Could not find our hostname
276 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot resolve my own IP address.',
277 $helperInstance->__toString()
280 } catch (FrameworkException $e) {
281 // Output debug message
282 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s',
283 $helperInstance->__toString(),
295 * Determines own remote IP address (e.g. can be used to probe if we are
296 * reachable from outside by determining external address and then connect to it.
297 * This is accomblished by connecting to the IP of www.shipsimu.org which
298 * should default to 188.138.90.169 and requesting /ip.php which does only
299 * return the content of $_SERVER['REMOTE_ADDR']. Of course, this method
300 * requires a working Internet connection.
302 * This method is taken from a user comment on php.net and heavily rewritten.
303 * Compare to following link:
304 * http://de.php.net/manual/en/function.socket-create.php#49368
306 * @return $externalAddress The determined external address address
307 * @throws InvalidSocketException If socket initialization wents wrong or if an errors occurs
308 * @todo This should be moved out to an external class, e.g. HttpClient
309 * @todo Make IP, host name, port and script name configurable
311 public static function determineExternalAddress () {
312 // Get helper instance
313 $helperInstance = new ConsoleTools();
315 // First get a socket
316 // @TODO Add some DNS caching here
319 if ($helperInstance->isProxyUsed() === true) {
320 // Resolve hostname into IP address
321 $ipAddress = self::resolveIpAddress($helperInstance->getConfigInstance()->getConfigEntry('proxy_host'));
323 // Connect to host through proxy connection
324 $socketResource = fsockopen($ipAddress, $helperInstance->getConfigInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30);
326 // Connect to host directly
327 $socketResource = fsockopen('188.138.90.169', 80, $errorNo, $errorStr, 30);
330 // Check if there was an error else
333 throw new InvalidSocketException(array($helperInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET);
336 // Prepare the GET request
337 $request = 'GET ' . ($helperInstance->isProxyUsed() === true ? 'http://shipsimu.org' : '') . '/ip.php HTTP/1.0' . self::HTTP_EOL;
338 $request .= 'Host: shipsimu.org' . self::HTTP_EOL;
339 $request .= 'User-Agent: ' . self::HTTP_USER_AGENT . self::HTTP_EOL;
340 $request .= 'Connection: close' . self::HTTP_EOL;
343 if ($helperInstance->isProxyUsed() === true) {
345 if ($helperInstance->getConfigInstance()->getConfigEntry('proxy_connect_method') == 'Y') {
346 // Setup proxy tunnel
347 $response = $helperInstance->setupProxyTunnel('shipsimu.org', 80, $socketResource);
349 // If the response is invalid, abort
350 if ((count($response) == 3) && (empty($response[0])) && (empty($response[1])) && (empty($response[2]))) {
352 $helperInstance->debugBackTrace('Proxy tunnel not working: response=' . print_r($response, true));
355 // Add header for proxy
356 $request .= 'Proxy-Connection: Keep-Alive' . self::HTTP_EOL;
361 $request .= self::HTTP_EOL;
363 // Send it to the socket
364 fwrite($socketResource, $request);
366 // Init IP (this will always be the last line)
367 $externalAddress = 'invalid';
369 // And read the reply
370 while (!feof($socketResource)) {
372 $externalAddress = trim(fgets($socketResource, 128));
374 // Detect HTTP response
375 if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) {
382 fclose($socketResource);
386 /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS[' . __METHOD__ . ':' . __LINE__ . ']: Resolved external address: ' . $externalAddress);
388 // Return determined external address
389 return $externalAddress;
393 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
394 * which indicates clearly that e.g. this script has been executed from
397 * @return $type The analyzed type, can be 'http' or 'console'
399 public static function analyzeEnvironmentForType () {
400 // Default is the console
403 // Now, do we have a request method, or query string set?
404 if ((isset($_SERVER['REQUEST_METHOD'])) || (isset($_SERVER['QUERY_STRING']))) {
405 // Possibly HTTP request
414 * Analyzes the 'environment', mostly $_SERVER, for presence of elements
415 * which indicates clearly that e.g. this script has been executed from
416 * console or web. This method should be used for class names, they
417 * currently are named differently. Here is a list to clarify this:
419 * Request type | Class type
420 * -----------------------------
424 * @return $type The analyzed type, can be 'http' or 'console'
426 public static function analyzeEnvironmentForClassType () {
427 // Default is the console
430 // Now, do we have a request method, or query string set?
431 if (self::analyzeEnvironmentForType() == 'http') {
432 // Possibly HTTP request