xref: /freebsd/contrib/wpa/wpa_supplicant/utils/log2pcap.py (revision 96190b4fef3b4a0cc3ca0606b0c4e3e69a5e6717)
1#!/usr/bin/env python3
2#
3# Copyright (c) 2012-2022, Intel Corporation
4#
5# Author: Johannes Berg <johannes@sipsolutions.net>
6#
7# This software may be distributed under the terms of the BSD license.
8# See README for more details.
9
10import sys, struct, re
11from binascii import unhexlify
12
13def write_pcap_header(pcap_file):
14    pcap_file.write(
15        struct.pack('<IHHIIII',
16                    0xa1b2c3d4, 2, 4, 0, 0, 65535,
17                    105 # raw 802.11 format
18                    ))
19
20def pcap_addpacket(pcap_file, ts, data):
21    # ts in seconds, float
22    pcap_file.write(struct.pack('<IIII',
23        int(ts), int(1000000 * ts) % 1000000,
24        len(data), len(data)))
25    pcap_file.write(data)
26
27if __name__ == "__main__":
28    try:
29        input = sys.argv[1]
30        pcap = sys.argv[2]
31    except IndexError:
32        print("Usage: %s <log file> <pcap file>" % sys.argv[0])
33        sys.exit(2)
34
35    input_file = open(input, 'r')
36    pcap_file = open(pcap, 'wb')
37    frame_re = re.compile(r'(([0-9]+.[0-9]{6}):\s*)?nl80211: MLME event frame - hexdump\(len=[0-9]*\):((\s*[0-9a-fA-F]{2})*)')
38
39    write_pcap_header(pcap_file)
40
41    for line in input_file:
42        m = frame_re.match(line)
43        if m is None:
44            continue
45        if m.group(2):
46            ts = float(m.group(2))
47        else:
48            ts = 0
49        hexdata = m.group(3)
50        hexdata = hexdata.split()
51        data = unhexlify("".join(hexdata))
52        pcap_addpacket(pcap_file, ts, data)
53
54    input_file.close()
55    pcap_file.close()
56