'''
webscan.py, sagator's web scanner

(c) 2003-2004 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>
 
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

Add these lines to apache configuration:
  AddHandler mod_python .py
  PythonHandler mod_python.publisher
  PythonPath "sys.path+['/usr/lib/sagator']"

If you need another configuration for sagator, please copy your
sagator to another directory and change it's config file.

'''

from aglib import *
import types

# load config
from default import *
try:
  from config import *
except ImportError,es:
  if str(es)[-6:]=="config":
    print "ERROR! Config file not found! Exiting now."
    sys.exit(1)
  else:
    raise

def form(req,num=1):
    req.write('<form action="webscan.py" method=post enctype="multipart/form-data">\n')
    for i in range(num,0,-1):
      req.write('<input type=file name=file%04d size=80><br>\n' % i)
    req.write('<input type=submit>\n</form>')
    return ''

class io:
  def __init__(self,req):
      self.req=req
  def write(self,s):
      self.req.write(s+"<br>")

def index(req,**args):
    req.content_type='text/html'
    req.write("<h3>WebSagator %s-%s</h3>\n" % (version.VERSION,version.RELEASE))
    if req.method == 'GET':
      try:
        return form(req,int(args['n']))
      except:
        return form(req)
    debug.set_level(1)
    debug.logfd=io(req)
    for scnr in SCANNERS:
      scnr.reinit()
    for file in args.values():
      if type(file) == types.InstanceType:
        globals.reset()
        mail.filename=file.filename
        mail.data=file.file.read()
        mail.comm="NOOP WEBSAGATOR, remote host: %s" \
          % (req.get_remote_host(2))
        d=''
        for scnr in SCANNERS:
          level,detected,virlist,scan_reply,err=do_scan(scnr)
          if is_infected(level,detected):
            d="[%s,%0.2f]" % (globals.found_by.name,level)
            break
        if d:
          req.write("%s: <font color=red>%s</font> %s<br>\n" \
            % (mail.filename,detected,d))
        else:
          req.write("%s: no virus detected<br>\n" % mail.filename)
    return ''
