#!/usr/bin/python 
#-*- coding: utf-8 -*-
#	Copyright (c) 2009 Plecno s.r.l. All Rights Reserved 
#	info@plecno.com
#	via Giovio 8, 20144 Milano, Italy
#	Released under the terms of the GPLv3 or later
#	Author: Oreste Notelli <oreste.notelli@plecno.com>	

import subprocess
import sys
from optparse import OptionParser
import pwd
import os

default_parser_script="/usr/share/justniffer/scripts/http_parser.py"

parser = OptionParser(version="%prog 0.1")
parser.add_option("-d", "--directory", dest="directory",
                  help="MANDATORY: directory where to save files")
parser.add_option("-p", "--packet-filter", dest="packet_filter",
                  help="packet filter (tcpdump filter syntax), default ='port 80'", default="\"port 80\"")
parser.add_option("-U", "--user", dest="user",
                  help="user to impersonate when saving files, cannot be root user")
parser.add_option("-i", "--interface", dest="interface",
                  help="network interface to listen on (e.g. eth0, en1, etc.)")
parser.add_option("-f", "--filecap", dest="filecap",
                  help="input file in 'tcpdump capture file format'")
parser.add_option("-P", "--parser_script", dest="parser_script", default =default_parser_script,
                  help="parser script to execute, default is /usr/share/justniffer/scripts/http_parser.py")

(options, args) = parser.parse_args()

if (options.directory == None):
  parser.print_help()
  sys.exit(-1)

options_to_pass=list()

def check(opt, str_opt, options_to_pass):
  if (opt):
    options_to_pass.append(str_opt)
    options_to_pass.append(opt)

def check_user(opt, options_to_pass):
  name = opt
  if (opt == None) :
    uid = os.getuid()
    name = pwd.getpwuid(uid)[0]
  else:
    try:
      uid = pwd.getpwnam(opt)[2]
    except KeyError:
      print "ERROR: user "+opt+ " not found"
      print
      parser.print_help()
      sys.exit(-1)
      
  if (uid== 0):
    print
    print "ERROR: you must specify a no root user (-U <username>)"
    print
    parser.print_help()
    sys.exit(-1)
  check(name, "-U", options_to_pass)
    
    
check(options.interface, "-i", options_to_pass)
check(options.filecap, "-f", options_to_pass)
check(options.packet_filter, "-p", options_to_pass)
check_user(options.user, options_to_pass)
options_to_pass.append("-r")
options_to_pass.append("-e")
options_to_pass.append('"'+options.parser_script+' -d '+options.directory+'"')
options_to_pass.insert(0, "justniffer")
result = subprocess.call(options_to_pass)

