| """Streaming pcap (libpcap, not pcapng) repair: copies valid records and, on a corrupt record header, scans forward for the next | |
| plausible record (incl<=snaplen, incl<=orig<=262144, |ts - last_ts| < 1 day, and the record after it is also plausible). | |
| Some CSE-CIC-IDS2018 per-host pcaps contain such garbage blocks. Returns stats dict.""" | |
| import struct | |
| def _ok(h, last_ts, snap): | |
| ts, us, incl, orig = h | |
| return incl <= snap and incl <= orig <= 262144 and us < 1000000 and (last_ts is None or abs(ts - last_ts) < 86400) | |
| def repair(src, dst, chunk=16 << 20): | |
| gh = src.read(24) | |
| if len(gh) < 24: return dict(ok=False, error="short") | |
| magic = gh[:4] | |
| if magic == b"\xd4\xc3\xb2\xa1" or magic == b"\x4d\x3c\xb2\xa1": e = "<" | |
| elif magic == b"\xa1\xb2\xc3\xd4" or magic == b"\xa1\xb2\x3c\x4d": e = ">" | |
| else: return dict(ok=False, error=f"not a libpcap file (magic {magic.hex()})") | |
| snap = struct.unpack(e + "I", gh[16:20])[0] or 65535; snap = min(max(snap, 65535), 262144) | |
| dst.write(gh) | |
| buf = b""; pos = 0; eof = False; last_ts = None; n = 0; resyncs = 0; skipped = 0; H = struct.Struct(e + "IIII") | |
| def fill(need): | |
| nonlocal buf, pos, eof | |
| if len(buf) - pos >= need or eof: return | |
| more = src.read(max(chunk, need)); buf = buf[pos:] + more; pos = 0 | |
| if not more: eof = True | |
| out = bytearray() | |
| while True: | |
| fill(16) | |
| if len(buf) - pos < 16: break | |
| h = H.unpack_from(buf, pos) | |
| if _ok(h, last_ts, snap): | |
| fill(16 + h[2]) | |
| if len(buf) - pos < 16 + h[2]: break # truncated last record | |
| out += buf[pos:pos + 16 + h[2]]; pos += 16 + h[2]; last_ts = h[0]; n += 1 | |
| if len(out) > chunk: dst.write(out); out = bytearray() | |
| continue | |
| # resync: slide byte by byte until two consecutive plausible headers | |
| resyncs += 1; start = pos; found = False | |
| while True: | |
| pos += 1; fill(16 + 65535 + 16) | |
| if len(buf) - pos < 16: break | |
| h = H.unpack_from(buf, pos) | |
| if _ok(h, last_ts, snap) and len(buf) - pos >= 32 + h[2]: | |
| if _ok(H.unpack_from(buf, pos + 16 + h[2]), h[0], snap): found = True; break | |
| elif _ok(h, last_ts, snap) and eof and len(buf) - pos == 16 + h[2]: found = True; break | |
| skipped += pos - start | |
| if not found: break | |
| dst.write(out) | |
| return dict(ok=True, packets=n, resyncs=resyncs, skipped_bytes=skipped) | |
Xet Storage Details
- Size:
- 2.47 kB
- Xet hash:
- 78119987a1cc001c047b2f9aa1994d711f0816063ecf683941904d37fd7a4f44
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.