#!/usr/local/bin/python

# This very generic CGI script does nothing but sending a query and its
# environment settings as python readable dictionaries to a server process
# and piping the answer to stdout. Note that the server output must contain
# the appropriate content headers.

import cgi, re, socket
import os, sys, string

# Edit this configure file. It contains the server addresses and the
# server access error page.
import CallConf

# Look for values from form:
form = cgi.FieldStorage(keep_blank_values=1)

# open the log file and log request
import time

ENV = os.environ
logstr = ''
if ENV.has_key('REMOTE_ADDR'):
  logstr = logstr + ENV['REMOTE_ADDR'] + ';'
logstr = logstr + time.ctime() + ';'
if ENV.has_key('HTTP_USER_AGENT'):
  logstr = logstr + ENV['HTTP_USER_AGENT'] + ';'
c = form.getvalue('command') 
if c == None:
  c = 'NO COMMAND'
logstr = logstr + c
logstr = logstr + '\n'
log = open(CallConf.LOGFILE, 'a')
log.write(logstr)
log.close()

# Try connecting the server:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
nrserv = len(CallConf.SERVERS)
while nrserv:
  nrserv -= 1
  try:
    s.connect(CallConf.SERVERS[nrserv])
  except socket.error:
    if nrserv == 0:
      print CallConf.NoConnectPage 
      sys.exit(0)
    else:
      continue
  break
  

# rewrite the form object as dictionary  
#XXX do we need to escape certain characters?
sendstr = ['CGIQUERY = {'];

# write form values to python readable dictionary with string components
for k in form.keys():
  val = form.getvalue(k)                          # re.escape(form.getvalue(k))
  # check validity of k, first truncate, then escape non-alpha-numerics
  if len(k) > 1000:
    k = k[:1000]
                                                  # k = re.escape(k)
  sendstr[len(sendstr):] = [ '\'', k , '\' : \'', val, '\',\n']
sendstr.append('}\n')

# add the environment settings
sendstr[len(sendstr):] = ['ENV = ', str(os.environ), '\n' ]

# mark the end of the input
sendstr.append('\nENDCGIINPUT\n')

# join
sendstr = "".join(sendstr)

# now send the command:
s.send(sendstr)

# pipe the answer to stdout
chunk = s.recv(100000)
while chunk:
    sys.stdout.write(chunk)
    chunk = s.recv(100000)

s.shutdown(2)

sys.exit(0)

