#!/usr/bin/perl

# Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM)
# Published By SunSoft Press/Prentice-Hall
# Copyright (C) 1996 Sun Microsystems Inc.
# All Rights Reserved. ISBN 0-13-596891-7
# 
# Permission to use, copy, modify, and distribute this 
# software and its documentation for NON-COMMERCIAL purposes
# and without fee is hereby granted provided that this 
# copyright notice appears in all copies. 
# 
# THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR 
# WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER 
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
# AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED 
# BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING 
# THIS SOFTWARE OR ITS DERIVATIVES.

# Version 1.00 07 Feb 1996 
# Author Cay Horstmann

($url) = @ARGV;

$url =~ tr/+/ /;
$url =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; 

$pos = index($url, "://");

if ($pos < 0) 
{  die $url." Sorry--can only recognize service://server/file";
}

$service_name = substr($url, 0, $pos);

if ($service_name eq "http") 
{  $port = 80;
} 
elsif ($service_name eq "gopher") 
{  $port = 70;
}
else 
{  die "Sorry--can only recognize http and gopher";
}

$pos += 3;
$pos2 = index($url, "/", $pos);
if ($pos2 < 0) 
{  die "Sorry--can only recognize service://server/file";
}

$server_name = substr($url, $pos, $pos2 - $pos);
$file_name = substr($url, $pos2);
$AF_INET = 2;
$SOCK_STREAM =1;

$sockaddr = 'S n a4 x8';

($name, $aliases, $proto) = getprotobyname ('tcp');
($name,$aliases,$type,$len,$thataddr) 
   = gethostbyname($server_name);
$that = pack($sockaddr, $AF_INET, $port, $thataddr);

if (!socket (S, $AF_INET, $SOCK_STREAM, $proto))
{  die $!;
}

if (!connect (S, $that)) 
{  die $!;
}

select(S); $|=1; select(STDOUT);

if ($service_name == "http") 
{  $command = "GET ".$file_name;
}
elsif ($service_name == "gopher")
{   $command = $file_name;
}

print S $command."\r\n";

print "Content-type: text/html\n\n";
while (<S>)
{  print;
}


