#!/usr/bin/python

import os
import cgi
import sys

from config import MALWARE_FOLDER
from libutils import printHeader, dieError, isCleanFile, isCleanDir

cgiParameters = cgi.FieldStorage()

# Check to see that we have our required parameters
if not (cgiParameters.has_key("md5") and cgiParameters.has_key("dump")):
    print "Content-Type: text/html"
    print
    print "<H1>Error</H1>"
    print "No MD5 or dumped binary given."
else:
    md5  = cgiParameters.getvalue("md5")
    dump = cgiParameters.getvalue("dump")
    
    folder = MALWARE_FOLDER + os.sep + md5
    
    if not isCleanDir(md5):
        printHeader()
        print "Invalid directory"
        sys.exit(0)

    if not os.path.exists(folder):
        printHeader()
        dieError("Invalid path.")
        sys.exit(0)
    
    if not isCleanFile(dump):
        printHeader()
        dieError("Invalid filename.")
        sys.exit(0)

    print "Content-type: application/x-executable"
    print 'Content-Disposition: attachment; filename="%s.exe"' % dump
    print
    print file(folder + os.sep + dump, "rb").read()
