|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""A PCAP dumper writes each record's fraction in its own file's resolution. C.f. #1500. |
| 3 | +
|
| 4 | +:class:`~pcapkit.dumpkit.pcap.PCAPIO` wrote a frame's ``ts_usec`` unscaled, so a |
| 5 | +microsecond capture traced with ``trace_nanosecond=True`` -- or a nanosecond one |
| 6 | +traced without it -- wrote every fraction 1000 times off. A frame converted from |
| 7 | +PCAP-NG (:func:`~pcapkit.toolkit.pcapng.block2frame`) carries its interface's |
| 8 | +resolution and was written the same way. |
| 9 | +
|
| 10 | +Each case below writes frames as :mod:`pcapkit` read them, reads the file back |
| 11 | +with :mod:`struct` alone and with :mod:`pcapkit`, and checks every timestamp |
| 12 | +against the source frame: exactly when the file is at least as fine as the |
| 13 | +source, and truncated to the microsecond when it is coarser. |
| 14 | +
|
| 15 | +Every case builds its own octets and reads no capture. Classes are imported |
| 16 | +inside each test, after :func:`~tests._support.reimport_once_per_class`. |
| 17 | +
|
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import decimal |
| 23 | +import importlib.util |
| 24 | +import io |
| 25 | +import os |
| 26 | +import tempfile |
| 27 | +import unittest |
| 28 | +import warnings |
| 29 | +from typing import TYPE_CHECKING |
| 30 | + |
| 31 | +from tests._support import close_extractor, reimport_once_per_class |
| 32 | +from tests.foundation._roundtrip import ethernet, ipv4, pcap, pcapng, read_pcap, tcp |
| 33 | + |
| 34 | +if TYPE_CHECKING: |
| 35 | + from typing import Any |
| 36 | + |
| 37 | +HAS_RUNTIME = all(importlib.util.find_spec(name) is not None |
| 38 | + for name in ('tbtrim', 'aenum', 'chardet', 'dictdumper')) |
| 39 | + |
| 40 | +SECOND = 1_500_000_000 |
| 41 | +#: Fractions per input resolution: the ends of the second, a value whose |
| 42 | +#: nanoseconds sit at exactly half a microsecond, and a sub-microsecond one. |
| 43 | +FRACTIONS = { |
| 44 | + False: (0, 1, 123_456, 999_999), |
| 45 | + True: (0, 999, 1_000, 123_456_500, 123_456_789, 999_999_999), |
| 46 | +} |
| 47 | + |
| 48 | + |
| 49 | +def _frames(count: 'int') -> 'list[bytes]': |
| 50 | + """``count`` TCP segments of one connection, client to server.""" |
| 51 | + return [ethernet(ipv4(tcp(b'x' * number, seq=1000 + number, syn=not number), proto=6), 0x0800) |
| 52 | + for number in range(count)] |
| 53 | + |
| 54 | + |
| 55 | +def _epoch(sec: 'int', frac: 'int', nanosecond: 'bool') -> 'decimal.Decimal': |
| 56 | + """The UNIX timestamp of a record header's two fields.""" |
| 57 | + return decimal.Decimal(sec) + decimal.Decimal(frac) / (10 ** 9 if nanosecond else 10 ** 6) |
| 58 | + |
| 59 | + |
| 60 | +def _expected(sec: 'int', frac: 'int', in_nsec: 'bool', out_nsec: 'bool') -> 'tuple[int, int]': |
| 61 | + """The seconds and fraction a file of resolution ``out_nsec`` should hold.""" |
| 62 | + if in_nsec == out_nsec: |
| 63 | + return sec, frac |
| 64 | + if out_nsec: |
| 65 | + return sec, frac * 1000 |
| 66 | + return sec, frac // 1000 |
| 67 | + |
| 68 | + |
| 69 | +@unittest.skipUnless(HAS_RUNTIME, 'runtime dependencies not installed') |
| 70 | +class TestPCAPTraceResolution(unittest.TestCase): |
| 71 | + """Every fraction is written, and reads back, in the output file's resolution.""" |
| 72 | + |
| 73 | + def setUp(self) -> None: |
| 74 | + reimport_once_per_class(self) |
| 75 | + self.tmpdir = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with |
| 76 | + self.addCleanup(self.tmpdir.cleanup) |
| 77 | + |
| 78 | + def read(self, data: 'bytes') -> 'list[Any]': |
| 79 | + """The frames :mod:`pcapkit` reads from ``data``, a PCAP or PCAP-NG file.""" |
| 80 | + from pcapkit import extract |
| 81 | + |
| 82 | + with warnings.catch_warnings(): |
| 83 | + warnings.simplefilter('ignore') |
| 84 | + extractor = extract(fin=io.BytesIO(data), nofile=True, store=True) |
| 85 | + close_extractor(extractor) |
| 86 | + return list(extractor.frame) |
| 87 | + |
| 88 | + def dump(self, frames: 'list[Any]', nanosecond: 'bool') -> 'str': |
| 89 | + """Write ``frames``, each a :class:`~pcapkit.protocols.data.misc.pcap.frame.Frame`.""" |
| 90 | + from pcapkit.const.reg.linktype import LinkType |
| 91 | + from pcapkit.dumpkit.pcap import PCAPIO |
| 92 | + |
| 93 | + path = os.path.join(self.tmpdir.name, f'out-{len(os.listdir(self.tmpdir.name))}.pcap') |
| 94 | + dumper = PCAPIO(path, protocol=LinkType.ETHERNET, byteorder='little', nanosecond=nanosecond) |
| 95 | + for frame in frames: |
| 96 | + dumper(frame) |
| 97 | + return path |
| 98 | + |
| 99 | + def reread(self, path: 'str') -> 'list[decimal.Decimal]': |
| 100 | + """Every frame's timestamp, as :mod:`pcapkit` reads the file at ``path``.""" |
| 101 | + with open(path, 'rb') as file: |
| 102 | + return [frame.info.time_epoch for frame in self.read(file.read())] |
| 103 | + |
| 104 | + def check(self, path: 'str', records: 'list[tuple[int, int]]', in_nsec: 'bool', out_nsec: 'bool') -> None: |
| 105 | + """The file at ``path`` holds ``records`` rescaled, and reads back as their instants.""" |
| 106 | + with open(path, 'rb') as file: |
| 107 | + written = read_pcap(file.read()) |
| 108 | + self.assertEqual(written.nanosecond, out_nsec) |
| 109 | + want = [_expected(sec, frac, in_nsec, out_nsec) for sec, frac in records] |
| 110 | + self.assertEqual([record[:2] for record in written.records], want) |
| 111 | + self.assertEqual(self.reread(path), [_epoch(sec, frac, out_nsec) for sec, frac in want]) |
| 112 | + |
| 113 | + def test_a_pcap_frame_is_written_at_the_files_resolution(self) -> None: |
| 114 | + """#1500: a PCAP frame's fraction is scaled up, or truncated down, to the file's.""" |
| 115 | + for in_nsec in (False, True): |
| 116 | + for out_nsec in (False, True): |
| 117 | + with self.subTest(in_nsec=in_nsec, out_nsec=out_nsec): |
| 118 | + records = [(SECOND + i, frac) for i, frac in enumerate(FRACTIONS[in_nsec])] |
| 119 | + data = pcap([(sec, frac, frame) for (sec, frac), frame |
| 120 | + in zip(records, _frames(len(records)))], nanosecond=in_nsec) |
| 121 | + frames = self.read(data) |
| 122 | + self.assertEqual([frame.info.time_epoch for frame in frames], |
| 123 | + [_epoch(sec, frac, in_nsec) for sec, frac in records]) |
| 124 | + |
| 125 | + path = self.dump([frame.info for frame in frames], out_nsec) |
| 126 | + self.check(path, records, in_nsec, out_nsec) |
| 127 | + if in_nsec == out_nsec: |
| 128 | + with open(path, 'rb') as file: |
| 129 | + self.assertEqual(file.read()[24:], data[24:]) |
| 130 | + |
| 131 | + def test_a_pcapng_frame_is_written_at_the_files_resolution(self) -> None: |
| 132 | + """#1500: so is a frame converted from PCAP-NG at its interface's resolution.""" |
| 133 | + from pcapkit.toolkit.pcapng import block2frame |
| 134 | + |
| 135 | + for in_nsec in (False, True): |
| 136 | + for out_nsec in (False, True): |
| 137 | + with self.subTest(in_nsec=in_nsec, out_nsec=out_nsec): |
| 138 | + records = [(SECOND + i, frac) for i, frac in enumerate(FRACTIONS[in_nsec])] |
| 139 | + data = pcapng([(sec, frac, frame) for (sec, frac), frame |
| 140 | + in zip(records, _frames(len(records)))], nanosecond=in_nsec) |
| 141 | + blocks = self.read(data) |
| 142 | + self.assertEqual([block.nanosecond for block in blocks], [in_nsec] * len(records)) |
| 143 | + |
| 144 | + # what the PCAP-NG engine hands a flow's dumper |
| 145 | + frames = [block2frame(block.info, nanosecond=block.nanosecond) for block in blocks] |
| 146 | + self.check(self.dump(frames, out_nsec), records, in_nsec, out_nsec) |
| 147 | + |
| 148 | + def test_a_trace_reads_back_as_its_source_frames(self) -> None: |
| 149 | + """#1500: a flow traced at either resolution re-reads as its frames' timestamps.""" |
| 150 | + from pcapkit import extract |
| 151 | + |
| 152 | + for container, build in (('pcap', pcap), ('pcapng', pcapng)): |
| 153 | + for in_nsec in (False, True): |
| 154 | + for out_nsec in (False, True): |
| 155 | + with self.subTest(container=container, in_nsec=in_nsec, out_nsec=out_nsec): |
| 156 | + records = [(SECOND + i, frac) for i, frac in enumerate(FRACTIONS[in_nsec])] |
| 157 | + data = build([(sec, frac, frame) for (sec, frac), frame |
| 158 | + in zip(records, _frames(len(records)))], nanosecond=in_nsec) |
| 159 | + tracedir = tempfile.mkdtemp(dir=self.tmpdir.name) |
| 160 | + with warnings.catch_warnings(): |
| 161 | + warnings.simplefilter('ignore') |
| 162 | + extractor = extract(fin=io.BytesIO(data), nofile=True, store=False, |
| 163 | + trace=True, tcp=True, trace_fout=tracedir, |
| 164 | + trace_format='pcap', trace_nanosecond=out_nsec) |
| 165 | + close_extractor(extractor) |
| 166 | + flows = list(extractor.trace.tcp) |
| 167 | + self.assertEqual([list(flow.index) for flow in flows], |
| 168 | + [list(range(1, len(records) + 1))]) |
| 169 | + self.check(flows[0].fpout, records, in_nsec, out_nsec) |
| 170 | + |
| 171 | + def test_nanoseconds_are_truncated_not_rounded(self) -> None: |
| 172 | + """#1500: 999,999,999 ns is 999,999 us of the same second, and half a microsecond drops.""" |
| 173 | + from pcapkit.protocols.data.misc.pcap.frame import Frame, FrameInfo |
| 174 | + |
| 175 | + frames = [] |
| 176 | + for frac in (999_999_999, 123_456_500, 500): |
| 177 | + frame = Frame(frame_info=FrameInfo(ts_sec=SECOND, ts_usec=frac, incl_len=0, orig_len=0), |
| 178 | + time='time', number=1, time_epoch=_epoch(SECOND, frac, True), len=0, cap_len=0) |
| 179 | + frame.__update__(packet=b'') |
| 180 | + frames.append(frame) |
| 181 | + with open(self.dump(frames, False), 'rb') as file: |
| 182 | + written = read_pcap(file.read()) |
| 183 | + self.assertEqual([record[:2] for record in written.records], |
| 184 | + [(SECOND, 999_999), (SECOND, 123_456), (SECOND, 0)]) |
| 185 | + |
| 186 | + def test_a_rescaled_fraction_of_a_second_or_more_is_carried(self) -> None: |
| 187 | + """#1500: a fraction past the second moves into ``ts_sec``, so 1000x cannot overflow.""" |
| 188 | + # Neither fraction is normalised, and 5,000,000 us is 5e9 ns, past 2**32. |
| 189 | + for in_nsec, frac, want in ((False, 5_000_000, (SECOND + 5, 0)), |
| 190 | + (True, 1_500_000_123, (SECOND + 1, 500_000))): |
| 191 | + with self.subTest(in_nsec=in_nsec): |
| 192 | + data = pcap([(SECOND, frac, _frames(1)[0])], nanosecond=in_nsec) |
| 193 | + frames = self.read(data) |
| 194 | + path = self.dump([frame.info for frame in frames], not in_nsec) |
| 195 | + with open(path, 'rb') as file: |
| 196 | + written = read_pcap(file.read()) |
| 197 | + self.assertEqual(written.records[0][:2], want) |
| 198 | + self.assertEqual(self.reread(path), [_epoch(*want, not in_nsec)]) |
| 199 | + if not in_nsec: |
| 200 | + self.assertEqual(self.reread(path), [frame.info.time_epoch for frame in frames]) |
| 201 | + |
| 202 | + def test_a_binary_resolution_keeps_its_sub_microsecond_part(self) -> None: |
| 203 | + """#1500: a fraction truncated to microseconds is rescaled from the exact timestamp.""" |
| 204 | + from pcapkit.protocols.data.misc.pcap.frame import Frame, FrameInfo |
| 205 | + |
| 206 | + # What :func:`~pcapkit.toolkit.pcapng.block2frame` makes of tick 1 of an |
| 207 | + # ``if_tsresol`` of 2**-10: 0.0009765625 s, truncated to 976 us. |
| 208 | + epoch = decimal.Decimal(SECOND) + decimal.Decimal(1) / 1024 |
| 209 | + frame = Frame(frame_info=FrameInfo(ts_sec=SECOND, ts_usec=976, incl_len=0, orig_len=0), |
| 210 | + time='time', number=1, time_epoch=epoch, len=0, cap_len=0) |
| 211 | + frame.__update__(packet=b'') |
| 212 | + with open(self.dump([frame], True), 'rb') as file: |
| 213 | + written = read_pcap(file.read()) |
| 214 | + self.assertEqual(written.records[0][:2], (SECOND, 976_562)) |
| 215 | + |
| 216 | + def test_a_frame_whose_timestamp_fits_neither_resolution_is_written_as_given(self) -> None: |
| 217 | + """A hand-built frame whose ``time_epoch`` fits neither resolution keeps its fields.""" |
| 218 | + from pcapkit.protocols.data.misc.pcap.frame import Frame, FrameInfo |
| 219 | + |
| 220 | + for nanosecond in (False, True): |
| 221 | + with self.subTest(nanosecond=nanosecond): |
| 222 | + frame = Frame(frame_info=FrameInfo(ts_sec=7, ts_usec=123_456, incl_len=0, orig_len=0), |
| 223 | + time='time', number=1, time_epoch=decimal.Decimal('2.5'), len=0, cap_len=0) |
| 224 | + frame.__update__(packet=b'') |
| 225 | + with open(self.dump([frame], nanosecond), 'rb') as file: |
| 226 | + written = read_pcap(file.read()) |
| 227 | + self.assertEqual(written.records[0][:2], (7, 123_456)) |
| 228 | + |
| 229 | + |
| 230 | +if __name__ == '__main__': |
| 231 | + unittest.main() |
0 commit comments