Follow TCP Stream¶
Removed in version 1.7.0: pcapkit.foundation.traceflow.tcp.logger, with no alias: it is in
traceflow, and
pcapkit.foundation.traceflow.tcp exports the flow tracing class alone
(#2882).
pcapkit.foundation.traceflow.tcp.traceflow traces TCP flows from a series of
packets.
- class pcapkit.foundation.traceflow.tcp.traceflow.TCP[_DT, _BT: Info, _IT: Info, _PT: Info](*, fout='./tmp', format='pcap', byteorder=sys.byteorder, nanosecond=False, bidirectional=True, analyze=False, timeout=None)[source]¶
Bases:
TraceFlowBase[tuple[_AT,int,_AT,int],Buffer[_AT],Index,Packet[_AT]],Generic[_AT]Trace TCP flows.
- Parameters:
fout (
str) – output pathformat (
str) – output formatbyteorder (
Literal['little','big']) – output file byte ordernanosecond (
bool) – output nanosecond-resolution file flagbidirectional (
bool) – trace both halves of a conversation as one flowanalyze (
bool) – reassemble each flow’s application layer, so thatIndex.packetcan be read
Note
A TCP connection has two halves, and by default they are traced as one flow – which is what “following a TCP stream” means everywhere else, and what this module’s own title claims to do. Keying a flow on (source, destination) instead would put a client’s packets and the server’s replies in separate flows, separate labels and separate output files, leaving a caller to pair them up by inspecting the labels.
This has consequences worth knowing:
The reverse half of a conversation does not produce a flow of its own, so a capture of n connections yields n flows rather than
2n, and one output file each rather than two.A teardown does not end a flow. Seeing a connection close is not the same as knowing nothing more will arrive on its endpoints: the four-way close of RFC 9293 Section 3.6 is FIN, ACK, FIN, ACK, so the acknowledgement that completes it follows the second FIN, and duplicates of that acknowledgement can follow in turn. A flow is therefore finalised only by proof that no more of it can come – a new connection’s SYN on the same endpoints, or the end of the capture (
finish()) – or, given atimeout, once it has been idle that long (advance()). What the teardown does is get recorded, which is how that SYN is told from the peer’s SYN-ACK; see_ended().Finalising a flow is also when its callbacks run, so they run against the whole conversation rather than a truncated one.
Pass
bidirectional=Falseto trace each direction as a flow of its own, finalised on that direction’s FIN. That mode ignores RST.Note
With
analyze=Truea flow also carries its application layer:Index.packetholds the flow’s reassembled datagrams, each with its payload parsed on demand. The tracer does not reassemble the stream itself – it feedsTCP, which already implements RFC 815 and copes with the reordering and retransmission that a tracer concatenating payloads in capture order would silently corrupt.How many datagrams that is follows from the reassembler’s own notion of a datagram, which is per direction and per acknowledgement number: it buckets as
self._buffer[BUFID].ack[ACK]and emits one datagram per bucket. Since_make_segment()passes each segment’sackthrough untouched, a direction yields one datagram per distinct acknowledgement number it carried – not one datagram per direction. Three request/response round trips on one connection therefore give six datagrams, three each way, one per exchange:src=12345 ack=501 payload=b'req1' src=443 ack=105 payload=b'resp1' src=12345 ack=506 payload=b'req2' src=443 ack=109 payload=b'resp2' src=12345 ack=511 payload=b'req3' src=443 ack=113 payload=b'resp3'
That is deliberate rather than incidental: the acknowledgement number advances exactly when the peer has spoken, so bucketing on it splits a direction wherever the other end got a word in – one datagram per exchange. Merging a whole direction into one stream would instead hand the application parser every message it ever sent, concatenated, and have it read only the first.
Be precise about what that does and does not buy, though, because the boundary is the peer’s turn and not the application’s message boundary. Where an exchange is one request and one reply, the two coincide and each datagram’s payload is a single message that
Datagram.packetcan parse alone. Where a sender pipelines – several requests in flight before any reply – they all carry the same acknowledgement number, so they share a bucket and are concatenated after all, astest_pipelined_sends_share_a_datagram_because_the_ack_never_movedintests/foundation/traceflow/test_tcp.pypins. So this narrows the concatenation to within one exchange rather than eliminating it, and an application parser handed a pipelined datagram still sees only the first message.A direction that carried one acknowledgement number throughout – a single request and its reply, which is what most of the unit tests exercise – does collapse to one datagram each way, which is where “one per direction” holds.
It is off by default because buffering every traced payload is a cost tracing does not otherwise pay, and tracing’s per-packet cost is something this package deliberately keeps low. Nothing is reassembled, parsed or retained unless it is asked for.
Changed in version 1.8.0: With
analyze=True, a datagram’s payload is parsed with thelayer,protocolandcontextof a default engine extraction feeding the tracer, as TCP reassembly’s are, where it was parsed with none of them (#2946).- property name: str¶
Protocol name of current flow tracing object.
Note
The same value is also available as a class attribute, from the property of the same name on
TraceFlowMeta.
- property protocol: Type[pcapkit.protocols.protocol.ProtocolBase]¶
Protocol of current flow tracing object.
Note
The same value is also available as a class attribute, from the property of the same name on
TraceFlowMeta.
Defaults
- __protocol_type__: Type[ProtocolBase] = <class 'pcapkit.protocols.transport.tcp.protocol.TCP'>¶
Protocol of current flow tracing object.
Methods
- dump(packet)[source]¶
Dump frame to output files.
- Parameters:
packet (
Packet[_AT]) – a flow packet (trace.tcp.packet)
The flow’s output file is kept open for its next frame, as
_write()describes, unless the frame ends the flow. Such a frame is written before the flow is finalised, so its callbacks find every frame its index entry lists in the file.
- trace(packet, *, output=False)[source]¶
Trace packets.
- Overloads:
- Parameters:
packet (
Packet[_AT]) – a flow packet (trace.tcp.packet)output (
bool) – flag if has formatted dumper
- Returns:
If
outputisTrue, returns the initiatedDumperobject, which will dump data to the output file named after the flow label; otherwise, returns the flow label itself.
Notes
The flow label is formatted as following, as
_make_label()builds it from the packet that opened the flow:f'{packet.src}_{packet.srcport}-{packet.dst}_{packet.dstport}-{packet.timestamp}'
- finish()[source]¶
Finalise every flow still being traced.
The end of the capture can prove a bidirectional flow is over, as a new connection on the same endpoints can. Draining the buffer here is what lets a flow keep the acknowledgement that completes its close and still have its callback fired, rather than having to choose between the two.
Idempotent: it drains the buffer, so a second call finds nothing to do. It also closes every output file still kept open, as
TraceFlow.finishdoes, even when a callback raises: the flow it was handed is finalised, and the flows after it stay in the buffer, unfinalised, for a later call.
- submit()[source]¶
Submit traced TCP flows.
- Return type:
- Returns:
Traced TCP flow (trace.tcp.index).
Note
This reports flows still being traced without finalising them, so that reading
TraceFlow.indexpart-way through a capture cannot disturb the tracing – popping a buffer there would strand the rest of its conversation in a second flow. Such a flow is therefore reported here but has not fired its callback;finish()is what does that, at the end of the capture.With
analyze=Truethat makes an open flow’sIndex.packeta snapshot, and a mid-capture one. TheDeferredresolves when it is first read and is then fixed in place, so it holds the flow as it stood at that read – not as it stood when this method returned, and not as it will stand once the conversation ends. Read it while the flow is open and the datagrams cover only the segments seen so far; segments arriving afterwards are reassembled into the buffer but cannot reach an already-resolved snapshot, and nothing on the returnedIndexdistinguishes one from the final result thatfinish()produces.This call’s own cache is not the cause and does not soften it: both
trace()andfinish()clear__cached__['submit'], so a later call rebuilds the tuple with freshDeferredobjects. It is the previously returnedIndex, if a caller kept one, that cannot catch up. For a result that is final, read afterfinish().
Utilities
- _make_index(buffer)[source]¶
Report a flow’s buffer as its index entry.
- Parameters:
buffer (
Buffer[_AT]) – a flow buffer (trace.tcp.buffer)- Return type:
- Returns:
The flow’s index entry, its reassembler, if any, in a
Deferredunflushed: readingpacketis what asks it for its datagrams, and their ownpacketis parsed later still.
Added in version 1.10.0.
- _make_segment(packet)[source]¶
Describe a traced packet the way the reassembler expects a segment.
- Parameters:
packet (
Packet[_AT]) – a flow packet (trace.tcp.packet)- Return type:
- Returns:
A
reassembly packetfor the same segment.
The tracer does not reassemble anything itself – it hands the segment to
TCP, which already implements the RFC 815 hole-descriptor algorithm and handles the out-of-order and retransmitted segments a tracer concatenating payloads in capture order would silently corrupt. This is the whole of the translation.Note
The buffer ID is (source, destination) and so unidirectional, which is what makes each direction of the conversation reassemble separately even though the flow is keyed on the pair. The sequence number is passed through untouched: a SYN occupies one of its own, and
TCP.reassemblyis where that is accounted for.
- static _ended(buffer)[source]¶
Whether a flow’s connection has been seen to end.
- Parameters:
buffer (
Buffer[_AT]) – a flow buffer (trace.tcp.buffer)- Return type:
- Returns:
Whether a teardown was observed – a FIN from both endpoints, the polite close of RFC 9293 Section 3.6, or a RST from either, the abrupt one of RFC 9293 Section 3.5.3.
This is not the same as “nothing more will arrive on these endpoints”: the acknowledgement that completes a four-way close, and any duplicate of it, still follow. It is used to tell a new connection’s SYN from the peer’s SYN-ACK, which is a question the flag alone cannot answer.
Terminology¶
- trace.tcp.packet¶
Data structure for TCP flow tracing (
TraceFlow.dump) is as follows:trace_dict = dict( protocol=data_link, # data link type from global header index=frame.info.number, # frame number frame=frame.info, # extracted frame info syn=tcp.flags.syn, # TCP synchronise (SYN) flag fin=tcp.flags.fin, # TCP finish (FIN) flag rst=tcp.flags.rst, # TCP reset (RST) flag seq=tcp.seq, # TCP sequence number ack=tcp.ack, # TCP acknowledgement number header=tcp.packet.header, # raw bytes type header payload=bytearray( tcp.packet.payload), # raw bytearray type payload src=ip.src, # source IP dst=ip.dst, # destination IP srcport=tcp.srcport, # TCP source port dstport=tcp.dstport, # TCP destination port timestamp=float( frame.info.time_epoch), # frame timestamp )
- trace.tcp.buffer¶
Data structure for internal buffering when performing flow tracing algorithms (
TraceFlow._buffer) is as follows:(dict) buffer --> memory buffer for reassembly |--> (tuple) BUFID : (dict) | |--> ip.src | | |--> tcp.srcport | | |--> ip.dst | | |--> tcp.dstport | | |--> 'fpout' : (dictdumper.dumper.Dumper) output dumper object | |--> 'index': (list) list of frame index, both directions | | |--> (int) frame index | |--> 'label': (str) flow label generated from the packet | | that opened the flow | |--> 'origin': (tuple) (address, port) of the endpoint | | that opened the flow | |--> 'forward': (list) frame index sent by 'origin' | |--> 'reverse': (list) frame index sent to 'origin' | |--> 'fin': (set) endpoints seen to have sent a FIN | |--> 'reset': (bool) whether a RST has been seen | |--> 'reassembly': (Optional[TCP]) the flow's own | reassembler, or None when | analyze is off |--> (tuple) BUFID ...
When tracing bidirectionally, the default,
BUFIDorders the endpoints canonically, so both halves of a conversation share one key;BufferIDsays why it stays a plaintuple.A teardown – a FIN from each endpoint, or a RST from either – is recorded in
finandresetbut does not finalise the flow. The ACK that completes RFC 9293 Section 3.6’s four-way close (FIN, ACK, FIN, ACK) arrives after the second FIN, so finalising on that FIN would let the ACK open a fresh buffer under the sameBUFID, for a later connection reusing those endpoints to merge into. Only proof that nothing more can arrive finalises it – a new connection’s SYN on the same endpoints, orTCP.finishat the end of the capture – and the recorded teardown is what tells that SYN from the peer’s SYN-ACK. Given atimeout, a flow idle that long is finalised too, byTraceFlow.advance.stateDiagram-v2 direction TB state "open" as O state "torn down" as T state "finalised" as F O : each packet recorded in index, and in forward or reverse O : a FIN adds its sender to fin, a RST sets reset and finalises nothing T : not stored, derived by _ended() from fin and reset T : the closing ACK and its duplicates still recorded [*] --> O : first packet on a BUFID,<br/>buffer created, label and origin from it O --> T : bidirectional only,<br/>FIN from both endpoints, or a RST T --> F : a new connection's SYN on the same BUFID,<br/>TCP.finish() at the end of the capture,<br/>or, given a timeout, that long idle O --> F : TCP.finish() at the end of the capture, either mode,<br/>this direction's FIN, when unidirectional,<br/>or, given a timeout, that long idle F --> [*] : \_finalise pops the buffer, stores its Index,<br/>then calls each \_\_callback\_fn\_\_- trace.tcp.index¶
Data structure for TCP flow tracing (element from
TraceFlow.indextuple) is as follows:(tuple) index |--> (Info) data | |--> 'fpout' : (Optional[str]) output filename, or None when | | the format writes no file | |--> 'index': (tuple) tuple of frame index, both directions, | | in capture order | | |--> (int) frame index | |--> 'label': (str) flow label generated from the packet that | | opened the flow | |--> 'forward': (tuple) frame index in the direction that | | opened the flow | |--> 'reverse': (tuple) frame index the other way; empty when | | tracing unidirectionally | |--> 'packet': (Optional[tuple]) reassembled datagrams, one per | direction and acknowledgement number, or None | when analyze is off |--> (Info) data ...
forwardandreversepartitionindex, soframe_number in flow.forwardanswers which way a packet went without taking the label apart.packetis reassembled on its first read, and each datagram’s ownpacketparsed later still, so a caller that wanted only frame numbers pays for none of it. The tracer does not reassemble the stream itself: it feedsTCP, whose RFC 815 algorithm handles the reordering and retransmission that concatenating payloads in capture order would corrupt.
Data Structures¶
Removed in version 1.7.0: pcapkit.foundation.traceflow.data.tcp, with no alias: the module moved here
(#2882).
- class pcapkit.foundation.traceflow.tcp.data.Packet[_AT: (IPv4Address, IPv6Address)](protocol, index, frame, syn, fin, rst, src, dst, srcport, dstport, timestamp, seq, ack, header, payload)[source]¶
-
Data structure for a packet submitted to TCP flow tracing.
Changed in version 1.6.0: A third-party engine’s
frameis aFrameRecord, whichto_dict()exports as anOrderedMultiDict; soPacket.from_dict(packet.to_dict())holds the frame as anOrderedMultiInfo, not aFrameRecord(#2726).- protocol: LinkType¶
Data link type – the PCAP global header’s, or that of the PCAP-NG interface the packet was captured on.
- frame: Frame | FrameRecord | dict[str, Any]¶
Extracted frame info – the default engine’s frame, a third-party engine’s
FrameRecord, or thedictPyShark’s adapter reports, which carries no frame record.
- rst: bool¶
TCP reset (RST) flag. A connection can end abruptly as well as politely (RFC 9293 Section 3.5.3), and the tracer cannot notice that unless the flag reaches it, otherwise a reset connection looks merely idle and a later connection reusing the same endpoints merges into it.
- pcapkit.foundation.traceflow.tcp.data.BufferID¶
Buffer ID, i.e.
(address, port, address, port).A plain
tuplerather than anInfodeliberately:Infoinheritscollections.abc.Mapping, which sets__hash__ = None, so anInfocannot be adictkey at all.When tracing bidirectionally – the default – the two endpoints are ordered canonically rather than as (source, destination), so that both halves of one conversation produce the same key; see
TCP.make_bufid. The shape is unchanged either way.
- class pcapkit.foundation.traceflow.tcp.data.Buffer[_AT: (IPv4Address, IPv6Address)](fpout, index, label, origin, forward, reverse, fin, reset, reassembly)[source]¶
-
Data structure for a TCP flow tracing buffer.
- fpout: dictdumper.dumper.Dumper¶
Output dumper object.
- index: list[int]¶
List of frame index, both directions, in capture order. This is the authoritative ordering;
forwardandreverseare subsequences of it.
- origin: tuple[_AT, int]¶
(address, port)of the endpoint whose packet opened this flow. It defines what “forward” means for the flow, and it is the endpoint thelabelnames first.
- reverse: list[int]¶
List of frame index sent to
origin, in capture order. Always empty when tracing unidirectionally, since the reverse half of the conversation is then a flow of its own.
- fin: set[tuple[_AT, int]]¶
Endpoints observed to have sent a TCP FIN. A bidirectional flow is a whole connection, and a connection closes only once both halves have finished (RFC 9293 Section 3.6), so the set has to be tracked rather than a single flag: submitting on the first FIN would cut the peer’s FIN and the final acknowledgement out of the flow.
- reset: bool¶
Whether a TCP RST has been seen on this flow. A reset ends the connection at once (RFC 9293 Section 3.5.3), where a polite close needs a FIN from each side, so it is tracked as a flag rather than per endpoint.
- class pcapkit.foundation.traceflow.tcp.data.Index(fpout, index, label, forward, reverse, packet)[source]¶
Bases:
DeferredPacket,InfoData structure for a traced TCP flow, as an index entry.
See also
element from
pcapkit.foundation.traceflow.traceflow.TraceFlow.indextuple
- fpout: str | None¶
Path of the flow’s output file, or
Nonewhen the output format writes no file. Open and finalised flows report the same path.
- forward: tuple[int, ...]¶
Frame index of the packets travelling in the direction that opened the flow, in capture order. That endpoint is the one the
labelnames first, soframe_number in index.forwardanswers “which way did this packet go” without having to take the label apart.
- reverse: tuple[int, ...]¶
Frame index of the packets travelling the other way, in capture order. Empty when tracing unidirectionally, in which case
forward==index.
- packet: tuple[Datagram, ...] | None¶
Reassembled datagrams of the conversation’s application layer, one per direction and acknowledgement number, or
Nonewhen the tracer was not asked for it (analyze=False, the default).Reassembled on the first read, not when the flow is finalised, and each datagram’s own
packetis parsed later still – the same postponement at each layer, so a caller that only wanted frame numbers pays for none of it.
Type Variables¶
- pcapkit.foundation.traceflow.tcp.data._AT: ipaddress.IPv4Address | ipaddress.IPv6Address¶
IP address type.