Skip to content

Commit b853afe

Browse files
committed
Merge commit '73f730757' into fold24
2 parents 3bd890f + 73f7307 commit b853afe

17 files changed

Lines changed: 1204 additions & 74 deletions

‎docs/source/pcapkit/protocols/protocol.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Internal Definitions below.
107107
.. automethod:: _lookup_next_layer
108108
.. automethod:: _decode_next_layer
109109
.. automethod:: _import_next_layer
110+
.. automethod:: _empty_next_layer
110111
.. automethod:: _parse_next_layer
111112
.. automethod:: _get_context
112113

@@ -117,6 +118,10 @@ Internal Definitions below.
117118
.. autoattribute:: _protos
118119
.. autoattribute:: _seekset
119120
.. autoattribute:: _sigterm
121+
.. autoattribute:: __reconstructing__
122+
.. autoattribute:: __short_read__
123+
.. autoattribute:: _uncaptured
124+
.. autoattribute:: _short_of_header
120125
.. autoattribute:: _past_layer_limit
121126
.. autoattribute:: __data__
122127

‎pcapkit/corekit/fields/collections.py‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,15 @@ class ListField(FieldBase[List[_TL]], Generic[_TL]):
8787
A list whose octets hold fewer items than ``count`` ended with the data
8888
before the rest, and reports them as :attr:`shortfall`, so that
8989
:meth:`Schema.unpack <pcapkit.protocols.schema.Schema.unpack>`
90-
records the cut; the items absent are not made up.
90+
records the cut; the items absent are not made up. A schema item it counts
91+
is read with ``__data_end__`` in its packet, since its octets end where the
92+
data does, so an item the data ends inside records the cut as its short
93+
read rather than warn that its fields run past the length it was given.
9194
9295
.. versionchanged:: 1.6.0
9396
94-
Takes ``count`` (:issue:`2711`).
97+
Takes ``count`` (:issue:`2711`), and reads a schema item it counts as
98+
ending with the data (:issue:`2749`).
9599
96100
"""
97101

@@ -209,15 +213,18 @@ def unpack(self, buffer: 'bytes | IO[bytes]', packet: 'dict[str, Any]') -> 'byte
209213
consumes nothing from ``buffer``, or if schema items short of the
210214
field's length cannot be zero-filled.
211215
212-
When ``buffer`` falls short of the field's length, schema items are read
213-
from its octets zero-filled to that length, as
216+
When ``buffer`` falls short of the field's length, the schema item it
217+
ends inside is read as though its missing octets were zeros, as
214218
:meth:`FieldBase.unpack <pcapkit.corekit.fields.field.FieldBase.unpack>`
215-
reads any other field, so the items cover the length declared.
219+
reads any other field, and the list ends with that item: none is read
220+
from the zeros past it, which hold no octet of the data.
216221
217222
.. versionchanged:: 1.6.0
218223
219-
Schema items short of the field's length are zero-filled to it, where
220-
an item past the data was refused as consuming nothing (:issue:`2686`).
224+
A list of schema items the data ends inside ends with the data, the
225+
item it ends inside read with its missing octets as zeros, where an
226+
item past the data was refused as consuming nothing (:issue:`2686`,
227+
:issue:`2756`).
221228
222229
"""
223230
length = self._length
@@ -263,16 +270,20 @@ def unpack(self, buffer: 'bytes | IO[bytes]', packet: 'dict[str, Any]') -> 'byte
263270
file.seek(start, io.SEEK_SET)
264271
if present < length:
265272
with _zero_filled_items(self.name, length, file.read()) as filled:
266-
return self._unpack_items(io.BytesIO(filled), packet, is_schema)
273+
return self._unpack_items(filled, packet, is_schema, present)
267274
return self._unpack_items(file, packet, is_schema)
268275

