#!/usr/local/bin/perl
# ungopher - vacuum out gopher tunnels

# usage:
# ungopher [www style gopher reference]
# ungopher gopher://gopher.msen.com:70/cicnet

# original NNTP client suggested by eci386!clewis
# socket code mailed to me by cmf@obie.cis.pitt.edu (Carl M. Fongheiser)
# adaptation for gopher by emv@msen.com (Edward Vielmetti)

# Configuration information -- change to reflect your site.

$DEFAULTGOPHER='gopher://gopher.msen.com:70/';
$GOPHER=$ARGV[0] ? $ARGV[0] : $DEFAULTGOPHER ;

($host, $port, $path) = &parseref($GOPHER);

$DEBUG = 1;				# uh, if it don't work

print "$GOPHER\n" if ($DEBUG);
print "host=$host; port=$port; path=$path\n" if ($DEBUG);

if ($GOPHER) {

   require 'sys/socket.ph';

   $sockaddr = 'S n a4 x8';

   chop($hostname = `hostname`);

   ($name,$aliases,$proto) = getprotobyname('tcp');
   ($name,$aliases,$port) = getservbyname($port, 'tcp')
	unless $port =~ /^\d+$/;
   ($name,$aliases,$type,$len,$thisaddr) = gethostbyname($hostname);
   ($name,$aliases,$type,$len,$thataddr) = gethostbyname($host);

   $this = pack($sockaddr, &AF_INET, 0, $thisaddr);
   $that = pack($sockaddr, &AF_INET, $port, $thataddr);

   socket(N, &PF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
   bind(N, $this) || die "bind: $!";
   connect(N, $that) || die "connect: $!";

   $DEBUG && print "sending path=$path\n";
   send(N,"$path\r\n",0);
   print STDERR "$path\r\n" if ($DEBUG);
   while(<N>)  {
      chop;chop; 
      next if /^[\. ]*$/;
      s/^(.)// && ( $type = $1);
      @G= split(/\t/);
      print "Type=$type\n";
      print "Name=$G[0]\n";
      print "Path=$G[1]\n";
      print "Host=$G[2]\n";
      print "Port=$G[3]\n\n";
   }

   close(N);

}

sub parseref {
	# turn gopher://gopher.msen.com:70/cicnet/
	# into
	# host=gopher.msen.com; port=70; path=/cicnet/
	local($_) = @_;
	local($host, $port, $path);
	if (/^(gopher:\/\/)([^:]+):(\d+)(.*)$/) 
	    {
	    $host = $2;
	    $port=$3;
	    $path=$4;
	    }
	return($host, $port, $path);
}

