TCP protocol implementation (RFC 9293)
README.md

ocaml-tcp #

Warning. This is a work-in-progress experimental fork of utcp. Do not use it in production; use utcp instead.

When the state machine of a TCP stack reads a clock and writes to a socket, each of its tests depends on the host kernel and on timing, and testing it gets hard. ocaml-tcp implements the Transmission Control Protocol (RFC 9293) in OCaml around a core that does no I/O and is given the current time as an argument. That one state machine runs under Eio, inside a unikernel, and in in-memory tests that behave the same on every run.

There are two opam packages. nox-tcp is the core (module Tcp) and nox-tcp-eio is the Eio adapter (module Tcp_eio). The nox- prefix keeps the names clear of existing opam packages. Two sub-libraries display a running stack: nox-tcp-eio.catalog as a SQL table and nox-tcp-eio.pstree as a tree on the console.

Installation #

Install with opam:

$ opam install nox-tcp nox-tcp-eio

If opam cannot find the package, it may not yet be released in the public opam-repository. Add the overlay repository, then install it:

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install nox-tcp nox-tcp-eio

Architecture #

The core is a function. It takes an incoming segment and the current state of the connection, and returns the next state, the segments to send and the events for the application. A separate adapter reads and writes the sockets. The library is built in layers, and each layer can be used on its own:

Layer Module Role
Codec wire and Tcp.Sequence binary combinators and RFC 1982 sequence-number arithmetic
Options Tcp.Options TCP options codec (RFC 2018, RFC 7323)
Segment Tcp.Segment RFC 9293 header codec and the IP pseudo-header checksum
Connection Tcp.Connection the RFC 9293 state machine, with time as an explicit parameter
Multiplexer Tcp.Stack, Tcp.Shard the connection table, listened ports, ephemeral ports and per-core flow affinity
Eio adapter Tcp_eio (nox-tcp-eio) drives the state machine over a link and presents the stack as an Eio.Net.t

Three rows of the table deserve a closer look. TCP sequence numbers are 32 bits wide and wrap around, so a < b is defined modulo 2^32: a comes before b when (b - a) mod 2^32 is between 1 and 2^31 - 1. This is the serial-number arithmetic of RFC 1982. Tcp.Sequence compares numbers in no other way, and a connection keeps working when its sequence numbers wrap.

The TCP checksum is the 16-bit ones'-complement sum over a pseudo-header, then the TCP header and the data. For IPv4 the pseudo-header is 12 bytes: the source and destination addresses, a zero byte, the protocol number 6 and the TCP length. Because the addresses are part of the sum, a segment delivered to the wrong host fails its checksum. Segment.to_string therefore takes ~src and ~dst.

With per-core flow affinity, each domain owns a shard: a connection table of its own that no other domain touches. A symmetric RSS hash of the connection's addresses and ports, over 128 buckets by default, sends every segment of a flow to the same shard for as long as the flow lasts. Each shard takes its client ports from its own stride of the RFC 6335 dynamic range, so the reply to a connection it opened hashes back to it.

The core package nox-tcp does not depend on eio, lwt or unix. Tcp.Connection takes a decoded segment and returns the next state, the segments to send and the events to report (RFC 9293 s.3.3.2). It reads no clock and opens no socket, and it schedules no fiber. The Eio adapter, the fuzz harness and the in-memory tests all drive this same Connection; only Tcp_eio knows about sockets. Tcp.Control describes the RFC 9293 transition graph as a typed state machine. It was written from the RFC, not from the code. The tests compare it with the engine and retain named, reproducible differences until each is resolved.

Tcp_eio.Net.eio wraps a running stack as an Eio.Net.t. An Eio application that already exists, an HTTP server or an iperf3 client for instance, then runs over this TCP stack with no change, and Eio.Net.listen, connect and accept behave as usual. UDP and Unix sockets are not supported; using them raises. Tcp_eio.Net.over_flow runs the stack over a utun relay link, which a stock iperf3 -c <ip> on the host can reach. utun is the layer-3 tunnel interface of the macOS kernel; packets routed to it reach a user process as raw IP datagrams. The relay (bench/nox_relay.exe, run as root) opens a utun device and passes its datagrams over a Unix socket to the stack, which runs without privileges. The host's own TCP can then talk to this one. Tcp_eio.Net.over_netif runs it over a raw Ethernet device, with ARP and IPv4 from nox-arp-eio and nox-ip-eio.

Implemented #

Tcp.Connection covers the RFC 9293 state machine:

  • the three-way handshake, in-order data transfer and the FIN and RST teardowns;
  • out-of-order reassembly through a queue spliced back in order (RFC 9293 s.3.4);
  • selective acknowledgement, with SACK-permitted negotiation and SACK blocks on duplicate acknowledgements (RFC 2018);
  • window scaling (RFC 7323);
  • SYN and SYN-ACK retransmission, and the R2 abort after 100 seconds of unacknowledged retransmission (RFC 1122 s.4.2.3.5).