269-
def _unpack_items(self, file: 'IO[bytes]', packet: 'dict[str, Any]', is_schema: 'bool') -> 'list[_TL]':
276+
def _unpack_items(self, file: 'IO[bytes]', packet: 'dict[str, Any]', is_schema: 'bool',
277+
present: 'int' = -1) -> 'list[_TL]':
270278
"""Unpack the field's items from ``file``.
271279
272280
Args:
273281
file: Stream the items are read from.
274282
packet: Packet data.
275283
is_schema: Whether the items are schemas.
284+
present: Octets of ``file`` the data holds, past which it holds the
285+
zeros :meth:`unpack` filled it with; negative where it holds
286+
no zeros.
276287
277288
Returns:
278289
Unpacked items.
@@ -289,8 +300,9 @@ def _unpack_items(self, file: 'IO[bytes]', packet: 'dict[str, Any]', is_schema:
289300
# which is what it read, but the schema branch sizes it by ``len(data)``,
290301
# which is only what the schema *recorded*. A schema that reads nothing
291302
# records nothing, so ``length -= len(data)`` makes no progress and the
292-
# loop spins forever. The zero-fill in ``unpack`` gives every item octets,
293-
# but an item schema may still consume none of them. Remembering where the
303+
# loop spins forever. The zero-fill in ``unpack`` gives the item the data
304+
# ends inside octets to read, and every item before it reads octets of the
305+
# data, but an item schema may still consume none of them. Remembering where the
294306
# previous item ended is what bounds the iteration count, since it does
295307
# not depend on what the schema reports. Cf. #431, which is the same
296308
# defect in the ``OptionField`` subclass.
@@ -304,10 +316,17 @@ def _unpack_items(self, file: 'IO[bytes]', packet: 'dict[str, Any]', is_schema:
304316

305317
temp = [] # type: list[_TL]
306318
while length > 0:
319+
# NOTE: An item starting past the octets present would be made of the zero-fill alone,
320+
# one the capture never held, so the list ends with the data (#2756).
321+
if 0 <= present <= offset - start:
322+
break
307323
field = item_type(packet)
308324

309325
if is_schema:
310-
data = cast('SchemaField', field).unpack(file, packet)
326+
# NOTE: A counted list runs to the end of the data, so an item it counts
327+
# running past the octets left is cut, not overrunning a length (#2749).
328+
context = dict(packet, __data_end__=True) if len(temp) < self._count else packet
329+
data = cast('SchemaField', field).unpack(file, context)
311330

312331
end = file.tell()
313332
if end <= offset:

‎pcapkit/corekit/fields/field.py‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import abc
2424
import contextlib
2525
import contextvars
26+
import io
2627
import re
2728
import struct
2829
from typing import TYPE_CHECKING, Generic, TypeVar, cast
@@ -120,22 +121,24 @@ def _zero_pad_budget() -> 'Iterator[list[int]]':
120121

121122

122123
@contextlib.contextmanager
123-
def _zero_filled_items(name: 'str', length: 'int', data: 'bytes') -> 'Iterator[bytes]':
124+
def _zero_filled_items(name: 'str', length: 'int', data: 'bytes') -> 'Iterator[IO[bytes]]':
124125
"""Zero-fill the octets of a list of schema items to its declared width.
125126
126127
:meth:`FieldBase.unpack` reads a field the data ends inside as though its
127128
missing octets were zeros, and :meth:`ListField.unpack
128-
<pcapkit.corekit.fields.collections.ListField.unpack>` gives a list of
129-
schema items the same reading here, so its items cover the width it
130-
declares (:issue:`2686`). The items are read inside the block.
129+
<pcapkit.corekit.fields.collections.ListField.unpack>` gives the schema
130+
item the data ends inside the same reading here (:issue:`2686`). The items
131+
are read inside the block, and none from the zeros past that item, which
132+
hold no octet of the data (:issue:`2756`).
131133
132134
Args:
133135
name: Field name.
134136
length: Octets the field declares.
135137
data: Octets actually present, fewer than ``length``.
136138
137139
Yields:
138-
``data``, zero-filled to ``length``.
140+
A stream of ``data``, zero-filled to ``length``. The zeros left unread
141+
past where the stream ends up are not counted as octets read.
139142
140143
Raises:
141144
FieldValueError: If ``length`` is past
@@ -157,8 +160,8 @@ def _zero_filled_items(name: 'str', length: 'int', data: 'bytes') -> 'Iterator[b
157160
ledger = [0, 0]
158161
_zero_pad_ledger.set(ledger)
159162

160-
# NOTE: The fill is made-up schema objects, not zeros, so it gets no free band or one-off
161-
# allowance: a 15-octet SETTINGS frame declaring 65,532 octets made 10,922 pairs in 7.5 MB.
163+
# NOTE: The fill makes up the rest of the item the data ends inside, a schema object, not
164+
# zeros, so it gets no free band or one-off allowance (#2686); past that item it makes none.
162165
padding = length - len(data)
163166
shortfall, ratio = config.MAX_ZERO_PAD_SHORTFALL, config.ZERO_PAD_BUDGET_RATIO
164167
if shortfall != -1:
@@ -174,14 +177,17 @@ def _zero_filled_items(name: 'str', length: 'int', data: 'bytes') -> 'Iterator[b
174177
ledger[1] += padding
175178

176179
# NOTE: The items credit the zeros they read as octets supplied, so they are taken off in
177-
# advance; items that fail credit an unknown share, so the octets read go back as they were.
180+
# advance and those left unread given back (#2756); items that fail credit an unknown share,
181+
# so the octets read go back as they were.
178182
read = ledger[0]
179183
ledger[0] -= padding
184+
filled = io.BytesIO(data + bytes(padding))
180185
try:
181-
yield data + bytes(padding)
186+
yield filled
182187
except BaseException:
183188
ledger[0] = read
184189
raise
190+
ledger[0] += length - max(filled.tell(), len(data))
185191

186192

187193
#: Pattern[str]: Matches a leading, optionally byte-order-prefixed negative

‎pcapkit/protocols/application/httpv2/protocol.py‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,10 @@ class HTTPv2(HTTPBase[Data_HTTP, Schema_HTTP],
207207
class, where it was kept as :class:`~pcapkit.protocols.misc.raw.protocol.Raw`
208208
(:issue:`2536`).
209209
* A ``SETTINGS`` frame the capture cut inside its settings parses, with the
210-
settings past the data read as zeros, as a cut ``DATA`` frame's data is,
211-
where it was :class:`~pcapkit.protocols.misc.raw.protocol.Raw` (:issue:`2659`,
212-
:issue:`2686`).
210+
setting the cut lands inside read as zeros past it, as a cut ``DATA``
211+
frame's data is, and no setting past the data, where it was
212+
:class:`~pcapkit.protocols.misc.raw.protocol.Raw` (:issue:`2659`,
213+
:issue:`2686`, :issue:`2756`).
213214
* Each enumeration field of :meth:`make` and of the frame makers takes
214215
a member or an :class:`int` code, resolved with the enumeration's
215216
``get``; a name, a :obj:`bool` for a field wider than one bit, or a
@@ -1437,6 +1438,15 @@ def _make_http_settings(self, frame: 'Optional[Data_SettingsFrame]' = None, *,
14371438
frame with no parameters, which :rfc:`9113#section-6.5` permits,
14381439
rather than being rejected (:issue:`2274`).
14391440
1441+
.. versionchanged:: 1.6.0
1442+
1443+
A ``frame`` the capture cut inside its settings, as its
1444+
``__short_read__`` records, packs the settings its parse read from the
1445+
octets its ``packet`` holds with zeros after them to the Length it
1446+
declares, since that parse reads no setting past the data, so its
1447+
rebuild declares that Length too; with its settings edited, the Length
1448+
is computed as for a whole frame (:issue:`2756`).
1449+
14401450
"""
14411451
if frame is not None:
14421452
ack = frame.flags.ACK
@@ -1478,6 +1488,16 @@ def _make_http_settings(self, frame: 'Optional[Data_SettingsFrame]' = None, *,
14781488
raise ProtocolError(f'HTTP/2: [Type {Enum_Frame.SETTINGS}] invalid settings: '
14791489
f'{settings!r}')
14801490

1491+
# NOTE: An unedited cut frame packs the octets its ``packet`` captured, zero to the pair, and
1492+
# keeps its Length in the zeros past them (#2756); a dict rebuilds as the base data model.
1493+
record = frame.get('__short_read__') if isinstance(frame, Data_HTTP) else None
1494+
if frame is not None and record is not None and isinstance(settings_val, list):
1495+
packed = b''.join(pair.pack() for pair in settings_val)
1496+
# A cut in the frame header leaves no setting captured.
1497+
read = cast('bytes', frame.get('packet', b''))[:record[1]] if record[0] == 'frame' else b''
1498+
if packed == read + bytes(-len(read) % 6) and len(packed) < frame.length:
1499+
settings_val = packed + bytes(frame.length - len(packed))
1500+
14811501
return Schema_SettingsFrame(
14821502
settings=settings_val,
14831503
), flags

‎pcapkit/protocols/internet/internet.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -400,8 +400,9 @@ def _next_layer_class(self, proto: 'Optional[int]', file_: 'bytes', length: 'int
400400
extension: if is extension header, see :meth:`_next_exthdr_depth`
401401
402402
Returns:
403-
:class:`~pcapkit.protocols.misc.no_payload.protocol.NoPayload` if there is
404-
nothing to parse; :class:`~pcapkit.protocols.misc.raw.protocol.Raw` if the
403+
The class :meth:`~pcapkit.protocols.protocol.Protocol._empty_next_layer`
404+
gives if there is nothing to parse;
405+
:class:`~pcapkit.protocols.misc.raw.protocol.Raw` if the
405406
parse stops at this layer, or the next layer is an IPv6 extension
406407
header past :data:`~pcapkit.utilities.config.EXTENSION_HEADER_LIMIT` in a row; otherwise the
407408
class registered for ``proto``. Paired with it, the keywords that
@@ -415,9 +416,9 @@ class registered for ``proto``. Paired with it, the keywords that
415416
layer is inside a payload being rebuilt (:issue:`1619`).
416417
417418
"""
418-
if min(length, len(file_)) == 0:
419-
from pcapkit.protocols.misc.no_payload.protocol import NoPayload # isort: skip # pylint: disable=import-outside-toplevel
420-
return NoPayload, {}
419+
empty = self._empty_next_layer(file_, length)
420+
if empty is not None:
421+
return empty, {}
421422
if self._sigterm:
422423
from pcapkit.protocols.misc.raw.protocol import Raw # isort: skip # pylint: disable=import-outside-toplevel
423424
return Raw, {}

