from scapy.all import * 
import socket
import sys
import time
import hashlib

def compute_checksums(file_path):
    sha512_hash = hashlib.sha512()
    md5_hash = hashlib.md5()
    try:
        with open(file_path, "rb") as f:
            while chunk := f.read(8192):
                sha512_hash.update(chunk)
                md5_hash.update(chunk)
    except FileNotFoundError:
        print(f"Error: File not found - {file_path}")
        return
    sha512_digest = sha512_hash.hexdigest()
    md5_digest = md5_hash.hexdigest()
    print(f"MD5: {md5_digest}")
    print(f"SHA-512: {sha512_digest}")


def main():
	if len(sys.argv) > 1: 
		try:
			bpf: str = 'tcp and src host 192.168.86.228 and src port 5000 and dst host 192.168.86.167'
			packets: PacketList = sniff(offline = sys.argv[1], filter=bpf, session = TCPSession)
		except:
			print("File read failure: %s not found" % sys.argv[1])
			sys.exit(1)
	else:
		print("Need a pcap file to read!")
		sys.exit(1)
	raw_packets: PacketList = packets[Raw]
	byte_accum = b''
	count = 0
	for i in range(0, len(raw_packets)):
		raw_packet: Packet = raw_packets[i]
		if b"Content-Type" in raw_packet[Raw].load:
			top_payload: bytes = raw_packet[Raw].load.split(b'\r\n')[-1]
			bottom_payload: bytes = b''
			if i+1 < len(raw_packets):
				raw_packet_2: Packet = raw_packets[i+1]
				bottom_payload: bytes = raw_packet_2[Raw].load
			count += 1
			byte_accum = byte_accum + base64_bytes(top_payload + bottom_payload) 
	file = open('download.bin','wb')
	file.write(byte_accum)
	print('done: ' ,count, ' packets decoded and packets written to download.bin')
	compute_checksums('download.bin')

if __name__ == '__main__':
	main()