Skip to content

Commit d323fee

Browse files
committed
fix(reassembly): the deferred TCP analyser dispatches on AppType, not bare ports
Follow-up to #2418, which made `Deferred` generic over what its analyser dispatches on but left the TCP side of that constraint as `tuple[int, int]`. The owner's note on it: we are still using int tuples for transport ports, so move to AppType tuples. * `TCP.submit` resolves `bufid[1]` / `bufid[3]` through `Transport._make_port` before building the `Deferred`, in a new `TCP._make_ports` helper. A deferred analysis now dispatches on the same `AppType` member `TCP.src` / `TCP.dst` already read off a parsed header. * `_KT`'s second constraint is `tuple[AppType, AppType]`, and `Transport.analyze` declares that pair. Both constraints are now named registry values rather than one named value and one pair of numbers. * `Transport.analyze` tests the chosen port against `__proto__` exactly as it arrived and takes only that one through `int()`, so a bare `int` caller keeps working -- the method is in v1.4.1 -- while the registry is still read with the `int` key it declares. * `_make_ports` reaches `_make_port` through `TCP` rather than through `self.protocol`: `__protocol_type__` is an extension point whose analyser need only define `analyze`, so `self.protocol._make_port` would be an `AttributeError` for one that is not a `Transport`. * `DatagramID`'s ports stay bare `int`s, and its docstring now says why: it is the flow identity split out of `BufferID`, a dict key every toolkit adapter builds from a plain port number and which is dumped as part of the report. Every port a 16-bit field can hold resolves to a member -- an assignment to its canonical service, an IANA span to that span's label, anything else to an unregistered `unknown` -- without growing the registry, so this adds no way for reassembly to raise. UDP and SCTP need no change: neither has a reassembler, so `Transport.analyze` has no caller but `TCP.submit`. mypy over `pcapkit/` is byte-identical to mainline (98 errors, same set); `pylint` with the Makefile flags reports the same two pre-existing `_decode_next_layer` messages as mainline over the touched files; `isort -l100 -ppcapkit` is clean. The reassembly and transport suites pass (412 tests, 1408 subtests), as do the annotation-name, tier, docstring and public-API guards (204 tests, 3371 subtests). Reassembly over the sample captures resolves the same next layer as before, port for port.
1 parent 867616b commit d323fee

5 files changed

Lines changed: 384 additions & 50 deletions

File tree

‎pcapkit/foundation/reassembly/data/data.py‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@
1212
if TYPE_CHECKING:
1313
from typing import Callable, Optional
1414

15+
from pcapkit.const.reg.apptype import AppType
1516
from pcapkit.const.reg.transtype import TransType
1617
from pcapkit.foundation.reassembly.data.ip import Datagram as IP_Datagram
1718
from pcapkit.foundation.reassembly.data.tcp import Datagram as TCP_Datagram
1819
from pcapkit.protocols.protocol import ProtocolBase
1920

2021
# registry key an analyser dispatches a reassembled payload on; see ``Deferred``
21-
_KT = TypeVar('_KT', 'TransType', 'tuple[int, int]')
22+
_KT = TypeVar('_KT', 'TransType', 'tuple[AppType, AppType]')
2223

2324

