Skip to content

Commit 63e8dea

Browse files
authored
fix(pcap,pcapng): prefix capture-guard messages and name the block type in option guards (#2398)
#2300: the guards that reject a file's magic number or byte order had no PCAP:/PCAP-NG: prefix, unlike every other message in those modules, and PCAP's magic-number guard didn't say what it read. Four sites: schema/misc/pcap/header.py's magic_number_callback, misc/pcap/header.py's _make_magic (byte order unresolved/unknown), and two byte-order sites in schema/misc/pcapng.py that were the only two of nine messages in that file still missing PCAP-NG:. #2301: 128 PCAP-NG option guards in misc/pcapng.py ended in a full stop, unlike the house <prefix>: ... form (#2232, #2257), and the placement guard formatted self._type -- a plain int at make time, not the Enum_ BlockType it's cast to -- with bare {}, showing a raw number. A new _block_type_name() helper resolves either form through Enum_BlockType, idempotent for the enum case; applying the int form via .name directly would raise AttributeError, verified against pristine main. Also fixed: the if_tsresol/if_tzone option guards carried the identical full-stop defect, outside the issue's literal checklist but left would have made this consistency fix inconsistent with itself -- the file's full-stop count is now 0, which a new test asserts as an invariant. CHANGELOG.md regenerated (util/changelog_md.py) after correcting one docs/source/changelog/1.5.0.rst entry that quoted the old literal message. Tests: new tests/protocols/misc/test_capture_message_prefix_2300_2301_unit.py, 14 cases, 13 fail / 1 passes against pristine main (the one passing case is a characterisation pin of _type's runtime type, true on both trees).
1 parent 790e630 commit 63e8dea

10 files changed

Lines changed: 470 additions & 145 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎docs/source/changelog/1.5.0.rst‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2139,8 +2139,9 @@ Fixed
21392139
key at ``-1`` for "unknown". Ships labelled breaking: well-formed captures are
21402140
byte-identical, but any truncated PCAP-NG now yields the frames before the cut where
21412141
it raised, the last of which may carry zero-padded octets, and some short-file depths
2142-
move from ``ProtocolError: unknown byteorder magic`` to :exc:`.StreamEOFError`. The
2143-
:pr:`683` drift :issue:`685` tracks is unchanged (:issue:`678`).
2142+
move from ``ProtocolError: PCAP-NG: unknown byte-order magic`` to
2143+
:exc:`.StreamEOFError`. The :pr:`683` drift :issue:`685` tracks is unchanged
2144+
(:issue:`678`).
21442145
* HIP's ``R1_COUNTER``/``R1_Counter`` parameter packed 12 octets where
21452146
:rfc:`7401#section-5.2.3` requires 16, and ``LOCATOR_SET`` declared its ``Length``
21462147
in 4-octet units where :rfc:`7401#section-5.2.1`'s ``Length`` is a byte count --

‎pcapkit/protocols/misc/pcap/header.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -367,14 +367,14 @@ def _make_magic(self, byteorder: 'Literal["big", "little"]' = sys.byteorder,
367367
368368
"""
369369
if lilendian is not None and bigendian is not None and lilendian == bigendian:
370-
raise EndianError('unresolved byte order')
370+
raise EndianError('PCAP: unresolved byte order')
371371
if bigendian is not None:
372372
byteorder = 'big' if bigendian else 'little'
373373
elif lilendian is not None:
374374
byteorder = 'little' if lilendian else 'big'
375375

376376
if byteorder not in ('little', 'big'):
377-
raise EndianError(f"unknown byte order: {byteorder!r}")
377+
raise EndianError(f'PCAP: unknown byte order: {byteorder!r}')
378378

379379
magic_number = _DECLARED_MAGIC[(byteorder, nanosecond)]
380380
return magic_number, (byteorder == 'little')

‎pcapkit/protocols/misc/pcapng.py‎

Lines changed: 153 additions & 130 deletions
Large diffs are not rendered by default.

‎pcapkit/protocols/schema/misc/pcap/header.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def magic_number_callback(field: 'NumberField', packet: 'dict[str, Any]') -> 'No
7575
declared = (MAGIC_NUMBER.get(bytes(magic_number))
7676
if isinstance(magic_number, (bytes, bytearray, memoryview)) else None)
7777
if declared is None:
78-
raise ProtocolError('invalid magic number')
78+
raise ProtocolError(f'PCAP: invalid magic number: {magic_number!r}')
7979
field._byteorder = declared[0]
8080

8181

‎pcapkit/protocols/schema/misc/pcapng.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ def shb_byteorder_callback(field: 'NumberField', packet: 'dict[str, Any]') -> 'N
246246
elif magic in (_SWAPPED_BYTE_ORDER_MAGIC, 0x0C000000):
247247
field._byteorder = 'little'
248248
else:
249-
raise ProtocolError(f'unknown byteorder magic: {magic:#x}')
249+
raise ProtocolError(f'PCAP-NG: unknown byte-order magic: {magic:#x}')
250250
packet['byteorder'] = field._byteorder
251251

252252

@@ -1370,7 +1370,7 @@ def post_process(self, packet: 'dict[str, Any]') -> 'SectionHeaderBlock':
13701370
elif magic == _SWAPPED_BYTE_ORDER_MAGIC or (magic == 0x0C000000 and self.length == GENERIC_BLOCK_MINIMUM):
13711371
self.byteorder = 'little'
13721372
else:
1373-
raise ProtocolError(f'unknown byteorder magic: {magic:#x}')
1373+
raise ProtocolError(f'PCAP-NG: unknown byte-order magic: {magic:#x}')
13741374
return self
13751375

13761376
if TYPE_CHECKING:
Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
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

Comments
 (0)