#! /usr/bin/env python
# Class describing interception transferred through HI1
#
# Copyright (C) 2011 Matej Gregr, Michal Kajan, Libor Polcak,
#                    Vladimir Vesely, Petr Kramolis
#
# 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.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import getopt
import os
import scapy.all as scapy
import socket
import sys

from modules.shared.scapy_input import fill_LiPacket
from modules.sockets.li2 import connectUnixSocket

def scapy_callback(scapy_paket):
    p=fill_LiPacket(scapy_paket)
    if not p: # Non-IP or malformed packet
        return
    try:
        s.send(p)
    except socket.error:
        pass # Do not do anything, chances are that the main part already finished
    except Exception, e:
        sys.stderr.write("CC-IIF: %s\n" % str(e))

def help():
    print "-h \t\t print this help"
    print "-i <interface>\t sniff on given interface"
    print "-p <file>\t read pcap file"


if __name__ == "__main__":
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:p:", ["help", "interface=","pcap="])
    except getopt.GetoptError, err:
        sys.stderr.write(str(err) + "\n")
        help()
        sys.exit(2)

    if os.geteuid() != 0:
        sys.stderr.write("You must be root to run this script.\n")
        sys.exit(1)

    #open socket
    s = connectUnixSocket("/tmp/liptest")

    for o, a in opts:
        if o in("-i, --interface"):
            #use given interface
            sys.stderr.write("Using interface: %s\n" % a)
            scapy.sniff(prn=scapy_callback, iface=a ,store=0)
            sys.exit()

        elif o in ("-h", "--help"):
            help()
            sys.exit()

        elif o in ("-p,--pcap"):
            #read pcap
            sys.stderr.write("Reading pcap file: %s\n" % a)
            scapy.sniff(prn=scapy_callback, offline=a ,store=0)
            sys.exit()

    #capture packets on all interfaces
    scapy.sniff(prn=scapy_callback,store=0)
