#! /usr/local/bin/perl5

# startfarm.cgi                                  (c) Baris Temelkuran 00 

# Just sends the query from user to STARTfarm running on $farmserver $farmport

use strict;
use Socket;				 # Required for sockets.

# Default inputs: 
my %ENTRIES = ( farm => 'margarita.csail.mit.edu',

		server => 'ailab',
		machine => 'production',
		action => 'askstart',
		te => 'HTML' );

my $farmport=8013;


#< check if bad guy
my $REMOTE_HOST = $ENV{'REMOTE_HOST'};
my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
my $REMOTE_PORT = $ENV{'REMOTE_PORT'};
open(DENY, "askstart.deny");
while(<DENY>) { /^$REMOTE_ADDR/ && &cgidie("askstart: response denied.\n"); }
close(DENY);
#>

#< process the query string (why aren't we `use CGI;'-ing?) into %ENTRIES
my $qry;
if ($ENV{'REQUEST_METHOD'} eq 'GET') {	 # Parse the cgi query.
    $qry = $ENV{'QUERY_STRING'}; 
} else {
    read (STDIN, $qry, $ENV{'CONTENT_LENGTH'});
}
foreach (split (/\&/, $qry)) {
    s/\+/ /g;
    s/%(..)/pack ('H2', $1)/eg;
    if(s/^([^=]*)=//) {
	s/\\/\\\\/g;
#	s/"/\\"/g;
	my $var = $1;
	$var =~ tr/A-Z/a-z/;
	$ENTRIES{$var} = $_ if $_;
    }
}
#>

#< make sure we have a query, and escape quotes in it
unless ($ENTRIES{query}) {
    &cgidie("askstart: no query.\n\n<P>Please type your query in the input field and then click 'Ask Question'.");
}
$ENTRIES{"query"} =~ s/"/\\"/g;
#>

#< get a socket connection to the $farmserver
socket(S, AF_INET, SOCK_STREAM, 0) 	 # Open socket to start
    || &cgidie("socket: $!");
my ($name, $aliases, $type, $len, $addr)
    = gethostbyname($ENTRIES{farm});
connect(S, pack('S n a4 x8', AF_INET, $farmport, $addr))
    || &cgidie("connect: $!");

select(S); $| = 1; select('stdout');	 # remove buffering
#>

#< send parameters
print S "(\n";				              # Send a lambda list of:
print S ":remote-address \"$ENV{'REMOTE_ADDR'}\"\n";  # remote address,
foreach my $key (keys(%ENTRIES)) {		      # and all the other
    print S ":$key \"$ENTRIES{$key}\"\n";             # parameters.
}
print S ")";
#>

#< read and echo the response
print "Content-type: text/html\n\n";	 # HTTP header.
while(<S>) { print; }			 # Dump START's response.
close(S);				 # Close socket and die.
#>

#< cgidie  (instead of CGI::Carp)
sub cgidie {
    my ($header, $body) = @_;

    if ($body eq '') { $body = $header; $header = '' }
    if ($header eq '') { $header = "Error in processing your request"; }

    print <<EOF;
Content-type: text/html

<title> $header </title>
<h1> $header </h1>
$body
EOF
    exit(1);
}
#>




