| 1 |
#!/usr/bin/python |
| 2 |
import argparse |
| 3 |
import sys |
| 4 |
|
| 5 |
import dns.exception |
| 6 |
import dns.message |
| 7 |
|
| 8 |
|
| 9 |
def main(): |
| 10 |
parser = argparse.ArgumentParser( |
| 11 |
description="Read sequence of DNS wire formats prefixed with 2-byte " |
| 12 |
"length field - like from TCP socket - and print the messages. This " |
| 13 |
"format is used e.g. by dnsperf -B option and dnsgen." |
| 14 |
) |
| 15 |
parser.add_argument("infile") |
| 16 |
args = parser.parse_args() |
| 17 |
ok_msgs = 0 |
| 18 |
bad_msgs = 0 |
| 19 |
|
| 20 |
with open(args.infile, "rb") as infile: |
| 21 |
while True: |
| 22 |
offset = infile.tell() |
| 23 |
len_wire = infile.read(2) |
| 24 |
if len(len_wire) == 0: # end of file - expected |
| 25 |
break |
| 26 |
if len(len_wire) == 1: |
| 27 |
raise ValueError("incomplete length preamble, offset", offset) |
| 28 |
len_msg = int.from_bytes(len_wire, byteorder="big", signed=False) |
| 29 |
print(f"; msg offset 0x{offset + 2:x}, length {len_msg} bytes") |
| 30 |
msg_wire = infile.read(len_msg) |
| 31 |
if len(msg_wire) != len_msg: |
| 32 |
raise ValueError( |
| 33 |
f"incomplete message: expected {len_msg} != got {len(msg_wire)}, " |
| 34 |
f"length field offset 0x{offset:x}", |
| 35 |
) |
| 36 |
try: |
| 37 |
msg = dns.message.from_wire(msg_wire) |
| 38 |
ok_msgs += 1 |
| 39 |
print(msg) |
| 40 |
except dns.exception.DNSException as ex: |
| 41 |
print(f"; invalid message, skipping: {ex}") |
| 42 |
bad_msgs += 1 |
| 43 |
print(f"; read {ok_msgs} valid and {bad_msgs} invalid messages") |
| 44 |
if bad_msgs: |
| 45 |
sys.exit(1) |
| 46 |
|
| 47 |
|
| 48 |
if __name__ == "__main__": |
| 49 |
main() |