2425
class Completion(EnumLookup, StrEnum):
@@ -148,23 +149,31 @@ class Deferred(Generic[_KT]):
148149
:meth:`Protocol.analyze <pcapkit.protocols.protocol.Protocol.analyze>`,
149150
which looks the next layer up by protocol registry number.
150151
* :meth:`TCP.submit <pcapkit.foundation.reassembly.tcp.TCP.submit>` builds a
151-
``Deferred[tuple[int, int]]``. It passes a ``(source, destination)`` port
152-
pair, because :meth:`Transport.analyze
152+
``Deferred[tuple[AppType, AppType]]``. It passes a
153+
``(source, destination)`` port pair, because :meth:`Transport.analyze
153154
<pcapkit.protocols.transport.transport.Transport.analyze>` overrides that
154155
parameter to one: a reassembled transport-layer payload carries no
155156
protocol number, so its application protocol is inferred from the ports.
156157
157-
Those are the two cases the type parameter is constrained to. The pairing
158-
the regression actually produced -- a port pair handed to an analyser
159-
declared over :class:`~pcapkit.const.reg.transtype.TransType` -- is
160-
rejected, which is the direction a real mismatch takes and the one
158+
Those are the two cases the type parameter is constrained to. Both are
159+
*named registry values* rather than one named value and one pair of bare
160+
port numbers: a port is an
161+
:class:`~pcapkit.const.reg.apptype.apptype.AppType` here, the same member
162+
:attr:`TCP.src <pcapkit.protocols.transport.tcp.TCP.src>` and
163+
:attr:`TCP.dst <pcapkit.protocols.transport.tcp.TCP.dst>` already read off a
164+
parsed header, so what the deferred analysis dispatches on is of a piece
165+
with what the eager path dispatches on, whichever reassembler built it.
166+
167+
The pairing the regression actually produced -- a port pair handed to an
168+
analyser declared over :class:`~pcapkit.const.reg.transtype.TransType` --
169+
is rejected, which is the direction a real mismatch takes and the one
161170
:issue:`2417` was about.
162171
163172
Rejecting the *reverse* pairing is not guaranteed by mypy alone, for a
164173
reason outside this class: |aenum|_ ships no type stubs, so under
165174
``ignore_missing_imports`` the ``aenum.IntEnum`` base of
166175
:class:`~pcapkit.const.reg.transtype.TransType` resolves to ``Any``. A
167-
``TransType`` is therefore accepted where a ``tuple[int, int]`` is
176+
``TransType`` is therefore accepted where a ``tuple[AppType, AppType]`` is
168177
expected, and a ``Deferred[TransType]`` built over the port-pair analyser
169178
type-checks clean. That is a gap in the dependency's type coverage rather
170179
than in the constraint, which would bite both ways were ``TransType`` fully

‎pcapkit/foundation/reassembly/data/tcp.py‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
from typing_extensions import TypeAlias
2121

22+
from pcapkit.const.reg.apptype import AppType
2223
from pcapkit.protocols.protocol import ProtocolBase
2324

2425
_AT = TypeVar('_AT', 'IPv4Address', 'IPv6Address')
@@ -84,7 +85,26 @@ def __init__(self, bufid: 'BufferID', dsn: 'int', ack: 'int', num: 'int', syn: '
8485

8586
@info_final
8687
class DatagramID(Info, Generic[_AT]):
87-
"""Data model for :term:`TCP <reasm.tcp.datagram>` original packet identifier."""
88+
"""Data model for :term:`TCP <reasm.tcp.datagram>` original packet identifier.
89+
90+
Note:
91+
The ports here stay bare :obj:`int` port numbers, where the pair
92+
:meth:`TCP.submit <pcapkit.foundation.reassembly.tcp.TCP.submit>` hands
93+
:class:`~pcapkit.foundation.reassembly.data.data.Deferred` is one of
94+
:class:`~pcapkit.const.reg.apptype.apptype.AppType` members
95+
(:issue:`2417`). The two are not the same thing to name: this is the
96+
flow's identity, split out of :data:`BufferID`, which every
97+
:mod:`pcapkit.toolkit` adapter builds from a plain port number -- the
98+
native ones by reading :attr:`AppType.port
99+
<pcapkit.const.reg.apptype.apptype.AppType.port>` off the parsed header,
100+
the third-party ones from whatever their own engine exposes -- and which
101+
is then used as a :class:`dict` key and dumped as part of the report.
102+
The deferred pair is a *dispatch* key for
103+
:meth:`Transport.analyze
104+
<pcapkit.protocols.transport.transport.Transport.analyze>`, which is
105+
what gains from carrying the service name.
106+
107+
"""
88108

89109
#: Source address.
90110
src: 'tuple[_AT, int]'
@@ -150,7 +170,7 @@ class Datagram(DeferredPacket, Info, Generic[_AT]):
150170
# :class:`~pcapkit.foundation.reassembly.data.ip.Datagram`, which applies
151171
# here identically: ``strict=False`` reports an incomplete payload buffer as
152172
# one contiguous ``bytes`` and analyses it.
153-
def __init__(self, completed: 'Completion', id: 'DatagramID[_AT]', index: 'tuple[int, ...]', header: 'bytes', payload: 'bytes | tuple[bytes, ...]', packet: 'Optional[ProtocolBase | Deferred[tuple[int, int]]]', conflict: 'tuple[tuple[int, int], ...]') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
173+
def __init__(self, completed: 'Completion', id: 'DatagramID[_AT]', index: 'tuple[int, ...]', header: 'bytes', payload: 'bytes | tuple[bytes, ...]', packet: 'Optional[ProtocolBase | Deferred[tuple[AppType, AppType]]]', conflict: 'tuple[tuple[int, int], ...]') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
154174

155175

156176
@info_final

‎pcapkit/foundation/reassembly/tcp.py‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import math
1313
from typing import TYPE_CHECKING
1414

15+
from pcapkit.const.reg.apptype import TransportProtocol as Enum_TransportProtocol
1516
from pcapkit.foundation.reassembly.data.data import Completion, Deferred
1617
from pcapkit.foundation.reassembly.data.tcp import (HOLE_OPEN_BOUND, Buffer, BufferID, Datagram,
1718
DatagramID, Fragment, HoleDescriptor, Packet)
@@ -21,6 +22,8 @@
2122
if TYPE_CHECKING:
2223
from typing import Type
2324

25+
from pcapkit.const.reg.apptype import AppType as Enum_AppType
26+
2427
__all__ = ['TCP']
2528

2629

@@ -653,6 +656,61 @@ def _merge_overlap(gap: 'list[tuple[int, int]]', old: 'bytes', new: 'bytes',
653656
index = stop
654657
return bytes(merged), conflicts
655658

659+
@staticmethod
660+
def _make_ports(bufid: 'BufferID') -> 'tuple[Enum_AppType, Enum_AppType]':
661+
"""The flow's ``(source, destination)`` ports, as application types.
662+
663+
Arguments:
664+
bufid: :term:`buffer <reasm.tcp.buffer>` identifier, whose positions
665+
``1`` and ``3`` are the source and destination ports.
666+
667+
Returns:
668+
The pair :meth:`submit` hands
669+
:class:`~pcapkit.foundation.reassembly.data.data.Deferred`, i.e. what
670+
:meth:`Transport.analyze
671+
<pcapkit.protocols.transport.transport.Transport.analyze>` dispatches
672+
the reassembled payload on (:issue:`2417`).
673+
674+
Important:
675+
Every port a 16-bit header field can hold resolves to a member, so
676+
this raises for nothing that can come off the wire:
677+
:meth:`AppType.get <pcapkit.const.reg.apptype.apptype.AppType.get>`
678+
answers an assignment with its canonical service, a port inside a
679+
documented IANA span with that span's label (``reserved`` for ``0``),
680+
and one in no span at all with an unregistered ``unknown`` member --
681+
never :obj:`None`, and without growing the registry (:issue:`860`).
682+
It rejects only a port outside ``0``-``65535``, a non-:obj:`int`, or
683+
a :obj:`bool` (:issue:`2287`), none of which a
684+
:mod:`pcapkit.toolkit` adapter can read out of a TCP header.
685+
686+
Note:
687+
The resolution is reached through
688+
:class:`~pcapkit.protocols.transport.tcp.TCP` rather than through
689+
:attr:`self.protocol
690+
<pcapkit.foundation.reassembly.reassembly.ReassemblyBase.protocol>`,
691+
which is what :meth:`submit` reads the analyser itself off. That is
692+
deliberate: ``__protocol_type__`` is an extension point, and an
693+
analyser plugged into it need only define ``analyze`` -- it is not
694+
required to be a
695+
:class:`~pcapkit.protocols.transport.transport.Transport` subclass
696+
and so need not have ``_make_port`` at all, which reaching it
697+
through ``self.protocol`` would turn into an
698+
:exc:`AttributeError`. What a TCP port *means* belongs to the TCP
699+
protocol either way, not to whatever consumes the payload, which is
700+
also why the transport below is named outright rather than read off
701+
the analyser.
702+
703+
"""
704+
# NOTE: ``_make_port`` is protected, and reached from outside its own
705+
# class as :meth:`SCTP._decode_next_layer
706+
# <pcapkit.protocols.transport.sctp.SCTP._decode_next_layer>` reaches
707+
# ``ProtocolBase._decode_next_layer``. Duplicating it here instead would
708+
# put a second port normaliser beside the maker path's, free to drift
709+
# from it; it is idempotent, so a ``bufid`` that already holds a member
710+
# passes through unchanged.
711+
return (TCP_Protocol._make_port(bufid[1], Enum_TransportProtocol.tcp), # pylint: disable=protected-access
712+
TCP_Protocol._make_port(bufid[3], Enum_TransportProtocol.tcp)) # pylint: disable=protected-access
713+
656714
def submit(self, buf: 'Buffer', *, bufid: 'BufferID', # type: ignore[override] # pylint: disable=arguments-differ
657715
timeout: 'bool' = False) -> 'list[Datagram]':
658716
"""Submit reassembled payload.
@@ -667,6 +725,22 @@ def submit(self, buf: 'Buffer', *, bufid: 'BufferID', # type: ignore[override]
667725
Returns:
668726
Reassembled :term:`packets <reasm.tcp.datagram>`.
669727
728+
Important:
729+
The ``(source, destination)`` pair handed to
730+
:class:`~pcapkit.foundation.reassembly.data.data.Deferred` is a pair
731+
of :class:`~pcapkit.const.reg.apptype.apptype.AppType` members
732+
rather than of the bare port numbers :data:`BufferID` holds
733+
(:issue:`2417`), so a deferred analysis dispatches on the same named
734+
service a parsed header already carries at
735+
:attr:`TCP.src <pcapkit.protocols.transport.tcp.TCP.src>`. The
736+
resolution is :meth:`Transport._make_port
737+
<pcapkit.protocols.transport.transport.Transport._make_port>`, so it
738+
is the one the maker path uses and cannot drift from it. See
739+
:meth:`_make_ports` for why it is reached through
740+
:class:`~pcapkit.protocols.transport.tcp.TCP` rather than through
741+
:attr:`self.protocol
742+
<pcapkit.foundation.reassembly.reassembly.ReassemblyBase.protocol>`.
743+
670744
"""
671745
datagram = [] # type: list[Datagram] # reassembled datagram
672746

