#!/usr/bin/perl
# whois
# a web interface to whois queries
# (C) 2003-2005 Amir Malik. All Rights Reserved. http://www.unoc.net/a/
#
# 2004.12.23 amir - rewrote cgi portion
#
# TODO - IPv6 support

my %nics = qw(
arin	whois.arin.net
ripe	whois.ripe.net
apnic	whois.apnic.net
occaid	whois.occaid.org
internic	whois.internic.net
altdb	whois.altdb.net
);

require 'cgi-lib.pl';
$| = 1; $ENV{PATH} = ''; &ReadParse(*input);

print "Content-Type: text/html\r\n\r\n";

my $header = readFile('header.html');
$header =~ s/{TITLE}/UNOC : Whois Gateway/g;
$header =~ s/{ONLOAD}/onLoad=\"javascript:document.f.q.focus()\"/;

my $registry = $input{'r'};
my $query = $input{'q'};

print <<HTML;
$header

<h2>WHOIS Gateway</h2>

<form name="f" method="post" action="/cgi-bin/whois">
Registry: <select name="r">
  <option value="auto">Automatic</option>
HTML

foreach my $reg (sort keys %nics) {
  my $selected = '';
  $selected = ' selected="true"' if($registry eq $reg);
  print <<_EOF;
  <option value="$reg"$selected>$nics{$reg}</option>
_EOF
}

my $server = 'none';

if(exists($nics{$registry})) {
  $server = $nics{$registry};
}

print <<HTML;
</select><br/>
WHOIS: <input name="q" value="" />
<a href="javascript:void(0)" onClick='document.f.q.value="$query"; document.f.q.focus();'>$query</a>
</form>
HTML


if(@ARGV) {
  # for command line testing only
  $query = $ARGV[0];
}
    
if ((defined $query) and ($query ne "" )) {
    if ($query =~ /^t=(.*)/) {
	$query=$1;
    }
    if (($query =~ /^(\d+\.\d+\.\d+\.\d+)$/) or
	($query =~ /^([a-zA-Z0-9][a-zA-Z0-9\.\-_]*)$/)) {
	$query = $1;   # unTaint 
	
        $html .= "<hr/><pre>";
        print $html;
      if($registry eq 'auto') {
        system('/usr/bin/whois', $query);
      } elsif($server eq 'none') {
        print "Illegal server specified -- We're not that dumb.\n";
      } else {
        system('/usr/bin/whois', '-h', $server, $query);
      }
        $html = "</pre><hr/>";
    }
}

print $html;
print readFile("footer.html");

#print <<HTML;
#</body></html>
#HTML
#<ISINDEX>

sub readFile {
  open(FILE,"<$_[0]");
  my $txt;
  $txt .= $_ while(<FILE>);
  close(FILE);
  return $txt;
}
