Reassembly Base Class¶
pcapkit.foundation.reassembly.reassembly contains
Reassembly, the abstract base
class of a custom reassembly class, and
ReassemblyBase, which it and
the built-in IP, TCP and DTLS reassembly classes derive from. The algorithms
follow RFC 791 and RFC 815.
- class pcapkit.foundation.reassembly.reassembly.Reassembly[_PT: Info, _DT: Info, _IT: tuple, _BT: Info](*, strict=True, store=True, timeout=None)[source]¶
Bases:
ReassemblyBase[_PT,_DT,_IT,_BT],Generic[_PT,_DT,_IT,_BT]Base reassembly class.
Example
Registration is opt-in. Pass keyword argument
protocolat class definition to register the reassembly under that protocol name:class MyProtocol(Reassembly, protocol='my_protocol'): ...
Omit it and the subclass is not registered, which is how a class that is not meant to be selectable by name declines:
class MyMixin(Reassembly): # not registered ...
Such a class can still be registered later, on demand:
Extractor.register_reassembly('my_mixin', MyMixin)
An engine feeds a registered reassembly through the
pcapkit.toolkitadapter it holds for that name, and anExtractorenables it by name:PCAP.register_reassembly('my_protocol', my_adapter) Extractor('in.pcap', reassembly=['my_protocol'])
- Parameters:
strict (
bool) – ifTrue, report a datagram that is not completely reassembled as the tuple of its received runs; otherwise as one contiguous payload, its holes zero-filled – or, for IP while the total length is unknown, only the prefix up to the first holestore (
bool) – if store reassembled datagram in memory, i.e.,self._dtgram(if not, datagram will be discarded after callback)timeout (
float|None) – reassembly timeout in seconds, on the capture’s own clock;Noneselects the protocol’s__timeout__default
Changed in version 1.3.0:
nameandprotocolare read from__protocol_name__and__protocol_type__, where they were abstract properties each reassembly implemented, and the built-in names are short:'IPv4'rather than'Internet Protocol version 4'. A subclass registers itself withExtractorat class definition.Changed in version 1.5.0: Registration is opt-in, under the
protocolclass keyword; 1.4.x registered every subclass, under itsnamewhen the keyword was omitted (#514). Thetimeoutargument is added: a buffer older than it on the capture’s clock is abandoned.See also
For customisation and extension, see Customisation & Extensions.
- property name: str¶
Protocol name of current reassembly class.
Note
Also a class variable, set by
__protocol_name__.
- property protocol: Type[pcapkit.protocols.protocol.ProtocolBase]¶
Protocol of current reassembly class.
Note
Also a class variable, set by
__protocol_type__.
- property registry: dict[str, ModuleDescriptor[ReassemblyBase] | Type[ReassemblyBase]]¶
Mapping of protocol names to reassembly classes.
Note
A class variable only, defined on
ReassemblyMeta. It is not per-class: it reads__reassembly__, the one table every reassembly registration lands in.
- __protocol_type__: Type[ProtocolBase]¶
Protocol of current reassembly object.
- __callback_fn__: list[Callable[[List[_DT]], None]]¶
List of callback functions upon reassembled datagram.
- _flag_s: bool¶
Strict mode flag. If set to
True, a datagram not completely reassembled is reported as the tuple of its received runs; otherwise, as one contiguous payload, its holes zero-filled – or, for IP while the total length is unknown, only the prefix up to the first hole.- Type:
- _flag_d: bool¶
Store mode flag. If set to
True, all reassembled datagram will be stored in memory, i.e.,self._dtgram; otherwise, datagram will be discarded after callback.- Type:
- _flag_n: bool¶
New datagram flag. If set to
True, theself._dtgramwill be repopulated.- Type:
- _flag_c: bool¶
Callback flag. Set while the callbacks run, so a callback reading
datagramgetsself._dtgramrather than a submission that would run them again.- Type:
- _timeout: float¶
Reassembly timeout in seconds, on the capture’s clock.
math.infdisables expiry.- Type:
- _parse_keywords: dict[str, Any]¶
Keyword arguments a reassembled payload’s parse takes: the stops and context the engine parses its frames with, as
EngineBase._setup_reassemblyhands them over (#2933).
- _buffer: dict[_IT, _BT]¶
Dict buffer field. This field is used to store reassembled packets in the form of
{bufid: buffer}.
Defaults
- __timeout__: float = inf¶
Default reassembly timeout, in seconds, for this protocol – overridden per protocol, e.g.
IPv6.__timeout__.math.infmeans “never expire”, which is the base default because nothing here knows what a protocol’s specification asks for.- Type:
Properties
- property timeout: float¶
Reassembly timeout, in seconds, of the current reassembly object.
A buffer whose first-arriving fragment is older than this many seconds on the capture’s own clock is abandoned rather than held for the life of the object – see
expire().math.infdisables expiry.
- property count: int¶
Total number of reassembled packets.
Read from a callback, it counts the stored datagrams only, as
datagramreports them there.
- property datagram: tuple[_DT, ...]¶
Reassembled datagram.
Read from a callback, it holds the stored datagrams only, without submitting the outstanding buffers; see
fetch().- Raises:
UnsupportedCall – If
self._flag_dis set toFalse.
Methods
- abstractmethod reassembly(info)¶
Reassembly procedure.
- Parameters:
info (
_PT) – info record of packets to be reassembled
- abstractmethod submit(buf, **kwargs)¶
Submit reassembled payload.
- Parameters:
buf (
_BT) – buffer dict of reassembled packets**kwargs (
Any) – arbitrary keyword arguments; implementations acceptexpired, set when the buffer is being submitted becauseexpire()abandoned it rather than because it completed or the capture ended, andstore, set when the buffer has left_bufferfor good, which they pass on to_notify()
- Return type:
list[_DT]
Changed in version 1.7.0: A custom
submitmust acceptstoreand pass it on to_notify(), which stores the datagrams before the callbacks run;_release()stores what one droppingstorereturns, after its callbacks.expire()stores what it returns, so a caller must not also extend_dtgramwith it (#2856). Thetimeoutflag is renamedexpired, with no alias, astimeoutis a number of seconds everywhere else (#2839).
- expire(timestamp)¶
Abandon every buffer whose reassembly timeout has elapsed.
- Parameters:
timestamp (
float) – Current time on the capture’s clock, in seconds since the Unix epoch – i.e. the capture timestamp of the packet just handed toreassembly().- Return type:
list[_DT]- Returns:
Datagrams of the buffers abandoned, reported with
Completion.TIMEOUTand already stored indatagram, through_release(). Empty when nothing expired, which is the overwhelmingly common case.
A buffer expires when more than
timeoutseconds separatetimestampfrom the capture timestamp of its first-arriving fragment, which is the deadline RFC 8200 Section 4.5 states (“within 60 seconds of the reception of the first-arriving fragment”) and which RFC 815 suggests implementing by reading “the clock when each first fragment arrives”. A later fragment therefore does not extend the deadline.Note
The clock is the capture’s timestamps, the only evidence an offline parser has that time has moved on. Fed by hand, a reassembly object sees only the packets handed to it, so a buffer followed by none is reported as
Completion.PARTIALat the end of the capture. TheExtractorcallsadvance()with every frame’s timestamp, so there a buffer expires once any later frame passes its deadline.Changed in version 1.7.0: The
Extractoradvances the clock on every frame, where it advanced only on the packets a reassembly object was fed (#2814). It stores what it returns, where its caller stored it after the callbacks, so a callback that raises cannot lose a datagram and a caller must not store one again (#2856).
- advance(timestamp)¶
Advance the capture clock, keeping what it times out.
- Parameters:
timestamp (
float) – Capture timestamp of the current frame, in seconds since the Unix epoch.
The datagrams
expire()abandons attimestampjoindatagram. TheExtractorcalls this with every frame’s timestamp, before the frame is fed, so the clock does not wait on this protocol’s own traffic.Added in version 1.7.0.
- fetch()¶
Fetch datagram.
Fetch reassembled datagrams from
self._dtgramand returns a tuple of such datagrams.If no cache found, the method will call
self.submitto forcedly obtain newly reassembled payload. Otherwise, the already calculatedself._dtgramwill be returned.Called from a callback, it returns what
_dtgramholds and submits nothing, since a submission would run the callbacks again.Changed in version 1.7.0: A callback reading
datagramwhile a buffer is outstanding gets the stored datagrams, where it recursed untilRecursionError(#2867).
- index(pkt_num)¶
Return datagram index.
- run(packets)¶
Run automatically.
- Parameters:
packets (
list[_PT]) – list of packet dicts to be reassembled
- classmethod register_callback(callback, *, index=None)¶
Register callback function.
- Parameters:
callback (
Callable[[List[_DT]],None]) – callback function, which will be called when reassembled datagram is obtained, with the list of reassembled datagrams as its only argumentindex (
int|None) – index to be inserted in the callback list; by default, the callback will be appended to the end of the list
- Return type:
Every callback runs on each submission. One raising an
Exceptiondoes not stop the rest, and the first such error propagates once they have run.Changed in version 1.7.0: Renamed from
register, with no alias, to matchTraceFlow.register_callback(#2839). A callback that raises no longer stops the ones after it (#2881).
Data Models
- classmethod __init_subclass__(protocol=None, *args, **kwargs)[source]¶
Initialise subclass.
This method is to be used for registering the reassembly class to
Extractorclass.- Parameters:
- Raises:
UnsupportedCall – If any unrecognised class keyword is given.
- Return type:
Registration is opt-in: the subclass is registered if and only if
protocolis given. This is what lets a subclass decline registration rather than having to inheritReassemblyBaseto avoid it, and it matchesEnumSchema.__init_subclass__, which guards on its owncodekeyword the same way.Note
__protocol_name__is not an opt-in. It supplies thenamethe reassembly reports, which it does whether or not the class is registered; only the keyword decides registration.See also
For more details, please refer to
pcapkit.foundation.extraction.Extractor.register_reassembly().
- __call__(packet)¶
Call packet reassembly.
- Parameters:
packet (
_PT) – packet dict to be reassembled (detailed format described in corresponding protocol)
Utilities
- _release(buf, **kwargs)¶
Submit a buffer that has left
_bufferfor good, storing its datagrams exactly once.- Parameters:
- Return type:
list[_DT]- Returns:
A
submit()that passesstoreon to_notify()has stored them before its callbacks ran. One that dropsstorestored none, so they are stored here, after its callbacks.Added in version 1.7.0.
- _notify(datagrams, *, store=False)¶
Run each callback on the datagrams
submit()built.Every callback runs, through
run_callbacks(): the firstExceptionone raises propagates once the last has run. While they run,fetch()returns what_dtgramholds, so a callback readingdatagramdoes not run them again.Added in version 1.7.0.
Internal Definitions¶
- class pcapkit.foundation.reassembly.reassembly.ReassemblyBase[_PT: Info, _DT: Info, _IT: tuple, _BT: Info](*, strict=True, store=True, timeout=None)[source]¶
Bases:
ReduceAsProtocol2,Generic[_PT,_DT,_IT,_BT]Base class for reassembly procedure.
- Parameters:
strict (
bool) – ifTrue, report a datagram that is not completely reassembled as the tuple of its received runs; otherwise as one contiguous payload, its holes zero-filled – or, for IP while the total length is unknown, only the prefix up to the first holestore (
bool) – if store reassembled datagram in memory, i.e.,self._dtgram(if not, datagram will be discarded after callback)timeout (
float|None) – reassembly timeout in seconds, measured on the capture’s clock;Noneselects the protocol’s own__timeout__default
Note
This class is for internal use only. For customisation, please use
Reassemblyinstead.
- class pcapkit.foundation.reassembly.reassembly.ReassemblyMeta(name, bases, namespace, /, **kwargs)[source]¶
Bases:
ABCMetaMeta class to add dynamic support to
Reassembly.It provides
Reassembly.name,Reassembly.protocolandReassembly.registryas class properties, the first two read from__protocol_name__and__protocol_type__where a subclass sets them.
Type Variables¶
- pcapkit.foundation.reassembly.reassembly._PT: pcapkit.corekit.infoclass.Info¶
Packet data structure.
- pcapkit.foundation.reassembly.reassembly._DT: pcapkit.corekit.infoclass.Info¶
Datagram data structure.
- pcapkit.foundation.reassembly.reassembly._BT: pcapkit.corekit.infoclass.Info¶
Buffer data structure.