# Path: fjospidie/Utils.py
# def get_md5(data):
#     """
#     Get the MD5sum of the passed data
#     """
#     md5 = hashlib.md5()
#     md5.update(data)
#     return md5.hexdigest()


import logging
import tempfile
import pcap
import subprocess
import threading
from fjospidie.Utils import get_md5

class PcapEngine(threading.Thread):

    def __init__(self, spidie, pcap_folder):
        threading.Thread.__init__(self)
        self.pcap_path = None
        self.spidie = spidie
        self.pcap_folder = pcap_folder
        self.logger = logging.getLogger(__name__)

    def run(self):
        self.logger.info("Starting PCAP engine")
        self.p = pcap.pcapObject()
        snaplen = 64 * 1024
        timeout = 1
        if 'bpf' in self.spidie.config:
            bpf = "{} and not (host {} and port {})".format(
                self.spidie.config.bpf, self.spidie.config.database_host, self.spidie.config.database_port)
        else:
            bpf = "not (host {} and port {})".format(self.spidie.config.database_host, self.spidie.config.database_port)

        pcap_file = tempfile.NamedTemporaryFile(prefix="suricata", suffix="pcap", delete=False, dir=self.pcap_folder)
        self.pcap_path = pcap_file.name
        self.logger.debug("PCAPing to " + self.pcap_path)
        dev = self.find_default_adapter()
        self.p.open_live(dev, snaplen, 0, timeout)
        self.p.setfilter(bpf, 0, 0)

# Path: fjospidie/Utils.py
# def get_md5(data):
#     """
#     Get the MD5sum of the passed data
#     """
#     md5 = hashlib.md5()
#     md5.update(data)
#     return md5.hexdigest()


# Path: fjospidie/engine/PcapEngine.py
import logging
import tempfile
import pcap
import subprocess
import threading
from fjospidie.Utils import get_md5


class PcapEngine(threading.Thread):

    def __init__(self, spidie, pcap_folder):
        threading.Thread.__init__(self)
        self.pcap_path = None
        self.spidie = spidie
        self.pcap_folder = pcap_folder
        self.logger = logging.getLogger(__name__)

    def run(self):
        self.logger.info("Starting PCAP engine")
        self.p = pcap.pcapObject()
        snaplen = 64 * 1024
        timeout = 1
        if 'bpf' in self.spidie.config:
            bpf = "{} and not (host {} and port {})".format(
                self.spidie.config.bpf, self.spidie.config.database_host, self.spidie.config.database_port)
        else:
            bpf = "not (host {} and port {})".format(self.spidie.config.database_host, self.spidie.config.database_port)

        pcap_file = tempfile.NamedTemporaryFile(prefix="suricata", suffix="pcap", delete=False, dir=self.pcap_folder)
        self.pcap_path = pcap_file.name
        self.logger.debug("PCAPing to " + self.pcap_path)
        dev = self.find_default_adapter()
        self.p.open_live(dev, snaplen, 0, timeout)
        self.p.setfilter(bpf, 0, 0)

        dumper = self.p.dump_open(self.pcap_path)