@@ -751,7 +825,8 @@ def submit(self, buf: 'Buffer', *, bufid: 'BufferID', # type: ignore[override]
751825
index=tuple(buffer.ind),
752826
header=buf.hdr,
753827
payload=bytes(payload),
754-
packet=Deferred(self.protocol.analyze, (bufid[1], bufid[3]), bytes(payload)),
828+
packet=Deferred(self.protocol.analyze,
829+
self._make_ports(bufid), bytes(payload)),
755830
conflict=conflict,
756831
)
757832
datagram.append(packet)

‎pcapkit/protocols/transport/transport.py‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,21 +132,58 @@ def register(cls, code: 'int', protocol: 'ModuleDescriptor[ProtocolBase] | Type[
132132
cls.__proto__[code] = entry
133133

134134
@classmethod
135-
def analyze(cls, ports: 'tuple[int, int]', payload: 'bytes', **kwargs: 'Any') -> 'ProtocolBase': # type: ignore[override] # pylint: disable=arguments-renamed
135+
def analyze(cls, ports: 'tuple[Enum_AppType, Enum_AppType]', payload: 'bytes', **kwargs: 'Any') -> 'ProtocolBase': # type: ignore[override] # pylint: disable=arguments-renamed
136136
"""Analyse packet payload.
137137
138138
Args:
139-
ports: Source & destination port numbers.
139+
ports: Source & destination ports, as the application types
140+
:meth:`_make_port` resolves them to -- the same values
141+
:attr:`TCP.src <pcapkit.protocols.transport.tcp.TCP.src>` and
142+
:attr:`TCP.dst <pcapkit.protocols.transport.tcp.TCP.dst>` read.
140143
payload: Packet payload.
141144
**kwargs: Arbitrary keyword arguments.
142145
143146
Returns:
144147
Parsed payload as a :class:`~pcapkit.protocols.protocol.Protocol`
145148
instance.
146149
150+
Important:
151+
A bare :obj:`int` port still resolves, so the tightened annotation
152+
is a declaration of what callers should pass rather than a new
153+
rejection -- the method predates 1.5.0, and a member and the port it
154+
carries are the same key of a :obj:`int`-keyed mapping anyway:
155+
:meth:`AppType.__hash__
156+
<pcapkit.const.reg.apptype.apptype.AppType.__hash__>` is its port's
157+
and :meth:`AppType.__eq__
158+
<pcapkit.const.reg.apptype.apptype.AppType.__eq__>` compares against
159+
it. Which is why the port chosen below is tested against
160+
:attr:`__proto__` exactly as it arrived, and only the chosen one is
161+
taken through :func:`int` --
162+
:meth:`AppType.__int__ <pcapkit.const.reg.apptype.apptype.AppType.__int__>`,
163+
i.e. :attr:`AppType.port
164+
<pcapkit.const.reg.apptype.apptype.AppType.port>`, for a member and
165+
the identity for an :obj:`int` -- so that the registry is read with
166+
the :obj:`int` key it declares. Reading ``.port`` directly would
167+
have made the :obj:`int` case an :exc:`AttributeError`.
168+
169+
Nothing is written back on a miss either way, so a payload on an
170+
unregistered port does not grow a process-wide registry -- see
171+
:meth:`ProtocolBase._lookup_registry
172+
<pcapkit.protocols.protocol.ProtocolBase._lookup_registry>`.
173+
174+
.. versionchanged:: 1.5.0
175+
176+
``ports`` is a pair of
177+
:class:`~pcapkit.const.reg.apptype.apptype.AppType` members rather
178+
than of bare :obj:`int` port numbers, so that the one caller that
179+
reaches this method -- :meth:`TCP.submit
180+
<pcapkit.foundation.reassembly.tcp.TCP.submit>`, through
181+
:class:`~pcapkit.foundation.reassembly.data.data.Deferred` -- hands
182+
over the same named ports a parsed header carries (:issue:`2417`).
183+
147184
"""
148-
protocol = cls._lookup_next_layer(
149-
cls.__proto__, ports[0] if ports[0] in cls.__proto__ else ports[1])
185+
port = ports[0] if ports[0] in cls.__proto__ else ports[1]
186+
protocol = cls._lookup_next_layer(cls.__proto__, int(port))
150187

151188
payload_io = io.BytesIO(payload)
152189
try:

0 commit comments

Comments
 (0)