DEV Community

Cover image for tcpip-stack: a userspace TCP/IP stack in Rust, tested over a bad cable
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

tcpip-stack: a userspace TCP/IP stack in Rust, tested over a bad cable

Every program that opens a socket relies on a stack of protocols it never sees. The kernel takes your bytes, cuts them into segments, numbers them, wraps them in IP packets and Ethernet frames, resends the ones that get lost and puts everything back in order on the other side. We learn the layer diagram once and then treat the whole thing as a pipe.

The diagram does not tell you why TCP is hard. The difficulty is not in the header format. It is in what to do when a packet is lost, arrives twice, or arrives late. To see that, I wrote tcpip-stack: a userspace TCP/IP stack in Rust with Ethernet, ARP, IPv4, ICMP echo, UDP and a minimal TCP. The link layer is a trait, so the whole stack is tested without root: two stacks talk over an in-memory wire that drops, delays, reorders and duplicates frames, and every test writes a pcap you can open in Wireshark. A TAP backend (feature tun) runs it on a real interface.

What I built

The wire formats. wire/*.rs parses and builds Ethernet II, ARP, IPv4, ICMP, UDP and TCP (with the MSS option), plus an incremental RFC 1071 checksum.

The link layer. link.rs defines the Link trait and MemWire, an in-memory wire with seeded loss, reordering, duplication and latency, and pcap capture. pcap.rs is a classic pcap writer, with a reader that the tests use.

The interface. stack.rs holds the ARP cache and the queue of packets waiting for an ARP answer, the IPv4 checks, ICMP echo and port unreachable, UDP sockets, TCP demultiplexing by 4-tuple, listeners and backlogs, and RST for closed ports.

TCP. tcp.rs is the TCB, the per-connection state. on_segment applies the RFC 9293 acceptability test, processes ACKs, reassembles data and handles FIN. poll runs the timers and sends data within the peer's window, FIN and pure ACKs.

The TCP details, as the README gives them: one retransmission timer per connection, starting at 200 ms and doubling up to 6.4 s. On expiry it goes back to snd_una and resends (go-back-N). After 12 timeouts the connection resets. Segments beyond rcv_nxt go into a reorder queue and are released when the gap fills. The advertised window is the free space in a 64 KiB receive buffer. When the peer's window is zero, the timer acts as a persist timer and sends a 1-byte probe. TIME-WAIT is 2 simulated seconds instead of the usual minutes.

The simulator. sim.rs has Pair: two stacks on one wire, stepped 1 ms at a time.

A real device. tap.rs opens a Linux TAP device through /dev/net/tun, behind the tun feature.

How to use it

Clone the repository. No privileges are needed for the tests or the demo.

git clone https://github.com/AbdeldjalilChougui/tcpip-stack
cd tcpip-stack

cargo test                                   # unit + two-stack tests, writes pcap/*.pcap
cargo run --example lossy_demo -- out.pcap 0.15 0.25 3   # loss, reorder, seed
wireshark out.pcap                           # or open samples/*.pcap
Enter fullscreen mode Exit fullscreen mode

Opening the capture in Wireshark is the best part: you see the handshake, the retransmissions and the out-of-order segments of your own stack, decoded by a tool you already trust.

From Rust, a lossy run looks like this:

use tcpip_stack::{link::WireConfig, sim::{Pair, IP_B}};

let mut p = Pair::new(WireConfig::lossy(0.10, 0.20, 7)); // 10% loss, 20% reordered
p.wire.capture("trace.pcap")?;
let l = p.b.tcp_listen(80);
let c = p.a.tcp_connect(IP_B, 80);
p.a.tcp_send(c, b"hello over a bad cable");
p.run_until(10_000, |p| p.b.tcp_accept(l).is_some());
Enter fullscreen mode Exit fullscreen mode

To run it on a real interface, you need a TAP device, and creating one needs CAP_NET_ADMIN. Do it once as root and hand the device to your user:

sudo ip tuntap add dev tap0 mode tap user $USER
sudo ip addr add 10.0.0.1/24 dev tap0 && sudo ip link set tap0 up
cargo run --features tun --example tap_echo -- tap0     # stack is 10.0.0.2
ping 10.0.0.2          # ICMP echo
nc 10.0.0.2 7          # TCP echo
nc -u 10.0.0.2 7       # UDP echo
Enter fullscreen mode Exit fullscreen mode

What it teaches

How the layers fit. A frame comes in and is handed to ARP or IPv4, then to ICMP, UDP or TCP. The way out is the reverse, with one extra step people forget: before sending an IP packet you need the MAC address of the next hop, so the packet waits in a queue while ARP asks for it.

The Internet checksum and the pseudo-header. TCP and UDP checksums cover fields from the IP header that are not part of the segment. Implementing it once makes the idea stick.

TCP is a state machine driven by bad news. The handshake and a clean transfer are the easy part. The work is sequence numbers that wrap around, ACKs, the receiver's window, out-of-order reassembly, retransmission with exponential backoff, zero-window probes, FIN and TIME-WAIT, and RST.

Sans-I/O design makes network code testable. The stack never reads a socket or a clock. You pass it frames and a millisecond counter, and it hands back frames. Because the loss on MemWire is seeded, a lossy run is deterministic: a failing seed fails every time, and you can step through it.

Lossy tests find bugs that clean tests cannot. The README describes two. A close() during the handshake used to throw away data already queued. And a RST arriving in TIME-WAIT, sent by the peer in answer to our re-ACK of a duplicated FIN, killed the connection instead of being ignored (RFC 1337). Neither shows up on a wire that never drops or duplicates anything.

Things to know

This is a learning project. The README lists what is missing on purpose:

  • IP fragmentation and reassembly (fragments are dropped), IP options, routing (single subnet, no gateway), IPv6, and ICMP errors other than port unreachable.
  • On the TCP side: congestion control, fast retransmit, SACK, window scaling, timestamps, RTT estimation (the initial RTO is fixed), delayed ACKs, Nagle and urgent data.
  • A FIN that arrives out of order is dropped and waits for retransmission.
  • The TAP path was not run against a live device. It was compiled and checked to fail cleanly with EPERM, but running it needs the root setup above.

What was tested. cargo test runs 23 unit tests: checksums, every header round-trip, sequence arithmetic, and the TCB driven directly (handshake across a sequence-number wrap, reassembly, RTO, zero-window probing, refused connect, give-up after max retries, simultaneous close, close during the handshake). Then 10 two-stack tests in tests/stack.rs:

  • ARP plus three pings sharing one ARP request; UDP both ways and ICMP port unreachable; frames with a corrupted checksum, fragments and wrong-MAC frames dropped and counted.
  • TCP connect to a closed port ending in Refused; a peer abort ending in Reset; an unreachable host ending in Timeout after SYN retries.
  • 200 KB echoed on a clean wire; 60 KB echoed over 10% loss, 20% reordering and 2% duplication for 8 seeds; 20 KB over 30% loss; four simultaneous connections over a lossy wire. Each checks byte-exact data and a clean FIN close on both sides.

The generated captures were also checked with scapy, which recomputed every IP, ICMP, UDP and TCP checksum with zero mismatches.

Why I built it

I wanted to understand TCP as running code, not as a diagram. A network stack is a good learning project in principle and an awkward one in practice, because the usual way to run one needs root, a TAP device and patience. Making the link layer a trait removes that obstacle: the stack runs in a normal test, on any machine, against a cable as bad as you ask for.

That choice shaped the whole project. With a deterministic, lossy wire and a pcap for every run, each TCP rule stops being a paragraph in an RFC and becomes a test that fails until the rule is implemented.

Get the code

The source, the tests and two sample captures are on GitHub: https://github.com/AbdeldjalilChougui/tcpip-stack. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)