From: Stefan Schantl Date: Sun, 18 Jul 2021 09:59:22 +0000 (+0200) Subject: general-functions.pl: Refactor function to fetch the public IP address. X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=refs%2Fheads%2Fgeneral-functions-cleanup;p=people%2Fstevee%2Fipfire-2.x.git general-functions.pl: Refactor function to fetch the public IP address. Signed-off-by: Stefan Schantl --- diff --git a/config/cfgroot/general-functions.pl b/config/cfgroot/general-functions.pl index f2313fb43f..1eadaac79d 100644 --- a/config/cfgroot/general-functions.pl +++ b/config/cfgroot/general-functions.pl @@ -16,8 +16,6 @@ package General; use strict; use Socket; -use IO::Socket; -use Net::SSLeay; $|=1; # line buffering $General::version = 'VERSION'; @@ -993,23 +991,60 @@ sub srtarray } sub FetchPublicIp { - my %proxysettings; - &General::readhash("${General::swroot}/proxy/settings", \%proxysettings); - if ($_=$proxysettings{'UPSTREAM_PROXY'}) { - my ($peer, $peerport) = (/^(?:[a-zA-Z ]+\:\/\/)?(?:[A-Za-z0-9\_\.\-]*?(?:\:[A-Za-z0-9\_\.\-]*?)?\@)?([a-zA-Z0-9\.\_\-]*?)(?:\:([0-9]{1,5}))?(?:\/.*?)?$/); - Net::SSLeay::set_proxy($peer,$peerport,$proxysettings{'UPSTREAM_USER'},$proxysettings{'UPSTREAM_PASSWORD'} ); - } - my $user_agent = &MakeUserAgent(); - my ($out, $response) = Net::SSLeay::get_http( 'checkip4.dns.lightningwirelabs.com', - 80, - "/", - Net::SSLeay::make_headers('User-Agent' => $user_agent ) - ); - if ($response =~ m%HTTP/1\.. 200 OK%) { - $out =~ /Your IP address is: (\d+.\d+.\d+.\d+)/; - return $1; - } - return ''; + my %proxysettings; + + # URL to fetch the public IP. + my $url = "https://checkip4.dns.lightningwirelabs.com"; + + # Read-in proxy settings. + &General::readhash("${General::swroot}/proxy/settings", \%proxysettings); + + # Load required perl module to handle the HTTPS connect. + use LWP::UserAgent; + + # Init the download module. + my $agent = LWP::UserAgent->new; + + # Set timeout to 10 seconds. + $agent->timeout(10); + + # Check if an upstream proxy is configured. + if ($proxysettings{'UPSTREAM_PROXY'}) { + my $proxy_url; + + $proxy_url = "http://"; + + # Check if the proxy requires authentication. + if (($proxysettings{'UPSTREAM_USER'}) && ($proxysettings{'UPSTREAM_PASSWORD'})) { + $proxy_url .= "$proxysettings{'UPSTREAM_USER'}\:$proxysettings{'UPSTREAM_PASSWORD'}\@"; + } + + # Add proxy server address and port. + $proxy_url .= $proxysettings{'UPSTREAM_PROXY'}; + + # Setup proxy settings. + $agent->proxy(['http', 'https'], $proxy_url); + } + + # Send request to the URL. + my $response = $agent->get($url); + + # Check if a response has been recieved. + if ($response) { + # Grab public IP from response. + $response =~ /Your IP address is: (\d+.\d+.\d+.\d+)/; + + # Assign address to a nice variable. + my $public_ip = $1; + + # Check if the address is valid. + if (&Network::check_ip_address($public_ip)) { + # Return the public address. + return $public_ip; + } + } + + return undef; } #