‎pcapkit/protocols/link/frad/protocol.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -456,9 +456,9 @@ def _import_next_layer(self, proto: 'int', length: 'Optional[int]' = None, *, #
456456

457457
if TYPE_CHECKING:
458458
protocol: 'Type[ProtocolBase]'
459-
if not min(length, len(file_)):
460-
from pcapkit.protocols.misc.no_payload.protocol import \
461-
NoPayload as protocol # isort: skip # pylint: disable=import-outside-toplevel
459+
empty = self._empty_next_layer(file_, length)
460+
if empty is not None:
461+
protocol = empty
462462
elif self._sigterm:
463463
from pcapkit.protocols.misc.raw.protocol import \
464464
Raw as protocol # isort: skip # pylint: disable=import-outside-toplevel

‎pcapkit/protocols/link/linux_sll/protocol.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -368,9 +368,9 @@ def _import_next_layer(self, proto: 'int', length: 'Optional[int]' = None, *, #
368368

369369
if TYPE_CHECKING:
370370
protocol: 'Type[ProtocolBase]'
371-
if not min(length, len(file_)):
372-
from pcapkit.protocols.misc.no_payload.protocol import \
373-
NoPayload as protocol # isort: skip # pylint: disable=import-outside-toplevel
371+
empty = self._empty_next_layer(file_, length)
372+
if empty is not None:
373+
protocol = empty
374374
elif self._sigterm:
375375
from pcapkit.protocols.misc.raw.protocol import \
376376
Raw as protocol # isort: skip # pylint: disable=import-outside-toplevel

0 commit comments

Comments
 (0)