|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""The capture-header and PCAP-NG option-guard messages take the house form. C.f. #2300, #2301. |
| 3 | +
|
| 4 | +Every other message in these modules reads ``PCAP: …`` or ``PCAP-NG: …``, the |
| 5 | +house ``<prefix>: <lowercase description>: … {value!r}`` form with no closing |
| 6 | +full stop (#2232, #2257). These guards did not. |
| 7 | +
|
| 8 | +#2300 -- the guards that reject a file's magic number or byte order carried no |
| 9 | +prefix at all: :func:`~pcapkit.protocols.schema.misc.pcap.header.magic_number_callback` |
| 10 | +raised ``invalid magic number``, naming neither the module nor the four octets |
| 11 | +it had just read; :meth:`Header._make_magic |
| 12 | +<pcapkit.protocols.misc.pcap.header.Header._make_magic>` raised ``unresolved |
| 13 | +byte order`` and ``unknown byte order: 'middle'``; and PCAP-NG's |
| 14 | +:func:`~pcapkit.protocols.schema.misc.pcapng.shb_byteorder_callback` and |
| 15 | +:meth:`SectionHeaderBlock.post_process |
| 16 | +<pcapkit.protocols.schema.misc.pcapng.SectionHeaderBlock.post_process>` raised |
| 17 | +``unknown byteorder magic: 0x11223344``, spelling the specification's |
| 18 | +"Byte-Order Magic" as one word. |
| 19 | +
|
| 20 | +#2301 -- the PCAP-NG option guards closed with a full stop, and the placement |
| 21 | +guard formatted :attr:`PCAPNG._type <pcapkit.protocols.misc.pcapng.PCAPNG._type>` |
| 22 | +with a bare ``{}``. That attribute is an :class:`~enum.IntEnum`, which a bare |
| 23 | +``{}`` renders as its value, so the message named the block type as a number: |
| 24 | +``must be in Interface Description Block, but found in 6 block.`` rather than |
| 25 | +``not Enhanced_Packet_Block``. |
| 26 | +
|
| 27 | +The placement guard is reached on both passes, and ``_type`` is not the same |
| 28 | +kind of object on each: the parse pass assigns the |
| 29 | +:class:`~pcapkit.const.pcapng.block_type.BlockType` off the schema, while the |
| 30 | +make pass assigns what :meth:`~pcapkit.protocols.protocol.Protocol._make_index` |
| 31 | +returns, a plain :obj:`int` that is only :func:`~typing.cast` to the |
| 32 | +enumeration. Reading ``.name`` off it directly therefore raises |
| 33 | +:exc:`AttributeError` on the make pass, which is what |
| 34 | +:func:`~pcapkit.protocols.misc.pcapng._block_type_name` exists to avoid; the |
| 35 | +make-pass cases below are what pin that. |
| 36 | +
|
| 37 | +Every case builds its own octets in memory and reads no capture. Classes are |
| 38 | +imported inside each test, after |
| 39 | +:func:`~tests._support.reimport_once_per_class`, so they match the live |
| 40 | +:mod:`pcapkit` import. |
| 41 | +
|
| 42 | +""" |
| 43 | + |
| 44 | +import io |
| 45 | +import struct |
| 46 | +import unittest |
| 47 | +from typing import TYPE_CHECKING |
| 48 | + |
| 49 | +from tests._support import reimport_once_per_class |
| 50 | + |
| 51 | +if TYPE_CHECKING: |
| 52 | + from typing import Any |
| 53 | + |
| 54 | + |
| 55 | +class TestPCAPHeaderMessages(unittest.TestCase): |
| 56 | + """#2300: PCAP's magic-number and byte-order guards.""" |
| 57 | + |
| 58 | + def setUp(self) -> None: |
| 59 | + reimport_once_per_class(self) |
| 60 | + |
| 61 | + def test_magic_number_is_prefixed_and_names_the_octets(self) -> None: |
| 62 | + """The magic-number guard says which module rejected what.""" |
| 63 | + from pcapkit.protocols.misc.pcap.header import Header |
| 64 | + from pcapkit.utilities.exceptions import ProtocolError |
| 65 | + |
| 66 | + with self.assertRaises(ProtocolError) as ctx: |
| 67 | + Header(io.BytesIO(b'\x00' * 24)) |
| 68 | + self.assertEqual(str(ctx.exception), |
| 69 | + "PCAP: invalid magic number: b'\\x00\\x00\\x00\\x00'") |
| 70 | + |
| 71 | + def test_magic_number_names_the_octets_it_read(self) -> None: |
| 72 | + """The rejected octets are the ones read, not a fixed string.""" |
| 73 | + from pcapkit.protocols.misc.pcap.header import Header |
| 74 | + from pcapkit.utilities.exceptions import ProtocolError |
| 75 | + |
| 76 | + octets = b'\xde\xad\xbe\xef' + b'\x00' * 20 |
| 77 | + with self.assertRaises(ProtocolError) as ctx: |
| 78 | + Header(io.BytesIO(octets)) |
| 79 | + self.assertEqual(str(ctx.exception), |
| 80 | + "PCAP: invalid magic number: b'\\xde\\xad\\xbe\\xef'") |
| 81 | + |
| 82 | + def test_unresolved_byte_order_is_prefixed(self) -> None: |
| 83 | + """Contradictory ``lilendian`` and ``bigendian`` flags name the module.""" |
| 84 | + from pcapkit.protocols.misc.pcap.header import Header |
| 85 | + from pcapkit.utilities.exceptions import EndianError |
| 86 | + |
| 87 | + with self.assertRaises(EndianError) as ctx: |
| 88 | + Header.__new__(Header)._make_magic(lilendian=True, bigendian=True) |
| 89 | + self.assertEqual(str(ctx.exception), 'PCAP: unresolved byte order') |
| 90 | + |
| 91 | + def test_unknown_byte_order_is_prefixed(self) -> None: |
| 92 | + """An unrecognised ``byteorder`` names the module and the value.""" |
| 93 | + from pcapkit.protocols.misc.pcap.header import Header |
| 94 | + from pcapkit.utilities.exceptions import EndianError |
| 95 | + |
| 96 | + with self.assertRaises(EndianError) as ctx: |
| 97 | + Header.__new__(Header)._make_magic(byteorder='middle') # type: ignore[arg-type] |
| 98 | + self.assertEqual(str(ctx.exception), "PCAP: unknown byte order: 'middle'") |
| 99 | + |
| 100 | + |
| 101 | +class TestPCAPNGByteOrderMessages(unittest.TestCase): |
| 102 | + """#2300: PCAP-NG's Byte-Order Magic guards.""" |
| 103 | + |
| 104 | + def setUp(self) -> None: |
| 105 | + reimport_once_per_class(self) |
| 106 | + |
| 107 | + def test_callback_is_prefixed_and_hyphenates_byte_order(self) -> None: |
| 108 | + """``shb_byteorder_callback`` takes the house prefix.""" |
| 109 | + from pcapkit.protocols.schema.misc.pcapng import shb_byteorder_callback |
| 110 | + from pcapkit.utilities.exceptions import ProtocolError |
| 111 | + |
| 112 | + with self.assertRaises(ProtocolError) as ctx: |
| 113 | + shb_byteorder_callback(None, {'match': {'byteorder': 0x11223344}}) |
| 114 | + self.assertEqual(str(ctx.exception), |
| 115 | + 'PCAP-NG: unknown byte-order magic: 0x11223344') |
| 116 | + |
| 117 | + def test_post_process_is_prefixed_and_hyphenates_byte_order(self) -> None: |
| 118 | + """The same guard on :meth:`SectionHeaderBlock.post_process` matches it. |
| 119 | +
|
| 120 | + A Section Header Block of 16 octets has no room for the Byte-Order |
| 121 | + Magic, so its slot holds the trailing Block Total Length -- 16 here, |
| 122 | + which is a byte order in neither direction (#1422). |
| 123 | +
|
| 124 | + """ |
| 125 | + from pcapkit.protocols.misc.pcapng import PCAPNG |
| 126 | + from pcapkit.utilities.exceptions import ProtocolError |
| 127 | + |
| 128 | + octets = struct.pack('<II', 0x0A0D0D0A, 16) + struct.pack('<I', 12) + struct.pack('<I', 16) |
| 129 | + with self.assertRaises(ProtocolError) as ctx: |
| 130 | + PCAPNG(octets, len(octets), num=0, sct=1, ctx=None) |
| 131 | + self.assertEqual(str(ctx.exception), |
| 132 | + 'PCAP-NG: unknown byte-order magic: 0xc000000') |
| 133 | + |
| 134 | + |
| 135 | +class TestPCAPNGOptionGuardMessages(unittest.TestCase): |
| 136 | + """#2301: the option placement and "only one" guards.""" |
| 137 | + |
| 138 | + def setUp(self) -> None: |
| 139 | + reimport_once_per_class(self) |
| 140 | + |
| 141 | + def _context(self) -> 'Any': |
| 142 | + """A one-section context with one Ethernet interface, as the engine builds it.""" |
| 143 | + from pcapkit.const.pcapng.block_type import BlockType |
| 144 | + from pcapkit.const.reg.linktype import LinkType |
| 145 | + from pcapkit.foundation.engines.pcapng import Context |
| 146 | + from pcapkit.protocols.misc.pcapng import PCAPNG |
| 147 | + |
| 148 | + section = PCAPNG(num=0, sct=1, ctx=None, type=BlockType.Section_Header_Block, block={}) |
| 149 | + context = Context(section.info) # type: Any |
| 150 | + interface = PCAPNG(num=1, sct=1, ctx=context, |
| 151 | + type=BlockType.Interface_Description_Block, |
| 152 | + block={'linktype': LinkType.ETHERNET, 'snaplen': 0x40000}) |
| 153 | + context.interfaces.append(interface.info) |
| 154 | + return context |
| 155 | + |
| 156 | + def test_placement_guard_names_the_block_type(self) -> None: |
| 157 | + """The block type is named, not numbered, and the message has no full stop. |
| 158 | +
|
| 159 | + This runs through :meth:`PCAPNG.make`, where ``_type`` is a plain |
| 160 | + :obj:`int`, so it is also what pins the guard against the |
| 161 | + :exc:`AttributeError` a direct ``.name`` would raise there. |
| 162 | +
|
| 163 | + """ |
| 164 | + from pcapkit.const.pcapng.block_type import BlockType |
| 165 | + from pcapkit.const.pcapng.option_type import OptionType |
| 166 | + from pcapkit.protocols.misc.pcapng import PCAPNG |
| 167 | + from pcapkit.utilities.exceptions import ProtocolError |
| 168 | + |
| 169 | + with self.assertRaises(ProtocolError) as ctx: |
| 170 | + PCAPNG(num=2, sct=1, ctx=self._context(), |
| 171 | + type=BlockType.Interface_Statistics_Block, |
| 172 | + block={'interface_id': 0, 'timestamp': 0, |
| 173 | + 'options': [(OptionType.if_name, {'name': 'eth0'})]}) |
| 174 | + self.assertEqual(str(ctx.exception), |
| 175 | + 'PCAP-NG: [if_name] option must be in Interface Description ' |
| 176 | + 'Block, not Interface_Statistics_Block') |
| 177 | + |
| 178 | + def test_placement_guard_does_not_raise_attribute_error(self) -> None: |
| 179 | + """The make pass's plain-``int`` ``_type`` reaches the guard, not an AttributeError.""" |
| 180 | + from pcapkit.const.pcapng.block_type import BlockType |
| 181 | + from pcapkit.const.pcapng.option_type import OptionType |
| 182 | + from pcapkit.protocols.misc.pcapng import PCAPNG |
| 183 | + from pcapkit.utilities.exceptions import ProtocolError |
| 184 | + |
| 185 | + seen = {} # type: dict[str, Any] |
| 186 | + original = PCAPNG._make_option_if_name |
| 187 | + |
| 188 | + def spy(inner_self: 'Any', *args: 'Any', **kwargs: 'Any') -> 'Any': |
| 189 | + seen['class'] = inner_self._type.__class__.__name__ |
| 190 | + return original(inner_self, *args, **kwargs) |
| 191 | + |
| 192 | + PCAPNG._make_option_if_name = spy # type: ignore[method-assign] |
| 193 | + try: |
| 194 | + with self.assertRaises(ProtocolError): |
| 195 | + PCAPNG(num=2, sct=1, ctx=self._context(), |
| 196 | + type=BlockType.Interface_Statistics_Block, |
| 197 | + block={'interface_id': 0, 'timestamp': 0, |
| 198 | + 'options': [(OptionType.if_name, {'name': 'eth0'})]}) |
| 199 | + finally: |
| 200 | + PCAPNG._make_option_if_name = original # type: ignore[method-assign] |
| 201 | + |
| 202 | + # The guard ran with a plain ``int``, which has no ``.name``. |
| 203 | + self.assertEqual(seen['class'], 'int') |
| 204 | + |
| 205 | + def test_block_type_name_takes_both_an_enum_and_a_plain_int(self) -> None: |
| 206 | + """The helper covers both passes' idea of ``_type``. |
| 207 | +
|
| 208 | + The parse pass assigns the enumeration member off the schema and the |
| 209 | + make pass a plain :obj:`int`, and the guard is shared, so the helper |
| 210 | + has to name either. Reaching a placement guard through a *parse* is |
| 211 | + not possible -- an option code is resolved in the namespace of the |
| 212 | + block being parsed, so code 2 in an Interface Statistics Block is |
| 213 | + ``isb_starttime`` and never ``if_name`` -- which is why this is |
| 214 | + checked on the helper rather than through a capture. |
| 215 | +
|
| 216 | + """ |
| 217 | + from pcapkit.const.pcapng.block_type import BlockType |
| 218 | + from pcapkit.protocols.misc.pcapng import _block_type_name |
| 219 | + |
| 220 | + self.assertEqual(_block_type_name(BlockType.Enhanced_Packet_Block), |
| 221 | + 'Enhanced_Packet_Block') |
| 222 | + self.assertEqual(_block_type_name(6), 'Enhanced_Packet_Block') # type: ignore[arg-type] |
| 223 | + self.assertEqual(_block_type_name(BlockType.Interface_Description_Block), |
| 224 | + 'Interface_Description_Block') |
| 225 | + self.assertEqual(_block_type_name(1), 'Interface_Description_Block') # type: ignore[arg-type] |
| 226 | + |
| 227 | + def test_only_one_guard_has_no_full_stop(self) -> None: |
| 228 | + """A repeated "only one" option reports the count in the house form.""" |
| 229 | + from pcapkit.const.pcapng.block_type import BlockType |
| 230 | + from pcapkit.const.pcapng.option_type import OptionType |
| 231 | + from pcapkit.protocols.misc.pcapng import PCAPNG |
| 232 | + from pcapkit.utilities.exceptions import ProtocolError |
| 233 | + |
| 234 | + with self.assertRaises(ProtocolError) as ctx: |
| 235 | + PCAPNG(num=2, sct=1, ctx=self._context(), |
| 236 | + type=BlockType.Interface_Description_Block, |
| 237 | + block={'linktype': 1, 'snaplen': 65535, |
| 238 | + 'options': [(OptionType.if_name, {'name': 'eth0'}), |
| 239 | + (OptionType.if_name, {'name': 'eth1'})]}) |
| 240 | + self.assertEqual(str(ctx.exception), |
| 241 | + 'PCAP-NG: [if_name] option must be only one, not 2') |
| 242 | + |
| 243 | + def test_if_tsresol_guard_has_no_full_stop(self) -> None: |
| 244 | + """The ``if_tsresol`` resolution guard takes the same ``not …`` form.""" |
| 245 | + from pcapkit.const.pcapng.block_type import BlockType |
| 246 | + from pcapkit.const.pcapng.option_type import OptionType |
| 247 | + from pcapkit.protocols.misc.pcapng import PCAPNG |
| 248 | + from pcapkit.utilities.exceptions import ProtocolError |
| 249 | + |
| 250 | + with self.assertRaises(ProtocolError) as ctx: |
| 251 | + PCAPNG(num=2, sct=1, ctx=self._context(), |
| 252 | + type=BlockType.Interface_Description_Block, |
| 253 | + block={'linktype': 1, 'snaplen': 65535, |
| 254 | + 'options': [(OptionType.if_tsresol, {'resolution': 3})]}) |
| 255 | + self.assertEqual(str(ctx.exception), |
| 256 | + 'PCAP-NG: [if_tsresol] option resolution must be power ' |
| 257 | + 'of 10 or 2, not 3') |
| 258 | + |
| 259 | + def test_if_tzone_guard_has_no_full_stop(self) -> None: |
| 260 | + """The ``if_tzone`` timezone guard takes the same ``not …`` form.""" |
| 261 | + from pcapkit.const.pcapng.block_type import BlockType |
| 262 | + from pcapkit.const.pcapng.option_type import OptionType |
| 263 | + from pcapkit.protocols.misc.pcapng import PCAPNG |
| 264 | + from pcapkit.utilities.exceptions import ProtocolError |
| 265 | + |
| 266 | + with self.assertRaises(ProtocolError) as ctx: |
| 267 | + PCAPNG(num=2, sct=1, ctx=self._context(), |
| 268 | + type=BlockType.Interface_Description_Block, |
| 269 | + block={'linktype': 1, 'snaplen': 65535, |
| 270 | + 'options': [(OptionType.if_tzone, {'tzone': 'UTC'})]}) |
| 271 | + self.assertEqual(str(ctx.exception), |
| 272 | + 'PCAP-NG: [if_tzone] option timezone must be int, ' |
| 273 | + 'timedelta or timezone, not str') |
| 274 | + |
| 275 | + def test_no_option_guard_message_ends_in_a_full_stop(self) -> None: |
| 276 | + """#2301: the whole module is free of the full-stop form, not just the guards hit above.""" |
| 277 | + import re |
| 278 | + |
| 279 | + from pcapkit.protocols.misc import pcapng |
| 280 | + |
| 281 | + with open(pcapng.__file__, encoding='utf-8') as file: |
| 282 | + source = file.read() |
| 283 | + |
| 284 | + # A message fragment on its own line, closing the call and ending in a |
| 285 | + # full stop -- the shape every guard in #2301 had. |
| 286 | + offenders = re.findall(r"^\s+f?'[^']*\.'\)", source, re.MULTILINE) |
| 287 | + self.assertEqual(offenders, []) |
| 288 | + |
| 289 | + def test_no_guard_formats_the_block_type_with_a_bare_brace(self) -> None: |
| 290 | + """#2301: ``{self._type}`` in a message would render the block type as a number.""" |
| 291 | + from pcapkit.protocols.misc import pcapng |
| 292 | + |
| 293 | + with open(pcapng.__file__, encoding='utf-8') as file: |
| 294 | + source = file.read() |
| 295 | + |
| 296 | + self.assertNotIn('but found in {self._type} block', source) |
| 297 | + |
| 298 | + |
| 299 | +if __name__ == '__main__': |
| 300 | + unittest.main() |
0 commit comments