#!/usr/bin/perl -Tw
#
# HTTP port redirector
# Written by Ben Hemming and Andrew Pam
# Copyright (c) March 1997 Serious Cybernetics
# Last modified 29 May 1997 by Andrew Pam

require 5.002;
use strict;
BEGIN { $ENV{PATH} = '/bin' }
use Socket;
use Carp;

# ----- Configuration -----
my $host = "http://xanadu.com.au";
my $port = 8000;
my $logfile = "/var/log/redirect";
my $name_lookup = 1;			# Name lookup is slow!
# -------------------------

my $done = 0;
my $logging = 0;
my $paddr = 0;

sub DONE
{
  $done = 1;
  exit if not $paddr;
}

my $proto = getprotobyname('tcp');
socket(Server, PF_INET, SOCK_STREAM, $proto) 	or die "socket: $!";
setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
						or die "setsockopt: $!";
bind(Server, sockaddr_in($port, INADDR_ANY))	or die "bind: $!";
listen(Server, SOMAXCONN)			or die "listen: $!";

if (not open(LOGFILE, ">>$logfile"))
{ print "Warning: $!\n"; }
else
{
  select(LOGFILE);
  print scalar localtime, " $0 started on port $port, PID $$\n";
  $logging = 1;
}

$SIG{HUP} = $SIG{INT} = $SIG{TERM} = \&DONE;

while (not $done) {
	$paddr = 0;
        $paddr = accept(Client, Server) until $paddr;
	my ($port, $iaddr) = sockaddr_in($paddr);
	if ($logging)
	{
	  print scalar localtime;
	  my $name = gethostbyaddr($iaddr, AF_INET) if $name_lookup;
	  print " $name" if $name;
	  print " [", inet_ntoa($iaddr), "]: ";
	}

	$_ = <Client>;
	if (not defined $_)
	{
		print "<connection terminated>\n" if $logging;
	}
	else
	{
		chomp;
		chop if /\r$/;
		print "$_\n" if $logging;
		@_ = split;
		$_ = $_[1];	# We only want the second field
		# Check if it has URL & abs_address or just abs_address
		if (/^\//)
		{ $_ = "$host$_"; }
		else
		{ s/:$port//; }
		print Client ("HTTP/1.0 301 Permanently moved!\r\n".
			"Location: $_\r\n\r\n");
	}
        close Client;
}

END { print scalar localtime, " $0, PID $$ exited\n" if $logging; }