Keep-alives (RFC 9293 s.3.8.4) are off until the application calls Connection.set_keepalive (or Stack.set_keepalive) with an idle interval.

Congestion control and the retransmission timer live in lib/connection.ml:

  • Slow start and congestion avoidance. The initial window is four segments (4 x MSS, 5840 bytes for a 1460-byte MSS), and cwnd grows exponentially and then linearly (RFC 5681). RFC 5681, 3.1 allows four segments only for an MSS of at most 1095 bytes, three for an MSS up to 2190 bytes and two above, so at 1460 bytes it allows 4380; the initial window of this stack departs from the RFC above 1095 bytes.
  • Fast retransmit and NewReno fast recovery. In ESTABLISHED, the third duplicate acknowledgement triggers a retransmission and halves ssthresh; partial and full acknowledgements inflate and deflate the window until the recovery point (RFC 5681, RFC 6582).
  • Timeout collapse. A retransmission timeout drops cwnd to one segment and re-enters slow start (RFC 5681). Connection.snd_nxt remains the boundary of new sequence numbers defined by RFC 9293 section 3.3.1. Recovery traverses earlier unacknowledged bytes separately, so control ACKs keep the send sequence the peer can accept even when both directions time out. The outstanding flight remains sent and cumulatively unacknowledged.
  • Adaptive retransmission timeout. A smoothed RTT estimator with variance, Karn's algorithm (no sample from a retransmitted segment) and exponential backoff on each timeout (RFC 6298).

The Eio adapter sends its output in batches. A single call into the state machine (handle, send or timer) returns a burst of segments, as many as a congestion window allows, and the adapter writes that burst with one vectored write in place of one system call for each segment. Tcp.Gso coalesces consecutive segments into one generic segmentation offload packet for a device that accepts them, and splits an oversized segment for a guest that sends them. With generic segmentation offload, a sender gives the device one large TCP payload along with a header template and the segment size. The device (or the host kernel, for a virtual device) cuts it into segments of MSS size, and one call does the work of dozens.

The shared duplex fixture drives the production connection engine for both deterministic and generated tests. Both peers receive a flight, lose its acknowledgements, and time out before a fair link resumes. Exact streams, prefix order, half-close completion, premature EOF, ACK amplification and monotone send sequence are checked across MSS, timestamp, reordering and initial-sequence values. The simulation services due timers while packets remain ready. Each generated input includes a short stream whose FIN was already sent before timeout and a larger duplex stream. The fuzz smoke runs 100 fixed samples per property; dune build @chaos runs 5000, with no wall-clock sampling budget.

The tests take an in-memory client and server through every transition. They cover reassembly, SACK emission, the growth of cwnd, fast retransmit, the timeout driven by the RTT, and window-scale negotiation. The codecs and the state machine are fuzzed for crash safety, and regression tests cover known CVE classes: bad data offsets, the SACK panic and degenerate options. The SACK panic (CVE-2019-11477) was a Linux bug. A peer that sent crafted selective-acknowledgement blocks with a tiny MSS made the kernel split its retransmission queue into more fragments than a counter could hold, and the kernel crashed. The regression tests here check that the option parser rejects malformed SACK options and that a tiny MSS decodes safely.

Example #

To encode one segment you need only the codec layer and no connection state:

let src = Ipaddr.of_string_exn "10.0.0.1"
let dst = Ipaddr.of_string_exn "10.0.0.2"

let syn =
  {
    Tcp.Segment.src_port = 12345;
    dst_port = 80;
    seq = Tcp.Sequence.of_int 0x01020304;
    ack = Tcp.Sequence.zero;
    flags = { Tcp.Segment.no_flags with syn = true };
    window = 65535;
    urg_ptr = 0;
    options = [ Tcp.Options.Mss 1460 ];
  }

let wire = Tcp.Segment.to_string ~src ~dst ~payload:Rope.empty syn

Credits #

The design follows robur-coop/utcp (Hannes Mehnert and the Robur team), itself translated from the Cambridge Netsem HOL4 executable specification. Netsem wrote a precise model of TCP, UDP and sockets in the HOL4 theorem prover and validated it against traces of Linux, FreeBSD and Windows (Bishop et al., Engineering with Logic, JACM 2019); utcp translates that model's rules into OCaml. nox-tcp follows utcp in keeping the core free of I/O and taking time as a parameter. Sequence is a port of utcp's module of that name. The state machine in Connection is written against RFC 9293: utcp has no equivalent module, and it omits the CLOSED and LISTEN states this one carries.

Options is forked from mirage/mirage-tcpip (Anil Madhavapeddy, Mindy Preston, Balraj Singh and the MirageOS team). Its equal follows upstream clause for clause, and SACK and timestamp support come from there rather than from utcp. Segment's record follows upstream's Tcp_packet. Both upstreams are under the ISC licence.

The cstruct codec is replaced by the wire library, byte streaming by bytesrw, the IPv4 layer by nox-ip and the checksum by nox-crc. The original copyright notices are preserved in LICENSE.md.