#!/usr/bin/env python
# Copyright (C) 2015 Jurriaan Bremer <jbr@cuckoo.sh>
# This file is part of HTTPReplay - http://jbremer.org/httpreplay/
# See the file 'LICENSE' for copying permission.

import argparse
import logging

import httpreplay.cobweb
import httpreplay.misc
import httpreplay.reader
import httpreplay.smegma
import httpreplay.test

from httpreplay.cut import (
    http_handler, https_handler, smtp_handler
)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("pcapfile", type=str, help="PCAP file")
    parser.add_argument("tlsmaster", type=str, nargs="?", help="TLS master secrets file")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)
    log = logging.getLogger(__name__)

    if args.tlsmaster:
        tlsmaster = httpreplay.misc.read_tlsmaster(args.tlsmaster)
    else:
        tlsmaster = {}

    handlers = {
        25: smtp_handler,
        80: http_handler,
        8000: http_handler,
        8080: http_handler,
        443: lambda: https_handler(tlsmaster),
        4443: lambda: https_handler(tlsmaster),
    }

    if args.pcapfile == "test":
        httpreplay.test.test_suite()

    reader = httpreplay.reader.PcapReader(args.pcapfile)
    reader.tcp = httpreplay.smegma.TCPPacketStreamer(reader, handlers)

    for s, ts, protocol, sent, recv in reader.process():
        print s, "%f" % ts, protocol, getattr(sent, "uri", None)
