|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""A FRAD pad octet is kept, and never invented, through a rebuild. |
| 3 | +
|
| 4 | +GitHub issue #2716: :rfc:`2427#section-3` allows a single ``0x00`` pad octet ahead of |
| 5 | +any NLPID, and :class:`~pcapkit.protocols.link.frad.FRAD` reads one ahead of every |
| 6 | +NLPID, but its data model did not record whether one was there. So |
| 7 | +:meth:`FRAD.make <pcapkit.protocols.link.frad.FRAD.make>` wrote the pad ahead of a |
| 8 | +SNAP header alone: a pad before a direct NLPID was lost on a rebuild, and one was |
| 9 | +invented ahead of a SNAP header captured without it. The data model's ``pad`` |
| 10 | +records it, and ``make()`` takes it, writing the pad ahead of a SNAP header alone |
| 11 | +when it is not given. |
| 12 | +
|
| 13 | +The frames are built here; this module is unit-tier and reads no capture file. |
| 14 | +
|
| 15 | +""" |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import contextlib |
| 19 | +import logging |
| 20 | +import struct |
| 21 | +import unittest |
| 22 | +import warnings |
| 23 | +from typing import TYPE_CHECKING |
| 24 | + |
| 25 | +from tests._support import reimport_once_per_class |
| 26 | + |
| 27 | +if TYPE_CHECKING: |
| 28 | + from typing import Any, Callable, Iterator |
| 29 | + |
| 30 | +#: Test tier (#1958): hand-picked parse -> rebuild round trips. |
| 31 | +__tier__ = 'ALL' |
| 32 | + |
| 33 | +#: An IPv4 header (protocol UDP) and an 8-octet UDP header. |
| 34 | +IPV4 = (bytes.fromhex('4500001c00010000401100000a0000010a000002') |
| 35 | + + bytes.fromhex('3039003500080000')) |
| 36 | +#: A minimal ARP request (RFC 826), 28 octets. |
| 37 | +ARP = bytes.fromhex('00010800060400010011223344550a0000010000000000000a000002') |
| 38 | + |
| 39 | +#: Each frame: the RFC 2427 address of DLCI 50 and UI control, then the NLPID with |
| 40 | +#: or without the pad; its ``pad``, ``nlpid`` and header length; and its protocol chain. |
| 41 | +FRAMES = { |
| 42 | + 'pad, IPv4': (bytes.fromhex('0c21' '03' '00' 'cc') + IPV4, (True, 0xCC, 5), 'FRAD:IPv4:UDP'), |
| 43 | + 'SNAP without the pad': (bytes.fromhex('0c21' '03' '80' '000000' '0806') + ARP, (False, 0x80, 9), |
| 44 | + 'FRAD:ARP'), |
| 45 | + # the forms the maker writes when ``pad`` is not given, as controls |
| 46 | + 'IPv4': (bytes.fromhex('0c21' '03' 'cc') + IPV4, (False, 0xCC, 4), 'FRAD:IPv4:UDP'), |
| 47 | + 'pad, SNAP': (bytes.fromhex('0c21' '03' '00' '80' '000000' '0806') + ARP, (True, 0x80, 10), 'FRAD:ARP'), |
| 48 | +} # type: dict[str, tuple[bytes, tuple[bool, int, int], str]] |
| 49 | + |
| 50 | +#: A Linux cooked-capture source address, padded to its 8 octets. |
| 51 | +LINK_ADDR = bytes.fromhex('001122334455') + bytes(2) |
| 52 | + |
| 53 | + |
| 54 | +class _Logged(logging.Handler): |
| 55 | + """Collect what the ``pcapkit`` logger reports.""" |
| 56 | + |
| 57 | + def __init__(self) -> None: |
| 58 | + super().__init__(logging.DEBUG) |
| 59 | + self.messages = [] # type: list[str] |
| 60 | + |
| 61 | + def emit(self, record: 'logging.LogRecord') -> None: |
| 62 | + self.messages.append(f'logged: {record.getMessage()}') |
| 63 | + |
| 64 | + |
| 65 | +@contextlib.contextmanager |
| 66 | +def _reported() -> 'Iterator[list[str]]': |
| 67 | + """Collect what the block reports, on the :mod:`warnings` channel and the logger.""" |
| 68 | + handler = _Logged() |
| 69 | + logger = logging.getLogger('pcapkit') |
| 70 | + logger.addHandler(handler) |
| 71 | + try: |
| 72 | + with warnings.catch_warnings(record=True) as caught: |
| 73 | + warnings.simplefilter('always') |
| 74 | + yield handler.messages |
| 75 | + finally: |
| 76 | + logger.removeHandler(handler) |
| 77 | + handler.messages.extend(f'warned: {item.message}' for item in caught) |
| 78 | + |
| 79 | + |
| 80 | +class FRADPadRebuildTests(unittest.TestCase): |
| 81 | + """A FRAD frame rebuilds with the pad octet it was captured with, and no other.""" |
| 82 | + |
| 83 | + def setUp(self) -> None: |
| 84 | + reimport_once_per_class(self) |
| 85 | + from pcapkit.const.linux.arphrd import ARPHRD |
| 86 | + from pcapkit.protocols.link.frad import FRAD |
| 87 | + from pcapkit.protocols.link.linux_sll1 import LinuxSLL1 |
| 88 | + from pcapkit.protocols.link.linux_sll2 import LinuxSLL2 |
| 89 | + from pcapkit.utilities.exceptions import ProtocolError |
| 90 | + |
| 91 | + self.FRAD = FRAD |
| 92 | + self.ProtocolError = ProtocolError |
| 93 | + self.cooked = { |
| 94 | + 'LinuxSLL1': (LinuxSLL1, struct.pack('>HHH', 0, ARPHRD.FRAD, 6) + LINK_ADDR |
| 95 | + + struct.pack('>H', 0)), |
| 96 | + 'LinuxSLL2': (LinuxSLL2, struct.pack('>HHIHBB', 0, 0, 1, ARPHRD.FRAD, 0, 6) + LINK_ADDR), |
| 97 | + } # type: dict[str, tuple[Any, bytes]] |
| 98 | + |
| 99 | + def parse(self, build: 'Callable[[], Any]') -> 'tuple[Any, list[str]]': |
| 100 | + """What ``build`` returns, and what it reported.""" |
| 101 | + with _reported() as messages: |
| 102 | + layer = build() |
| 103 | + return layer, messages |
| 104 | + |
| 105 | + def assertRebuildsQuietly(self, layer: 'Any') -> 'None': # pylint: disable=invalid-name |
| 106 | + """``layer`` rebuilt from its data model and its dict: its octets, and nothing reported.""" |
| 107 | + for path, data in (('model', layer.info), ('dict', layer.info.to_dict())): |
| 108 | + with self.subTest(path=path): |
| 109 | + rebuilt, messages = self.parse(lambda: type(layer).from_data(data)) # pylint: disable=cell-var-from-loop |
| 110 | + self.assertEqual((rebuilt.data.hex(), messages), (layer.data.hex(), [])) |
| 111 | + |
| 112 | + def test_a_whole_frame_reads_its_pad(self) -> None: |
| 113 | + for label, (frame, (pad, nlpid, length), chain) in FRAMES.items(): |
| 114 | + with self.subTest(frame=label): |
| 115 | + layer, messages = self.parse(lambda: self.FRAD(frame, len(frame))) # pylint: disable=cell-var-from-loop |
| 116 | + self.assertEqual(messages, []) |
| 117 | + self.assertEqual((layer.info.pad, layer.info.nlpid, layer.info.len), (pad, nlpid, length)) |
| 118 | + self.assertEqual(str(layer.protochain), chain) |
| 119 | + |
| 120 | + def test_a_whole_frame_rebuilds_as_captured(self) -> None: |
| 121 | + for label, (frame, _, _) in FRAMES.items(): |
| 122 | + with self.subTest(frame=label): |
| 123 | + layer = self.FRAD(frame, len(frame)) |
| 124 | + self.assertRebuildsQuietly(layer) |
| 125 | + |
| 126 | + def test_every_cut_rebuilds_as_captured(self) -> None: |
| 127 | + for label, (frame, _, _) in FRAMES.items(): |
| 128 | + for count in range(1, len(frame)): |
| 129 | + with self.subTest(frame=label, captured=count): |
| 130 | + with warnings.catch_warnings(): |
| 131 | + warnings.simplefilter('ignore') |
| 132 | + layer = self.FRAD(frame[:count], count) |
| 133 | + self.assertEqual(layer.data, frame[:count]) |
| 134 | + self.assertRebuildsQuietly(layer) |
| 135 | + |
| 136 | + def test_linux_sll_rebuilds_the_pad_as_captured(self) -> None: |
| 137 | + for name, (cls, head) in self.cooked.items(): |
| 138 | + for label, (frame, (pad, _, _), chain) in FRAMES.items(): |
| 139 | + raw = head + frame |
| 140 | + with self.subTest(cooked=name, frame=label): |
| 141 | + sll, messages = self.parse(lambda: cls(raw, len(raw))) # pylint: disable=cell-var-from-loop |
| 142 | + self.assertEqual(messages, []) |
| 143 | + self.assertEqual(str(sll.protochain).split(':', 1)[1], chain) |
| 144 | + self.assertIs(sll.payload.info.pad, pad) |
| 145 | + self.assertRebuildsQuietly(sll) |
| 146 | + |
| 147 | + def test_make_writes_the_pad_ahead_of_snap_alone_by_default(self) -> None: |
| 148 | + # A direct build is as it was: the pad ahead of a SNAP header, and an |
| 149 | + # NLPID of 0 written as the pad it reads as. |
| 150 | + cases = { |
| 151 | + 'IPv4': ({'nlpid': 0xCC}, '0c2103cc'), |
| 152 | + 'SNAP': ({'nlpid': 0x80, 'snap_oui': bytes(3), 'snap_pid': 0x0806}, '0c2103008000000008' '06'), |
| 153 | + 'zero NLPID': ({'nlpid': 0}, '0c21030000'), |
| 154 | + } |
| 155 | + for label, (kwargs, octets) in cases.items(): |
| 156 | + with self.subTest(case=label): |
| 157 | + made, messages = self.parse(lambda: self.FRAD(dlci=50, **kwargs)) # pylint: disable=cell-var-from-loop |
| 158 | + self.assertEqual((made.data.hex(), messages), (octets, [])) |
| 159 | + |
| 160 | + def test_make_takes_the_pad(self) -> None: |
| 161 | + cases = { |
| 162 | + 'pad, IPv4': ({'nlpid': 0xCC, 'pad': True}, '0c2103' '00cc'), |
| 163 | + 'IPv4 without the pad': ({'nlpid': 0xCC, 'pad': False}, '0c2103' 'cc'), |
| 164 | + 'SNAP without the pad': ({'nlpid': 0x80, 'pad': False, 'snap_oui': bytes(3), 'snap_pid': 0x0806}, |
| 165 | + '0c2103' '80' '000000' '0806'), |
| 166 | + 'pad, zero NLPID': ({'nlpid': 0, 'pad': True}, '0c2103' '0000'), |
| 167 | + } |
| 168 | + for label, (kwargs, octets) in cases.items(): |
| 169 | + with self.subTest(case=label): |
| 170 | + made, messages = self.parse(lambda: self.FRAD(dlci=50, **kwargs)) # pylint: disable=cell-var-from-loop |
| 171 | + self.assertEqual((made.data.hex(), messages), (octets, [])) |
| 172 | + self.assertIs(self.FRAD(made.data, len(made.data)).info.pad, kwargs['pad']) |
| 173 | + |
| 174 | + def test_make_refuses_a_zero_nlpid_without_the_pad(self) -> None: |
| 175 | + from pcapkit.utilities.exceptions import CaughtByCaller |
| 176 | + |
| 177 | + with CaughtByCaller(self.ProtocolError), self.assertRaisesRegex( |
| 178 | + self.ProtocolError, r'^FRAD: an nlpid of 0 reads as the pad, so pad cannot be False$'): |
| 179 | + self.FRAD(nlpid=0, pad=False) |
| 180 | + |
| 181 | + |
| 182 | +if __name__ == '__main__': |
| 183 | + unittest.main() |
0 commit comments