#!/usr/bin/perl

# $Id: wcat,v 1.1 2002/09/05 06:01:10 misaka Exp $

# This is a quick hack written by Misha Gorodnitzky to 'cat' out contents
# of a given URL.  Run 'wcat' with the desired URL on the cmdline, and
# it'll spit out whatever contents are to be found there.
#
# Copyright Misha Gorodnitzky <misaka@pobox.com>, 2002, licensed
# under the Perl Artistic License see
# http://www.perl.com/language/misc/Artistic.html for details.  You
# use, you enjoy, you take responsability for the use of this program
# yourself, since you can view the code and see what's good/bad about
# it.
#
# Feel free to send me improvements and modifications, I'll give due
# credit, etc.

use IO::Socket::INET;
use Getopt::Long;


my( $url );
my( $socket, $protocol, $host, $port, $path );
my( @header );
my( $arg_header, $arg_all, $arg_verbose );

GetOptions( 'header!'  => \$arg_header,
	    'all!'     => \$arg_all,
	    'verbose!' => \$arg_verbose );

$url = shift( @ARGV );

if( $url =~ m|^(\w+)://([\w0-9\.-]+)(:(\d+))?(/.*)?$| ) {
    $protocol = $1;
    $host = $2;
    $port = $4;
    $path = $5 || '/';
} else {
    die( "$url doesn't look like a url to me." );
}

if( !$port ) {

    if( $protocol eq 'http' ) {
	$port = 80;
    } else {
	die( "$protocol is an unsupported protocol, sorry." );
    }

}

if( @ARGV ) {
    $server = shift( @ARGV );
    $path = "http://$host:$port$path";
    $port = 80;
} else {
    $server = $host;
}

$socket = new IO::Socket::INET ( PeerAddr => $server,
				 PeerPort => $port,
				 Proto    => 'tcp' )
    or die( "Unable to connect to $server:$port" );

print( "Connected to $server:$port.\n" )
  if( $arg_verbose );

print( "Sending: GET $path HTTP/1.0\n" )
  if( $arg_verbose );
$socket->print( "GET $path HTTP/1.0\r\n" );

print( "Sending: Host: $host:$port\n" )
  if( $arg_verbose );
$socket->print( "Host: $host:$port\r\n",
		"\r\n" );

print( "Waiting for header.\n" )
  if( $arg_verbose );

my( $line );
while( $line = <$socket> ) {
    $line =~ s/\r?\n?$//;
    print( $line . "\n" ) if( $arg_header or $arg_all );
    last if( $line =~ m/^\s*$/ );
}

print( "Finished header.\n" )
  if( $arg_verbose );

while( $line = <$socket> ) {
    print( $line ) if( $arg_all or !$arg_header );
}
