#!/usr/bin/perl
# Most error checking left out for brevity.
require 5.0;
use Getopt::Std;

$proxy = $ENV{PROXY};
if ($proxy) { $auth = $ENV{PROXY_AUTH} }

$opt_b = $ENV{HTTPGET_BIND};
$opt_p = $proxy;
$opt_a = $auth;
getopts('p:r:h:a:b:vdq') || exit 1 ;
$proxy = $opt_p;
$header = $opt_h;
$auth = $opt_a;
$range = $opt_r;
$verbose = $opt_v;
$debug = $opt_d;
$quiet = $opt_q;
$bind= $opt_b;

$orig_url = @ARGV[0];

if ($proxy) {
  $url = $orig_url;
  $site = $proxy;
}
else {
  ($_) = $orig_url; ($site, $url) = /^http:\/\/([^\/]*)(\/.*)/;
}

$_ = $site; ($desthost, $port) = /([^:]*):*(.*)/;
$port = 80 unless $port;	# Default http port is 80

if ($verbose || $debug) {
    print stderr "desthost = $desthost ";
    print stderr "port = $port ";
    print stderr "url = $url \n";
    print stderr "auth = $auth \n";
    print stderr "bind = $bind \n";
}

use Socket;
$proto = (getprotobyname('tcp'))[2];
# Unless service is a number, look it up in /etc/services.
$port = (getservbyname($port, 'tcp'))[2] unless $port =~ /^\d+$/;
$thataddr = (gethostbyname($desthost))[4] || die "Unknown host '$desthost'";

# printf stderr "IP:  %s\n", inet_ntoa($thataddr);

# S: address family (unsigned short), n: port number (network order short),
# a4: network address (4 strings), x8: 8 nulls

# Create the connection to a remote server.
if ($debug) {
    $verbose = 1
}
else {
    $that = pack('S n a4 x8', AF_INET, $port, $thataddr);
    socket(S, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
    if ($bind) {
	$myaddr = (gethostbyname($bind))[4] ||
	    die "Unknown bind address '$bind' $!";
	$me=pack('S n a4 x8', AF_INET, 0, $myaddr);
	bind(S, $me) || die "bind: $!";
    }
    connect(S, $that) || die "connect: $!";
    select(S); $| = 1;
}

# Send request to get the document.
print S "GET $url HTTP/1.0\r\n";
print S "Host: $desthost\r\n";
if ($range) { print S "Range: bytes=$range \r\n" }
if ($auth) { print S "Proxy-Authorization: $auth \r\n" }
if ($header) { print S "$header\r\n" }
print S "\r\n";

if ($verbose) {
    print stderr "GET $url HTTP/1.0\r\n";
    print stderr "Host: $desthost\r\n";
    if ($range) { print stderr "Range: bytes=$range \r\n" }
    if ($auth) { print stderr "Proxy-Authorization: $auth \r\n" }
    if ($header) { print stderr "$header \r\n" }
    print stderr "\r\n";
}

# Read Header and send to stderr
select(stderr) ;	# Send Header to stderr
$first_line=1;
while(<S>) {
    if (! $quiet || $first_line == 1) { print ; $first_line = 0 }
    if (($good == 1) && ( /^*$/ )) {
	last;
    }
    if ( /*$/ ) {
	$good = 1 ;
    }
    else {
	$good = 0 ;
    }
}

# Read Body and send to stdout
select(stdout);		# Send body to stdout
while(<S>) { print; }
