Skip to content

Commit 96b32e3

Browse files
committed
fix(schema): Schema.pack keeps option padding, SchemaField spans and iterated keys
- pack: an OptionField records the part of its declared area the packed options leave unfilled as __option_padding__, the mirror of unpack, so TCP and IPv4 rebuild to the length their header declares (#1289). - __getitem__: serves every key __iter__ yields, including values a post_process stores, so dict(schema) no longer raises KeyError (#1291). - pack: a SchemaField packs its whole declared span, re-emitting the octets its nested schema left unread when the unpack buffer still holds them and zero-filling otherwise (#1292).
1 parent 13aa677 commit 96b32e3

2 files changed

Lines changed: 144 additions & 3 deletions

File tree

‎pcapkit/protocols/schema/schema.py‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010

1111
from pcapkit.corekit.fields.collections import ListField, OptionField
1212
from pcapkit.corekit.fields.field import NO_VALUE, FieldBase
13-
from pcapkit.corekit.fields.misc import ConditionalField, ForwardMatchField, PayloadField
13+
from pcapkit.corekit.fields.misc import (ConditionalField, ForwardMatchField, PayloadField,
14+
SchemaField)
1415
from pcapkit.corekit.fields.strings import PaddingField
1516
from pcapkit.corekit.infoclass import FinalisedState
1617
from pcapkit.utilities.compat import Mapping, final
@@ -626,10 +627,16 @@ def __iter__(self) -> 'Iterator[str]':
626627
yield self.__map_reverse__.get(key, key)
627628

628629
def __getitem__(self, name: 'str') -> '_VT':
629-
if name in self.__fields__:
630+
# NOTE: Serves every key :meth:`__iter__` yields, not only the declared
631+
# fields: a ``post_process`` may store derived values on the instance,
632+
# as :class:`~pcapkit.protocols.schema.internet.ipv4.TSOption` does, and
633+
# iteration reports them, so ``dict(schema)`` must be able to read them
634+
# back (:issue:`1291`). A mangled key is reachable only under the name
635+
# it was mangled from, as in iteration.
636+
if name in self.__fields__ or (name not in self.__builtin__ and name not in self.__map_reverse__):
630637
key = self.__map__.get(name, name)
631638
return self.__dict__[key]
632-
return super().__getitem__(name)
639+
raise KeyError(name)
633640

634641
def __setattr__(self, name: 'str', value: '_VT') -> 'None':
635642
if name in self.__fields__:
@@ -817,6 +824,16 @@ class will consider negative value as a placeholder.
817824
self.__buffer__[field.name] = field.pack(list(data), packet)
818825
else:
819826
raise ProtocolUnbound(f'unsupported type {type(data)}')
827+
828+
if isinstance(field, OptionField):
829+
# NOTE: The packing mirror of the ``__option_padding__`` that
830+
# :meth:`unpack` records: whatever of the declared option area
831+
# the packed options do not fill. Without it every padding
832+
# field sized from that key packs nothing, and the header
833+
# comes out shorter than its own length field says
834+
# (:issue:`1289`). An undeclared area (a negative length)
835+
# leaves no remainder.
836+
packet['__option_padding__'] = max(field.length - len(self.__buffer__[field.name]), 0)
820837
continue
821838

822839
if isinstance(field, PaddingField):
@@ -841,6 +858,24 @@ class will consider negative value as a placeholder.
841858
temp = field.pack(data, packet)
842859
except NoDefaultValue:
843860
temp = bytes(field.length)
861+
862+
if isinstance(field, SchemaField) and len(temp) < field.length:
863+
# NOTE: :meth:`unpack` hands a nested schema its whole declared
864+
# span, and the schema may read less of it than that. The octets
865+
# it left unread are still in the buffer :meth:`unpack` stored, so
866+
# they are re-emitted from there, as long as the buffer still
867+
# starts with what the nested schema packs to now; otherwise, or
868+
# for a schema that was never unpacked, the span is zero-filled.
869+
# Either way the field keeps the width its length field declares
870+
# (:issue:`1292`).
871+
#
872+
# A field reached through a
873+
# :class:`~pcapkit.corekit.fields.misc.SwitchField` is not handled
874+
# here: the PCAP-NG block selector declares the rest of the
875+
# *stream* as its span, which is no part of the field.
876+
buffer = self.__buffer__[field.name]
877+
tail = buffer[len(temp):field.length] if buffer.startswith(temp) else b''
878+
temp += tail + bytes(field.length - len(temp) - len(tail))
844879
self.__buffer__[field.name] = temp
845880

846881
self.post_process(packet)
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
# -*- coding: utf-8 -*-
2+
"""Base :class:`~pcapkit.protocols.schema.schema.Schema` round trips.
3+
4+
GitHub issue #1289: nothing on the packing path set ``__option_padding__``, so
5+
a padding field sized from it packed nothing, and a TCP or IPv4 header rebuilt
6+
from its schema came out shorter than its own length field said.
7+
8+
GitHub issue #1291: iterating a schema yielded the values its
9+
``post_process`` stores on the instance, which ``__getitem__`` refused, so
10+
``dict(schema)`` raised :exc:`KeyError`.
11+
12+
GitHub issue #1292: a :class:`~pcapkit.corekit.fields.misc.SchemaField` read
13+
its whole declared span but packed only what its nested schema consumed, so
14+
the octets the nested schema left unread were lost.
15+
16+
Every case builds its own octets in memory and reads no capture. Everything
17+
from :mod:`pcapkit` is imported inside each test, after
18+
:func:`~tests._support.reimport_once_per_class`, not at module load.
19+
20+
"""
21+
22+
import unittest
23+
24+
from tests._support import reimport_once_per_class
25+
26+
#: TCP header, Data Offset 6: NOP, EOOL, then two octets of padding.
27+
TCP_HEADER = bytes.fromhex('0050c3500000000100000000' '6002ffff00000000' '01000000')
28+
#: IPv4 header, IHL 6: NOP, EOOL, then two octets of padding.
29+
IPV4_HEADER = bytes.fromhex('460000180000000040060000c0a80001c0a80002' '01000000')
30+
31+
32+
def _nested_schemas(): # type: ignore[no-untyped-def]
33+
"""An outer schema whose nested schema reads less than its span."""
34+
from pcapkit.corekit.fields.misc import SchemaField
35+
from pcapkit.corekit.fields.numbers import UInt8Field
36+
from pcapkit.protocols.schema.schema import Schema, schema_final
37+
38+
@schema_final
39+
class Inner(Schema):
40+
x: int = UInt8Field()
41+
42+
@schema_final
43+
class Outer(Schema):
44+
n: int = UInt8Field()
45+
inner: Inner = SchemaField(length=lambda pkt: pkt['n'], schema=Inner)
46+
tail: int = UInt8Field()
47+
48+
return Inner, Outer
49+
50+
51+
class TestSchemaRoundTrip(unittest.TestCase):
52+
"""Pin the base schema's packing and mapping behaviour."""
53+
54+
def setUp(self) -> None:
55+
reimport_once_per_class(self)
56+
57+
def test_tcp_rebuild_keeps_option_padding(self) -> None:
58+
from pcapkit.protocols.transport.tcp import TCP
59+
60+
parsed = TCP(TCP_HEADER, len(TCP_HEADER))
61+
rebuilt = TCP.from_schema(parsed.schema.to_dict())
62+
self.assertEqual(bytes(rebuilt), TCP_HEADER)
63+
64+
def test_ipv4_rebuild_keeps_option_padding(self) -> None:
65+
from pcapkit.protocols.internet.ipv4 import IPv4
66+
67+
parsed = IPv4(IPV4_HEADER, len(IPV4_HEADER))
68+
rebuilt = IPv4.from_schema(parsed.schema.to_dict())
69+
self.assertEqual(bytes(rebuilt), IPV4_HEADER)
70+
71+
def test_iterated_keys_are_readable(self) -> None:
72+
from pcapkit.protocols.schema.internet.ipv4 import TSOption
73+
74+
schema = TSOption.unpack(bytes.fromhex('4408090000000001'), 8, None)
75+
keys = list(schema)
76+
self.assertIn('timestamp', keys)
77+
for key in keys:
78+
with self.subTest(key=key):
79+
schema[key] # pylint: disable=pointless-statement
80+
self.assertEqual(list(dict(schema)), keys)
81+
82+
def test_builtin_names_are_not_items(self) -> None:
83+
from pcapkit.protocols.schema.internet.ipv4 import TSOption
84+
85+
schema = TSOption.unpack(bytes.fromhex('4408090000000001'), 8, None)
86+
for name in ('__buffer__', 'pack', 'nonexistent'):
87+
with self.subTest(name=name), self.assertRaises(KeyError):
88+
schema[name] # pylint: disable=pointless-statement
89+
90+
def test_schema_field_keeps_unread_octets(self) -> None:
91+
_, outer = _nested_schemas()
92+
93+
raw = bytes.fromhex('0302eeee04')
94+
self.assertEqual(outer.unpack(raw, len(raw), None).pack(), raw)
95+
96+
def test_schema_field_keeps_declared_width(self) -> None:
97+
inner, outer = _nested_schemas()
98+
99+
raw = bytes.fromhex('0302eeee04')
100+
rebuilt = outer.from_dict(outer.unpack(raw, len(raw), None).to_dict())
101+
self.assertEqual(rebuilt.pack(), bytes.fromhex('0302000004'))
102+
self.assertEqual(outer(n=3, inner=inner(x=2), tail=4).pack(), bytes.fromhex('0302000004'))
103+
104+
105+
if __name__ == '__main__':
106+
unittest.main()

0 commit comments

Comments
 (0)