WireGuard
Source files: 30 · checked against Etemenanki 46c12e4 · katana v6.0.0
Etemenanki/protocols/src/wireguard/mod.rsEtemenanki/protocols/src/wireguard/config.rsEtemenanki/protocols/src/wireguard/device.rsEtemenanki/protocols/src/wireguard/slot.rsEtemenanki/protocols/src/wireguard/connector.rsEtemenanki/protocols/src/helpers/address_family.rsEtemenanki/concepts/src/link.rsEtemenanki/environment/src/dial/udp.rsEtemenanki/environment/src/dial/socket.rsEtemenanki/app/src/config.rsEtemenanki/app/src/lower.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/build/dns.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/topology/outbound/mod.rsEtemenanki/protocols/Cargo.tomlEtemenanki/protocols/tests/pipeline/wireguard.rsEtemenanki/protocols/tests/support/wireguard.rsEtemenanki/protocols/tests/unit/wireguard/device.rsEtemenanki/protocols/tests/unit/wireguard/slot.rsEtemenanki/protocols/tests/unit/wireguard/connector.rsEtemenanki/protocols/tests/unit/helpers/address_family.rsEtemenanki/app/tests/integration/e2e_wg.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/supervisor/tests/unit/plan.rskatana/src/lower/outbound.rskatana/src/runtime.rs
Unlike the proxy protocols in etemenanki-protocols, WireGuard is not built from a server core and a client codec. It is a Layer 3 VPN: the tunnel carries raw IP packets, not “a connection to target X”. The module therefore provides only the outbound direction. WgConnector implements the ordinary Connector trait, and behind it a single driver task runs a WireGuard state machine (boringtun) and a userspace TCP/IP stack (smoltcp), so every routed flow becomes a TCP connection or UDP association inside that stack.
This page is for contributors who change protocols/src/wireguard/. It follows one flow from the connector down to the UDP socket and back, names every channel, buffer and constant on the way, and lists the tests that pin the behaviour. The operator’s view of the same outbound is in the WireGuard user guide.
Responsibilities
Section titled “Responsibilities”The module does four things:
- Parse configuration.
WgConfigholds the key material, the peer endpoint, the tunnel-local addresses and the transport knobs;parse_keydecodes keys from base64 or hex. - Run the tunnel.
WgDeviceowns one driver task that connects smoltcp to boringtun and boringtun to a connected UDP socket. - Keep one tunnel alive per outbound.
DeviceSlotbuilds the device lazily on the first flow, shares it with every later flow, and rebuilds it with backoff when its driver has stopped. One tunnel per outbound means one per supervisor: katana runs a supervisor per node, so every node that routes to the same WireGuard outbound brings up its own tunnel with the same key, and the peer keeps only one of those sessions at a time. katana warns about that at start (src/runtime.rs→warn_shared_wireguard):wireguard outbound <tag> is routed to by <n> nodes (<nodes>): each brings up its own tunnel with the same key, and the peer keeps only one of them at a time. - Present the tunnel as a connector.
WgConnectorturns a TCP flow into aWgStreamand a UDP flow into aWgDatagramLink.
It deliberately leaves these to others:
| Concern | Where it lives |
|---|---|
| Reading the configuration | etemenanki-app app/src/lower.rs → lower_wireguard; katana src/lower/outbound.rs → lower_wireguard. Both produce a WireguardSpec, and supervisor/src/build/outbound.rs → build_outbound turns it into a WgConfig and a WgConnector. Both take an IPv6 endpoint bracketed, as wg-quick writes it, or bare (see etemenanki-app: from TOML to a spec) |
| Resolving the endpoint’s name | WgConfig::endpoint_resolution; the supervisor passes its proxy-server resolver (Dns::servers) and the spec’s endpoint_address_family |
| Resolving destination names | the Resolver passed with WgConnector::with_resolver; the supervisor passes the resolver for destinations this process reaches itself (Dns::destinations, see DNS) |
| Routing, sniffing, relaying | the per-connection runtime that calls the connector (see Client runtime) |
| The WireGuard and Noise protocol | the boringtun crate (Tunn) |
| TCP and UDP inside the tunnel | the smoltcp crate (Interface, tcp::Socket, udp::Socket) |
The driver binds the tunnel’s outer UDP socket through etemenanki-environment’s UdpDialer, so the socket policy described in Dialers applies to it: bind address, interface, packet mark and hook. The supervisor passes its own policy (supervisor/src/supervisor.rs → SupervisorBuilder::socket_options).
Why there is no inbound
Section titled “Why there is no inbound”A WireGuard inbound would terminate a peer at Layer 3 and then see a stream of raw IP packets. The other inbounds hand the runtime flows that each carry a decoded Destination; to produce those from IP packets, a netstack would have to intercept every new TCP or UDP flow and synthesise one flow per connection. That is a transparent-proxy netstack, which sits above a protocol rather than inside it, and building it here would mean bending the concepts contracts. The module docs in protocols/src/wireguard/mod.rs record the omission as intentional and point out that the driver in device.rs is the reusable building block.
etemenanki-app enforces the omission when it lowers the config: app/src/lower.rs → lower_inbound refuses protocol = "wireguard" on an inbound with inbound <tag>: wireguard cannot be used as an inbound (no server implementation). Accepting traffic at the IP layer is the job of the TUN inbound.
Layout
Section titled “Layout”Directoryprotocols/src/wireguard/
- mod.rs module docs and re-exports
- config.rs
WgConfig,parse_key,KeyError,DEFAULT_MTU - device.rs
WgDevice, the driver task,Uplink,InMemoryDevice - slot.rs
DeviceSlot,acquire_device,connect_tcp_any - connector.rs
WgConnector,WgStream,WgDatagramLink
Directoryprotocols/src/helpers/
- address_family.rs
AddressFamilyStrategy,FamilySupport,resolve_candidates
- address_family.rs
mod.rs re-exports AddressFamilyStrategy, DEFAULT_MTU, KeyError, WgConfig, parse_key, WgConnector, WgDatagramLink, WgStream, TunnelTcp, TunnelUdp and WgDevice. The WireGuard module is not behind a feature flag: boringtun and smoltcp are ordinary dependencies of the crate. protocols/Cargo.toml turns on three smoltcp features for the tunnel’s TCP and IP handling; its comment gives what each replaces:
| smoltcp feature | Effect | Without it |
|---|---|---|
socket-tcp-cubic |
Cubic congestion control on every tunnel TCP socket | no congestion control: every retransmission timeout resent the whole window at once |
assembler-max-segment-count-16 |
room for 16 out-of-order segments per socket | 4 |
reassembly-buffer-count-4 |
4 IPv4 datagrams in reassembly at once | 1, which one lost fragment held for 60 s |
Key types
Section titled “Key types”WgConfig and parse_key
Section titled “WgConfig and parse_key”protocols/src/wireguard/config.rs describes one point-to-point association: one peer, one endpoint.
pub const DEFAULT_MTU: usize = 1420;
pub struct WgConfig { pub private_key: [u8; 32], pub peer_public_key: [u8; 32], pub preshared_key: Option<[u8; 32]>, pub endpoint: Destination, pub endpoint_resolution: Option<(Resolver, AddressFamilyStrategy)>, pub local_addrs: Vec<IpAddr>, pub mtu: usize, pub persistent_keepalive: Option<u16>, pub reserved: Option<[u8; 3]>, pub socket: SocketOptions,}
impl WgConfig { pub fn new( private_key: [u8; 32], peer_public_key: [u8; 32], endpoint: Destination, local_addrs: Vec<IpAddr>, ) -> Self;}| Field | Meaning | Set by WgConfig::new |
|---|---|---|
private_key |
Our Curve25519 static secret, passed to x25519::StaticSecret::from. |
argument |
peer_public_key |
The peer’s Curve25519 public key. | argument |
preshared_key |
Optional key mixed into the Noise handshake. | None |
endpoint |
The peer’s UDP endpoint. The driver dials it directly. | argument |
endpoint_resolution |
How a named endpoint is looked up, and which family of its addresses is dialed. None asks the host resolver and takes its first answer. |
None |
local_addrs |
Tunnel-local addresses of the virtual interface. They also decide which address families the outbound can reach. | argument |
mtu |
IP-layer MTU of the virtual interface. | DEFAULT_MTU (1420, the Xray-core default) |
persistent_keepalive |
Keepalive interval in seconds, handed to Tunn::new. |
None |
reserved |
The Xray-style 3-byte header field (see The reserved bytes). | None |
socket |
The socket policy for the tunnel’s UDP socket. | SocketOptions::default() |
WgConfig derives Clone; the connector wraps it in an Arc so every rebuild starts from the same value.
pub enum KeyError { Invalid,}
pub fn parse_key(text: &str) -> Result<[u8; 32], KeyError>;parse_key trims surrounding whitespace, then tries two encodings in order:
- standard padded base64 (
base64::engine::general_purpose::STANDARD), which is whatwg genkeyandwg pubkeyprint; - hex, which Xray-core also accepts.
Each attempt succeeds only if it decodes to exactly 32 bytes. The two cannot collide: 32 bytes are 44 base64 characters including = padding, or 64 hex digits. Anything else returns KeyError::Invalid, whose message is invalid WireGuard key: expected base64 or hex encoding of 32 bytes. The callers wrap it: etemenanki-app reports outbound <tag>: invalid wireguard private_key (or peer_public_key, preshared_key), and katana reports wireguard outbound <tag> <field>: <KeyError>, with the field private_key, public_key or pre_shared_key, or wireguard outbound <tag> needs a <field> when a required key is missing.
WgDevice and its handles
Section titled “WgDevice and its handles”protocols/src/wireguard/device.rs exposes a handle to the running driver and two pairs of channels.
pub struct TunnelTcp { pub tx: mpsc::Sender<Bytes>, pub rx: mpsc::Receiver<Bytes>,}
pub struct TunnelUdp { pub tx: mpsc::Sender<(SocketAddr, Bytes)>, pub rx: mpsc::Receiver<(SocketAddr, Bytes)>,}
pub struct WgDevice { cmd_tx: mpsc::Sender<Command>, local_addrs: Vec<IpAddr>,}
impl WgDevice { pub async fn start(config: Arc<WgConfig>) -> io::Result<WgDevice>; pub(crate) async fn start_with(config: Arc<WgConfig>, lifetimes: Lifetimes) -> io::Result<WgDevice>; pub fn is_alive(&self) -> bool; pub async fn connect_tcp(&self, ip: IpAddr, port: u16) -> io::Result<TunnelTcp>; pub async fn connect_udp(&self) -> io::Result<TunnelUdp>;}start is start_with(config, Lifetimes::default()); the crate’s own tests call start_with with shorter lifetimes (see Connection lifetimes). WgDevice is deliberately not Clone; it is shared as Arc<WgDevice>. Its only link to the driver is cmd_tx, the sending half of the command channel. is_alive returns !self.cmd_tx.is_closed(): the driver owns the receiving half, so a closed channel means exactly that the driver task has returned.
The command channel carries two requests, and under #[cfg(test)] three queries the unit tests ask through WgDevice::live_tcp, passes and has_session (LiveTcp, Passes, HasSession). Command is private to device.rs:
enum Command { ConnectTcp { dst: SocketAddr, src: IpAddr, out_rx: mpsc::Receiver<Bytes>, in_tx: mpsc::Sender<Bytes>, reply: oneshot::Sender<io::Result<()>>, }, ConnectUdp { out_rx: mpsc::Receiver<(SocketAddr, Bytes)>, in_tx: mpsc::Sender<(SocketAddr, Bytes)>, reply: oneshot::Sender<io::Result<()>>, },}connect_tcp and connect_udp create two mpsc::channel(CHANNEL_CAP) pairs per connection: out for the uplink (application to tunnel) and in for the downlink. They move the driver’s ends (out_rx, in_tx) into the command, send it, and await the oneshot reply. The caller keeps the other ends, returned as TunnelTcp or TunnelUdp. Because the reply is awaited, a TCP connect failure surfaces as an error from connect_tcp rather than as an early EOF on a stream.
connect_tcp also picks the source address: local_addr_for returns the first entry of local_addrs with the same family as the destination, or AddrNotAvailable with wireguard: no tunnel-local address matching destination family. connect_udp takes no destination, because each datagram carries its own.
The driver task
Section titled “The driver task”WgDevice::start spawns one task that owns everything below. The struct is private:
struct Driver { tunn: Tunn, device: InMemoryDevice, iface: Interface, sockets: SocketSet<'static>, udp: UdpSocket, cmd_rx: mpsc::Receiver<Command>, reserved: Option<[u8; 3]>, scratch: Vec<u8>, recv_buf: Vec<u8>, tcp_conns: HashMap<SocketHandle, TcpConn>, udp_conns: HashMap<SocketHandle, UdpConn>, tcp_ports: PortCursor, udp_ports: PortCursor, tcp_in_use: HashSet<(u16, SocketAddr)>, udp_in_use: HashSet<u16>, lifetimes: Lifetimes, revival: Revival, room: RoomWaits, #[cfg(test)] passes: u64,}
struct TcpConn { in_tx: Option<mpsc::Sender<Bytes>>, uplink: Uplink<Bytes>, connect_reply: Option<oneshot::Sender<io::Result<()>>>, uplink_closed: bool, remote_fin: bool, local: (u16, SocketAddr), orphan_deadline: Option<Instant>,}
struct UdpConn { in_tx: mpsc::Sender<(SocketAddr, Bytes)>, uplink: Uplink<(SocketAddr, Bytes)>, local_port: u16,}
struct PortCursor { next: u16,}
impl PortCursor { fn new() -> Self; fn next_free(&mut self, taken: impl Fn(u16) -> bool) -> Option<u16>;}| Field | Role |
|---|---|
tunn |
The boringtun Tunn: Noise handshake, session keys, timers, encryption. A pure state machine with no I/O of its own. |
device |
InMemoryDevice, the smoltcp phy::Device. Its rx queue holds decrypted IP packets for smoltcp to read; its tx queue collects IP packets smoltcp emits. |
iface, sockets |
The smoltcp Interface and the SocketSet holding one smoltcp socket per tunnelled connection. |
udp |
The UDP socket, connected to the peer endpoint. |
cmd_rx |
Receiving half of the command channel. |
scratch, recv_buf |
SCRATCH-sized buffers for boringtun output and for UDP receive. |
tcp_conns, udp_conns |
Per-connection state, keyed by smoltcp SocketHandle. Each connection owns its uplink receiver inside its Uplink. |
tcp_ports, udp_ports |
One PortCursor each for tunnel-side source ports (see Tunnel-side ports). |
tcp_in_use |
Each live TCP socket’s local port and remote. smoltcp tells TCP connections apart by both, so one port may serve several remotes. |
udp_in_use |
Each live UDP association’s local port. An association takes its port for every remote, and smoltcp hands a datagram to the first socket bound to its port, so two associations sharing one would get each other’s replies. |
lifetimes |
The keep-alive, timeout and orphan linger of every tunnel TCP connection (see Connection lifetimes). |
revival |
The state of an outage after the WireGuard session expired (see Reviving an expired session). |
room |
RoomWaits: one wait per downlink channel found full, which wakes the driver once the channel has room. |
passes |
Test-only: how many passes the driver has run. |
Each connection’s uplink holds at most one item: one the driver has taken from the uplink channel but smoltcp has not yet accepted. connect_reply holds the oneshot sender until the TCP handshake settles. A TcpConn’s in_tx becomes None once its downlink has ended (see Closing); remote_fin is set, and stays set, once the socket has been seen past the remote’s FIN; local is the entry it holds in tcp_in_use; orphan_deadline is set once the downlink has ended and every uplink sender is gone, and the connection is aborted if it has not closed by then. A UdpConn’s local_port is its entry in udp_in_use.
Uplink is private to device.rs, together with the free function that waits on every connection’s uplink at once:
struct Uplink<T> { rx: Option<mpsc::Receiver<T>>, held: Option<T>,}
impl<T> Uplink<T> { fn new(rx: mpsc::Receiver<T>) -> Self; fn take(&mut self) -> Option<T>; fn hold(&mut self, item: T); fn is_finished(&self) -> bool; fn sender_gone(&self) -> bool; fn poll_refill(&mut self, cx: &mut Context<'_>) -> Poll<()>;}
fn poll_uplinks( tcp: &mut HashMap<SocketHandle, TcpConn>, udp: &mut HashMap<SocketHandle, UdpConn>, cx: &mut Context<'_>,) -> Poll<()>;| Item | Behaviour |
|---|---|
rx |
The receiving half of the connection’s uplink channel. It becomes None once every sender is gone and the channel is drained. |
held |
The one item the socket has not accepted yet. |
new |
Wraps the uplink receiver, with nothing held. |
take |
Returns the held item, else the next item already in the channel (try_recv). It never waits for an item. When the channel reports Disconnected, it records the end by setting rx to None. |
hold |
Keeps an item the socket did not accept; take offers it first next time. |
is_finished |
true when rx is gone and nothing is held: the application is done and everything it sent was handed to the socket. |
sender_gone |
true once the application has dropped every sender (rx is gone or closed), whatever is still held or queued. The orphan check uses it. |
poll_refill |
With nothing held, waits on the channel: its next item becomes the held one, or its end is recorded, and the call returns Ready. With an item held, it returns Pending (see Backpressure). |
poll_uplinks |
Calls poll_refill on every TCP connection and every UDP association and returns Ready if any of them did. |
Nothing outside the task touches this state, so the driver needs no locks. smoltcp and boringtun are both synchronous and poll-driven; the task is what drives them.
DeviceSlot
Section titled “DeviceSlot”protocols/src/wireguard/slot.rs holds the tunnel that every flow of one outbound shares.
#[derive(Default)]pub struct DeviceSlot { pub device: Option<Arc<WgDevice>>, pub failures: u32, pub retry_at: Option<StdInstant>, pub started_at: Option<StdInstant>,}
impl DeviceSlot { pub fn died_young(&self) -> bool; pub fn note_failure(&mut self);}
pub async fn acquire_device( slot: &Mutex<DeviceSlot>, config: &Arc<WgConfig>,) -> io::Result<Arc<WgDevice>>;
pub fn tunnel_down() -> io::Error;
pub async fn connect_tcp_any( device: &WgDevice, candidates: Vec<IpAddr>, port: u16,) -> io::Result<TunnelTcp>;The slot is an Option rather than a OnceCell so that a dead device can be dropped and replaced. Mutex here is tokio::sync::Mutex. The fields are public so the unit tests can inspect them; WgConnector::slot exposes the slot for the same reason.
WgConnector, WgStream and WgDatagramLink
Section titled “WgConnector, WgStream and WgDatagramLink”protocols/src/wireguard/connector.rs adapts the tunnel to the Connector trait from concepts/src/link.rs (see Links and types).
pub struct WgConnector { config: Arc<WgConfig>, address_family: AddressFamilyStrategy, resolver: Resolver, device: Arc<Mutex<DeviceSlot>>,}
impl WgConnector { pub fn new(config: WgConfig) -> Self; pub fn with_address_family(config: WgConfig, address_family: AddressFamilyStrategy) -> Self; pub fn with_resolver(mut self, resolver: Resolver) -> Self; pub fn slot(&self) -> &Arc<Mutex<DeviceSlot>>; pub fn reaches(&self, ip: IpAddr) -> bool;}
impl<T: Send + Sync + 'static> Connector<Flow<T>> for WgConnector { type Stream = WgStream; type Datagram = WgDatagramLink; type Future = DialFuture;
fn connect(&mut self, flow: Flow<T>) -> DialFuture;}
type DialFuture = Pin<Box<dyn Future<Output = io::Result<Outbound<WgStream, WgDatagramLink>>> + Send>>;WgConnector::new uses AddressFamilyStrategy::Auto and Resolver::default(), which is the system resolver. Both etemenanki-app and katana call with_address_family(...).with_resolver(resolver.clone()), so tunnelled names go through the configured resolver. The lookup itself runs on the host; only the connection to the resolved address travels through the tunnel.
Clone is implemented by hand and clones the Arcs, so every clone shares one DeviceSlot and therefore one tunnel. connect clones self into a boxed future that calls the private dial.
reaches(ip) says whether a destination at ip can be dialed through the tunnel: the outbound’s AddressFamilyStrategy allows its family, and the tunnel has a local address of that family to send from. The supervisor’s Outbound::lacks_ipv6 (supervisor/src/topology/outbound/mod.rs) asks it for a WireGuard outbound when the TUN inbound screens IPv6 connections (see TUN).
pub struct WgStream { tx: PollSender<Bytes>, rx: mpsc::Receiver<Bytes>, pending: Bytes, eof: bool,}
pub struct WgDatagramLink { tx: PollSender<(SocketAddr, Bytes)>, rx: mpsc::Receiver<(SocketAddr, Bytes)>, resolver: Resolver, strategy: AddressFamilyStrategy, support: FamilySupport, resolved: Lookups, resolving: Option<(CompactString, ResolveFuture)>,}
const FAILED_LOOKUP_TTL: Duration = Duration::from_secs(10);
struct Lookups { names: HashMap<CompactString, Lookup>,}
enum Lookup { Found(IpAddr), Failed(Instant),}WgStream implements AsyncRead and AsyncWrite over the TunnelTcp channels; pending is the unread tail of the last chunk it received, and eof is set once the remote’s FIN has been read. WgDatagramLink implements DatagramLink<Addr = Destination> over the TunnelUdp channels and resolves domain destinations packet by packet. resolved is what the association has learned of the names it sends to, and resolving is the lookup in flight with its name.
FamilySupport
Section titled “FamilySupport”An ordinary dialer lets the kernel pick a source address and fail fast when a family is unusable. The smoltcp netstack has no host routing table, so WireGuard answers the capability question itself, from its tunnel-local addresses (protocols/src/helpers/address_family.rs):
pub struct FamilySupport { ipv4: bool, ipv6: bool,}
impl FamilySupport { pub fn both() -> Self; pub fn from_addrs(addrs: &[IpAddr]) -> Self; pub fn supports(self, ip: IpAddr) -> bool; pub fn describe(self) -> &'static str;}
pub async fn resolve_candidates( context: &str, dest: &Destination, strategy: AddressFamilyStrategy, support: FamilySupport, resolver: &Resolver,) -> io::Result<Vec<IpAddr>>;dial computes FamilySupport::from_addrs(&self.config.local_addrs) and passes it with the operator’s AddressFamilyStrategy to resolve_candidates. That keeps every resolved address, removes those the strategy forbids or the tunnel cannot source, and sorts stably for prefer_ipv4 and prefer_ipv6, so the other family stays available as a fallback. When nothing is left, the error names the capability: wireguard: no usable auto destination address for example.com:443 (local address supports IPv4 only).
The supervisor also checks the combination when it validates the spec (supervisor/src/build/validate.rs), so the check covers every front end: ipv4_only without an IPv4 address and ipv6_only without an IPv6 one are refused, for example with outbound <tag>@v0: wireguard address_family ipv6_only needs an IPv6 address.
The reserved bytes
Section titled “The reserved bytes”Every WireGuard message starts with a 4-byte header. The WireGuard specification fixes bytes 1 to 3 at zero; Xray-core lets an operator put a 3-byte value there, which some peers use to identify a client. The driver supports it through WgConfig::reserved.
| Offset | Size | Field | On send | On receive |
|---|---|---|---|---|
| 0 | 1 | message type (1 initiation, 2 response, 3 cookie reply, 4 transport data) | written by boringtun | read by boringtun |
| 1 | 3 | reserved | apply_reserved overwrites with WgConfig::reserved when it is Some |
decapsulate_all zeroes it before parsing, when the datagram is longer than 3 bytes |
| 4 | rest | message body | written by boringtun | read by boringtun |
The zeroing on receive is required, not cosmetic: boringtun reads the first four bytes as one little-endian message type, so non-zero reserved bytes would make every datagram unparseable. apply_reserved runs on all three outgoing paths: encapsulated data (flush_tx), handshake and cookie replies produced while decapsulating (send_all), and timer packets.
Data flow
Section titled “Data flow”The module docs in device.rs draw the whole path as a loop through one task. Redrawn:
flowchart LR app["WgStream / WgDatagramLink"] -->|"uplink channel"| held["Uplink held slot, one item"] held -->|"send_slice while the socket has room"| sock["smoltcp socket"] sock -->|"Interface::poll"| devtx["InMemoryDevice tx"] devtx -->|"Tunn::encapsulate, apply_reserved"| udp["connected UdpSocket"] udp -->|"UDP"| peer["WireGuard peer"] peer -->|"UDP"| udp udp -->|"zero reserved, Tunn::decapsulate"| devrx["InMemoryDevice rx"] devrx -->|"Interface::poll"| sock sock -->|"try_reserve on downlink channel"| app
Bringing the tunnel up
Section titled “Bringing the tunnel up”WgDevice::start(config) performs these steps and returns as soon as the task is spawned:
- Reject an empty
local_addrswithInvalidInput:wireguard: no tunnel-local addresses configured. - Resolve the endpoint (
resolve_endpoint). Withendpoint_resolutionset toSome((resolver, strategy)), the endpoint goes throughhelpers::address_family::destination_to_socketaddrswith that resolver and strategy, and the first address is taken; the supervisor always sets it. WithNone, an IP literal is used as is and a domain goes throughtokio::net::lookup_host, taking the first result. No result givesNotFound:wireguard: endpoint domain did not resolve. The address is fixed for the life of the device; a rebuilt device resolves the name again. - Bind the UDP socket with
UdpDialer::new(config.socket.clone()).bind(AddressFamily::of(&endpoint)): an unconnected socket of the endpoint’s family on an ephemeral port, v6-only for IPv6, with the socket policy applied before the bind. Thenconnectit to the endpoint. A connected socket receives only the peer’s datagrams, and reports the errors its earlier datagrams drew, ICMP answers among them, on a later send or receive. - Build the
Tunnwith the static secret, the peer’s public key, the pre-shared key, the keepalive, a randomu32session index andNonefor the rate limiter, so boringtun creates its own handshake rate limiter for this tunnel. - Build the smoltcp
Interface(build_interface):HardwareAddress::IponMedium::Ip, a random seed, each local address as a host route (/32for IPv4,/128for IPv6), and, for each family that has a local address, a default route via the first such address. OnMedium::Ipthe gateway is never used for next-hop resolution; the default route only makes off-link destinations routable. The device reportsconfig.mtuasmax_transmission_unit. - Create the command channel (
CHANNEL_CAP) and spawn the driver.
start performs no handshake. boringtun starts one when the first IP packet is encapsulated, which happens when the first flow sends its SYN or first datagram, or, when persistent_keepalive is set, when the first keepalive falls due in update_timers. So start succeeds even against a peer that is unreachable; that is why DeviceSlot judges a tunnel by how long it lived (MIN_HEALTHY_LIFETIME), not by whether start returned Ok.
The supervisor builds the connector when an apply prepares the outbound, but nothing calls start then: the device is built by the first flow that needs it (see Rebuilding the tunnel).
One turn of the driver loop
Section titled “One turn of the driver loop”Driver::run repeats the same three phases, then waits on six event sources.
flowchart TB
poll["Interface::poll: rx packets into sockets, sockets emit into tx"] --> svc["service_sockets: connect replies, uplinks into sockets, sockets into downlink channels, aborts, closes"]
svc --> flush["flush_tx: encapsulate every tx packet, send over UDP"]
flush --> wait{"select!"}
wait -->|"udp.recv"| dec["take_batch: up to RECV_BATCH datagrams, decapsulate, send replies"]
wait -->|"cmd_rx.recv"| cmd["handle_command, then the commands already queued"]
wait -->|"poll_fn(poll_uplinks)"| push["fill the held slot of each ready connection"]
wait -->|"poll_fn(poll_room)"| room["a full downlink channel has room"]
wait -->|"timer.tick"| tim["Tunn::update_timers, revive an expired session"]
wait -->|"sleep"| idle["smoltcp timers"]
dec --> poll
cmd --> poll
push --> poll
room --> poll
tim --> poll
idle --> poll
The phases:
- Poll.
self.iface.poll(now, &mut self.device, &mut self.sockets)feeds every packet inInMemoryDevice::rxto smoltcp and lets smoltcp emit segments, ACKs and datagrams intoInMemoryDevice::tx. - Service sockets.
service_socketswalks every connection. It resolves pending TCP connects, hands uplink items to the smoltcp socket while it has room, at mostCHANNEL_CAPitems per connection per pass so that no producer can keep the driver to itself, moves received data into the downlink channel while the channel has room, aborts the connections Connection lifetimes describes, and collects sockets to remove. A downlink channel found full is handed toRoomWaits::wait;service_socketsreturns nothing. - Flush.
flush_txpops each IP packet fromInMemoryDevice::tx, encapsulates it intoscratch, copies the result out, applies the reserved bytes and sends it withsend_datagram. Without a session, boringtun queues the packet and returns a handshake initiation asWriteToNetwork, orTunnResult::Donewhen a handshake is already in flight; the queued packets go out later from thedecapsulateloop.DoneandTunnResult::Errare skipped. - Wait.
compute_sleepturnsInterface::poll_delayinto atokio::time::Sleep: the smoltcp delay when there is one, and 3600 s otherwise. Theselect!then waits for the first of:
| Branch | Action |
|---|---|
self.udp.recv(&mut self.recv_buf) |
take_batch handles that datagram and then whatever else has arrived, taken with try_recv, up to RECV_BATCH (64) datagrams in one pass. The doc comment gives the reason: every pass sweeps every socket, so one pass per datagram would cost the whole set per packet. For each datagram, decapsulate_all zeroes the reserved bytes and calls Tunn::decapsulate. A WriteToNetwork result (handshake response, cookie reply, or packets boringtun had queued) is collected, and decapsulate is called again with an empty datagram until it stops producing them, as boringtun’s contract requires. A WriteToTunnelV4 or WriteToTunnelV6 result is pushed onto InMemoryDevice::rx. send_all then sends the collected packets. WouldBlock from try_recv ends the batch; any other error but a fatal one is logged at debug (wireguard: receive error: <error>) and ends the batch. A fatal error, from try_recv or from a send, ends the driver with wireguard: tunnel driver stopping: <error> at warn. |
self.cmd_rx.recv() |
Some(cmd) goes to handle_command, and so do the commands already queued behind it, taken with try_recv, up to CHANNEL_CAP in the pass. None means every WgDevice handle is gone, and the driver returns. |
std::future::poll_fn(poll_uplinks) |
Resolves once any connection that holds nothing has an item in its uplink channel or has seen the channel end. poll_uplinks polls every such connection, not only the first, so the next pass serves them all. The branch only fills the held slot; service_sockets hands the item to the socket on the next pass. |
std::future::poll_fn(RoomWaits::poll_room) |
Resolves once a downlink channel found full has room again, or has closed. RoomWaits keeps one ReusableBoxFuture per waiting socket, which awaits reserve_owned on a clone of the sender and lets the permit go at once, so the slot is there for the next pass’s try_reserve. A socket that is removed has its wait dropped (RoomWaits::forget), since the wait holds a sender and the reader must see its channel close. |
timer.tick() |
Every TIMER_TICK (250 ms, MissedTickBehavior::Delay), call Tunn::update_timers. A WriteToNetwork result (handshake retry, keepalive) gets the reserved bytes and goes out through send_datagram, like every other datagram, so an error that is not fatal drops it; a fatal one logs wireguard: tunnel driver stopping, send failed: <error> at warn and ends the driver. A TunnResult::Err(WireGuardError::ConnectionExpired) while any connection uses the tunnel starts a handshake (see Reviving an expired session). Other results are ignored. |
sleep |
Wake to re-poll smoltcp for its own timers (retransmission, delayed ACK, keep-alive, timeout). |
Opening a TCP connection
Section titled “Opening a TCP connection”sequenceDiagram participant R as Runtime participant C as WgConnector participant S as DeviceSlot participant D as WgDevice participant T as Driver task participant P as Peer R->>C: connect(flow) C->>S: acquire_device (lock) S-->>C: Arc of WgDevice C->>C: resolve_candidates with FamilySupport C->>D: connect_tcp_any, one candidate at a time D->>T: Command::ConnectTcp over cmd channel T->>T: open_tcp: tcp::Socket::connect, keep reply T->>P: SYN, encapsulated (handshake first if needed) P-->>T: SYN-ACK, decapsulated into smoltcp T-->>D: reply Ok once may_send() D-->>C: TunnelTcp C-->>R: Outbound::Stream(WgStream)
WgConnector::dial branches on dest.network. For TCP it resolves the destination with resolve_candidates("wireguard", ...) and calls connect_tcp_any, which tries the candidates in order. Each attempt is tokio::time::timeout(TCP_CONNECT_ATTEMPT_TIMEOUT, device.connect_tcp(ip, port)) with a 10 s limit; the first success wins. If all fail, the error is TimedOut with every attempt’s reason: wireguard: tunnel TCP connect failed for all resolved addresses (192.0.2.1: timed out; ...).
Inside the driver, open_tcp creates a tcp::Socket with a TCP_BUFFER receive and send buffer, sets its keep-alive and timeout from the driver’s Lifetimes (60 s and 180 s by default, see Connection lifetimes), takes a local port from tcp_ports that tcp_in_use does not hold for dst, and calls socket.connect from src to dst. If every port is taken, the reply is AddrInUse (wireguard: every tunnel-side port is in use). If smoltcp refuses the connect call, the reply is InvalidInput (wireguard: connect failed: <smoltcp error>) and nothing is stored. Otherwise the socket joins the SocketSet, (port, dst) joins tcp_in_use, and a TcpConn holding the reply and Uplink::new(out_rx) joins tcp_conns. On a later pass, service_sockets answers the reply:
socket.may_send()is true (the handshake reachedEstablished):Ok(()).socket.state() == tcp::State::Closed(the peer reset it, or smoltcp gave up):ConnectionRefusedwithwireguard: tunnel TCP connect failed.
Tunnel-side ports
Section titled “Tunnel-side ports”TCP and UDP each have their own PortCursor. next_free hands out ports round-robin from EPHEMERAL_BASE (49152), wrapping back to it after 65535, and skips every port its taken test claims. For TCP a port is taken when tcp_in_use already holds it for the same remote; for UDP it is taken when udp_in_use holds it at all, because smoltcp hands a datagram to the first socket bound to its port. A port is released when its socket is removed. next_free returns None after one full lap without a free port, and the connect fails with AddrInUse, wireguard: every tunnel-side port is in use. a_port_still_taken_is_skipped_after_the_wrap and a_released_port_is_handed_out_again pin the cursor.
Moving TCP bytes
Section titled “Moving TCP bytes”Uplink. WgStream::poll_write waits in PollSender::poll_reserve for a slot in the uplink channel, copies the whole buffer into one Bytes chunk and reports it as written. poll_flush does nothing. On each pass, service_sockets calls uplink.take() for the next chunk, up to CHANNEL_CAP times. take runs before the can_send() check, so an uplink that has ended is noticed in any socket state. Then:
- the socket cannot send: the chunk is held;
send_sliceaccepts the whole chunk: the loop takes the next one;send_sliceaccepts only part of it: the rest,chunk.split_off(sent), is held and the loop stops;send_slicereturns an error: the chunk is held and the loop stops.
A held chunk is offered first on the next pass. Nothing goes back into a queue, because the driver keeps at most that one chunk per connection.
Downlink. For each readable socket whose downlink has not ended, service_sockets first takes a permit with in_tx.try_reserve(), then copies the contiguous readable part of the smoltcp receive buffer into one Bytes and sends it, repeating while can_recv() holds. If the channel is full, the data stays in the smoltcp receive buffer and the driver registers RoomWaits::wait(handle, in_tx): it runs a pass once the channel has room, and there is no timed re-poll. While the data stays there, smoltcp’s advertised receive window shrinks, which slows the remote sender. WgStream::poll_read hands out a received chunk across as many reads as the caller’s buffer needs, through pending.
UDP associations and per-packet resolution
Section titled “UDP associations and per-packet resolution”A UDP flow does not resolve anything at dial time. dial calls device.connect_udp(), and the driver’s open_udp creates a smoltcp udp::Socket with 64 metadata slots and TCP_BUFFER bytes of payload storage per direction, binds it to a port from udp_ports that no live association holds, with no fixed address, records the port in udp_in_use, stores a UdpConn holding Uplink::new(out_rx), and replies Ok at once. With every port taken, the reply is AddrInUse (wireguard: every tunnel-side port is in use).
WgDatagramLink::poll_send_to(cx, buf, to) first maps the Destination to a SocketAddr in poll_target:
- An IP literal is used directly; the strategy and
FamilySupportfilters apply only to names. - A domain is looked up with
resolve_candidates, using the link’s resolver, strategy andFamilySupport, and the first candidate is the target. - What a lookup gave is kept in
resolved(Lookups): a found address for the association’s life, a failure forFAILED_LOOKUP_TTL(10 s). Within that time a datagram to the name is dropped without a lookup; after it, the next datagram looks the name up again. The doc comment gives the reason for the expiry: one lookup that timed out used to blackhole the name for as long as the association lived, while the application’s own sends kept the association from idling out.
When the name does not resolve, the packet is dropped (logged at trace) and poll_send_to still returns Ok(buf.len()): dropping is what UDP does. Otherwise the link reserves a slot in the uplink channel and sends (target, payload). On each pass, service_sockets takes up to CHANNEL_CAP datagrams with uplink.take() and sends each with udp::Socket::send_slice(payload, target):
Ok: the datagram is in the socket’s send ring; the loop takes the next one.SendError::BufferFulland the payload fits the ring (payload.len() <= socket.payload_send_capacity()): the datagram is held until the next poll empties the ring, and the loop stops.- Any other error, meaning a datagram larger than the whole send ring or
SendError::Unaddressable: the datagram is dropped with atraceline,wireguard: dropping a <n>-byte datagram to <target>: <error>, and the loop moves on. A datagram that can never be sent therefore does not hold up the ones behind it.
Received datagrams travel back as (source, payload). poll_recv_from copies as much of the payload as fits in the caller’s buffer and returns the source as Destination { network: DialNetwork::Udp, remote: Remote::IpAddr(..), port }.
Backpressure
Section titled “Backpressure”The # Backpressure section of the module docs in device.rs states the bound, and Uplink implements it. The driver reads a connection’s uplink channel only while that connection holds no item. When a socket stops accepting, because the remote stops reading or the tunnel stops draining, the connection keeps its held item and the uplink channel (CHANNEL_CAP, 256 items) fills behind it. WgStream::poll_write then waits in PollSender::poll_reserve, so the pressure reaches the producer and the driver takes nothing more for that connection. Every other connection has its own channel and held slot, and poll_uplinks keeps refilling those that hold nothing, so they keep moving. A UDP association works the same way, with WgDatagramLink::poll_send_to waiting for the channel slot.
With an item held, poll_refill returns Pending on purpose, without registering a waker. The connection is then waiting on its socket, not on its channel, and the socket’s progress (an ACK that opens the window, a poll that empties the UDP send ring) always comes through the driver loop, whose next pass offers the held item again. Leaving the channel unread is what pushes back on the application.
For one TCP connection, the uplink holds at most:
| Stage | Bound |
|---|---|
| smoltcp send ring | TCP_BUFFER, 64 KiB |
| uplink channel | CHANNEL_CAP, 256 items |
held slot in Uplink |
1 item |
The channel and the held slot count items, not bytes. A poll_write chunk is the caller’s whole buffer, so the number of bytes behind a full channel follows the size of the writer’s buffers.
The downlink is bounded the other way round: a socket is read only while its downlink channel has room (see Moving TCP bytes).
Closing
Section titled “Closing”TCP close is driven by the channels, and the downlink tells a remote close from a reset:
stateDiagram-v2 [*] --> Connecting: open_tcp stores TcpConn Connecting --> Open: may_send, reply Ok Connecting --> Closed: state Closed, reply ConnectionRefused Connecting --> Closed: uplink ended in SYN-SENT (dial abandoned) Open --> LocalClosed: uplink finished, FIN sent Open --> LocalClosed: downlink receiver dropped, seen on the next pass Open --> RemoteClosed: FIN from the remote, empty chunk after the last byte LocalClosed --> Closed: remote FIN, then 10 s TIME-WAIT LocalClosed --> Closed: data with no reader left, abort (RST) LocalClosed --> Closed: orphan linger over, abort (RST) RemoteClosed --> Closed: local close, LAST-ACK acknowledged Open --> Closed: reset, or 180 s with nothing heard, downlink sender dropped Closed --> [*]: removed once the downlink has ended and no RST is owed
- Local close.
WgStream::poll_shutdowncloses thePollSender. Onceuplink.is_finished()is true (the sender is gone, the channel is drained and the last item has been handed to the socket),service_socketscallssocket.close()(a FIN) once and setsuplink_closed. Dropping aWgStreamhas the same effect. The downlink carries on:a_half_closed_flow_still_gets_the_whole_replyshuts down its write side and still reads the whole echo. - Remote close.
remote_finis set once the socket is seen in CLOSE-WAIT, LAST-ACK, CLOSING or TIME-WAIT (past_remote_fin), and it stays set. Once every byte before the FIN has been handed on and the socket has nothing left to read, the driver sends an emptyBytesdown the channel and setsin_txtoNone. The empty chunk is the FIN:WgStream::poll_readsetseofand returns end of file, and every later read does too, while the local side may still be open. If the channel is full when the empty chunk is due, the driver registers a room wait and tries again on the pass that room starts.a_remote_close_reaches_the_reader_as_eofreads a greeting followed by end of file from a peer that closes at once. - Reset. A socket that reaches
tcp::State::Closedwithout having passed the remote’s FIN was reset (or smoltcp gave up). Bytes the remote sent before the reset are still in the receive buffer and are still delivered; then the driver drops the sender (in_tx = None).WgStream::poll_readsees the channel close without the empty chunk and returnsConnectionReset,wireguard: the tunnelled connection was reset, so a cut-short transfer does not read as a whole one.a_reset_is_not_a_clean_eofreads the bytes sent before an abort, then getsConnectionReset. - Reader gone. If the application dropped the downlink receiver, the driver notices on the next pass, whether or not the socket has data to deliver: it checks
in_tx.is_closed()before reading, andtry_reservereturningClosedcounts the same. It callssocket.close()and setsin_txtoNone. If the remote still sends after that, the bytes can never be handed on, so the driver aborts the socket, which sends a reset: the code compares this to a kernel resetting a socket closed with unread data, where leaving the bytes unread would have the remote push into a closed window and the connection sit in FIN-WAIT-2 for good.a_reader_that_leaves_a_sending_remote_resets_it_at_oncepins it. - Orphan. Once the downlink has ended and every uplink sender is gone (
Uplink::sender_gone),orphan_deadlineis set to now plusLifetimes::orphan_linger. A socket that has not reached Closed by then is aborted, so a remote that never takes the rest of the upload, or never sends its FIN, does not hold the connection for the life of the tunnel. - Removal. A socket in
tcp::State::Closedis removed from theSocketSetandtcp_connsonly once its downlink has ended (in_txisNone) andremote_endpoint()isNone: a FIN that found the reader’s channel full is not lost to the close, and the reset an abort owes the remote has gone out. Its(port, remote)entry leavestcp_in_usewith it, and its room wait, if any, is dropped. A later write fails withBrokenPipe(wireguard: the tunnelled connection is closed). When the local side closes first, the socket passes through TIME-WAIT, which smoltcp holds for 10 s, before it reaches Closed. - Abandoned dial. If a dial is abandoned while its socket is still in SYN-SENT,
socket.close()moves it straight to Closed. smoltcp sends the remote one reset from Closed on the next poll and then forgets the remote, so the driver removes the socket on the next pass.
A UDP association is removed in two cases:
- Its uplink has finished (every sender dropped, the last datagram handed to the socket). It retires on the pass after the one in which that happened:
service_socketschecksuplink.is_finished()at the top of the association’s turn, so theInterface::pollthat starts the pass has already sent its last datagrams. - Its downlink receiver has been dropped and a datagram arrives for it.
Its port leaves udp_in_use when it is removed. Dropping a WgDatagramLink drops both ends, so the first case applies. poll_recv_from on a link whose driver side is gone returns BrokenPipe with the same message.
Connection lifetimes
Section titled “Connection lifetimes”smoltcp bounds nothing by itself: without a timeout a socket retransmits every 60 s forever, and it has no FIN-WAIT-2 timer. A connection that never reaches Closed would stay in the socket set for the life of the tunnel, and every pass sweeps it. Lifetimes (device.rs) bounds every tunnel TCP connection three ways:
#[derive(Clone, Copy, Debug)]pub(crate) struct Lifetimes { pub(crate) keep_alive: Duration, pub(crate) timeout: Duration, pub(crate) orphan_linger: Duration,}| Field | Default | Applied by | Effect |
|---|---|---|---|
keep_alive |
60 s | open_tcp → set_keep_alive |
smoltcp probes a connection after this long without traffic either way. The ACKs its probes draw keep a healthy idle connection clear of timeout |
timeout |
180 s | open_tcp → set_timeout |
smoltcp aborts a connection once no segment from its remote has been accepted for this long, in any state. It must exceed keep_alive and smoltcp’s 10 s TIME-WAIT, or a connection in TIME-WAIT is reset |
orphan_linger |
60 s | service_sockets, through orphan_deadline |
a connection whose downlink has ended and whose uplink senders are all gone is aborted this long later if it has not closed; the doc comment matches it to the minute Linux gives an orphaned socket in FIN-WAIT-2 |
A connection aborted by its timeout reaches Closed without the remote’s FIN, so its reader gets ConnectionReset, as for any reset. smoltcp_duration and smoltcp_after convert the values to smoltcp’s time types. The four tests in protocols/tests/unit/wireguard/device.rs that drive these against the in-process peer pass shorter Lifetimes to WgDevice::start_with.
Reviving an expired session
Section titled “Reviving an expired session”After 90 s without an answer to its handshakes, boringtun clears its sessions and answers every timer tick with ConnectionExpired, sending nothing more: no retries, no keepalives. Only a packet to encapsulate starts a handshake again. The connections still on the tunnel send only when their retransmission timers fire, by then up to a minute apart, so the doc comment on Revival notes that the tunnel would stay dark for that long even with the peer back.
const REKEY_RETRY: Duration = Duration::from_secs(5);
#[derive(Default)]struct Revival { since: Option<tokio::time::Instant>, last_attempt: Option<tokio::time::Instant>,}
impl Revival { fn due(&mut self, in_use: bool) -> bool; fn recovered(&mut self);}On each timer tick that returns TunnResult::Err(WireGuardError::ConnectionExpired), the driver asks revival.due(in_use), where in_use is whether any TCP connection or UDP association is open on the tunnel. due is false when nothing uses the tunnel, since the next dial’s packet starts a handshake anyway. Otherwise the first call of an outage records since and logs wireguard: session expired after unanswered handshakes; retrying every 5s at warn, and due is true at once and then once every REKEY_RETRY (5 s, boringtun’s own retry interval). When it is true, the driver calls Tunn::format_handshake_initiation and sends the initiation like any timer packet. On any other tick where the tunnel has a session (time_since_last_handshake() is Some), recovered clears the attempt time and, if an outage was recorded, ends it and logs wireguard: session re-established after <n>s at info.
Rebuilding the tunnel
Section titled “Rebuilding the tunnel”acquire_device runs under the slot’s mutex and handles three cases.
stateDiagram-v2 [*] --> Empty Empty --> Live: start Ok, started_at = now Empty --> Waiting: start Err, note_failure Live --> Live: is_alive, hand out Arc Live --> Empty: driver stopped after MIN_HEALTHY_LIFETIME, reset failures Live --> Waiting: driver stopped young, note_failure Waiting --> Waiting: before retry_at, tunnel_down error Waiting --> Empty: retry_at passed
- Live device.
device.is_alive()is true: return a clone of theArc. - Dead device. Log
wireguard: tunnel driver stopped, rebuildingatwarnand drop it. If itdied_young(never recorded a start, or ran less thanMIN_HEALTHY_LIFETIME, 10 s), count a failure withnote_failureand returntunnel_down():note_failurehas just setretry_atat least 2 s in the future, so this request never rebuilds. If it ran longer, the death is a fresh problem:failuresandretry_atare reset and the rebuild happens immediately. - No device. If
retry_atis in the future, returntunnel_down(), which isBrokenPipewithwireguard: tunnel is down, waiting before the next attempt. Otherwise callWgDevice::start. Success stores the device andstarted_at; failure callsnote_failure, logswireguard: tunnel start failed: <error>and returns the error.
note_failure increments failures (saturating) and sets retry_at to now plus REBUILD_BACKOFF_BASE * 2^min(failures, 5), capped at REBUILD_BACKOFF_MAX:
failures after the call |
Wait before the next attempt |
|---|---|
| 1 | 2 s |
| 2 | 4 s |
| 3 | 8 s |
| 4 | 16 s |
| 5 or more | 30 s (REBUILD_BACKOFF_MAX) |
A successful start does not reset failures; only the death of a tunnel that lived at least MIN_HEALTHY_LIFETIME does.
The mutex is held across WgDevice::start, including the endpoint lookup. Flows that arrive while a tunnel is being built wait for that build and then receive the same device, instead of each starting a tunnel of their own.
Across an apply, the supervisor carries an unchanged WireGuard outbound over by Arc, and with it its connector, slot and tunnel, so later flows ride the same tunnel. A changed outbound, or any outbound after a change to the DNS spec (every outbound but a blackhole holds the resolvers, supervisor/src/build/dns.rs), is a new version with a slot of its own, whose first flow builds a new tunnel. The version it replaces, like a removed WireGuard outbound, always drains with DrainPolicy::Close, whatever the outbound’s drain or the supervisor’s policy: the drain-policy closure in supervisor/src/topology/spec_plan/plan.rs → plan returns Close for any tag whose old outbound was WireGuard. The reason, in that closure and in the DrainPolicy doc (supervisor/src/policy.rs): the flows run on the old version’s device, which they do not keep alive, and which could not run beside a successor on the same key and peer anyway. An outbound that becomes WireGuard keeps its policy for the version it replaces. See Planning and applying a change.
Invariants
Section titled “Invariants”| Invariant | Mechanism | Pinned by |
|---|---|---|
| All flows routed to one outbound share one tunnel and one UDP socket. | WgConnector clones share Arc<Mutex<DeviceSlot>>; acquire_device returns the stored Arc<WgDevice> while it is alive. |
a_dead_device_is_replaced_on_the_next_request (Arc::ptr_eq on two acquire_device calls) in protocols/tests/unit/wireguard/slot.rs; a_tcp_flow_rides_the_tunnel in protocols/tests/pipeline/wireguard.rs opens a second flow on the same connector |
| A stopped driver is replaced on the next request, not reused. | WgDevice::is_alive checks cmd_tx.is_closed(); acquire_device drops a dead device and starts a new one. |
a_dead_device_is_replaced_on_the_next_request clears the slot itself and checks that the next request builds a live device; the is_alive() == false branch has no dedicated test |
| While the backoff gate is closed, no socket or driver task is created. | acquire_device checks retry_at before calling WgDevice::start. |
the_backoff_gate_refuses_without_building_another_tunnel, a_failed_start_backs_off_before_retrying |
| The backoff grows with repeated failures and never exceeds 30 s. | DeviceSlot::note_failure with REBUILD_BACKOFF_BASE, the min(5) exponent and REBUILD_BACKOFF_MAX. |
repeated_failures_escalate_the_backoff |
| A tunnel that dies within 10 s of starting counts as a failure. | DeviceSlot::died_young against MIN_HEALTHY_LIFETIME. |
a_short_lived_tunnel_counts_as_a_failure |
| An error the path reports (an ICMP answer, a local drop) does not end the driver, on any path. | is_fatal_socket_error treats only NotConnected, BrokenPipe and InvalidInput as fatal, in the udp.recv branch, in take_batch and in send_or_drop, which every send goes through: flush_tx, send_all and the timer’s handshakes and keepalives. |
only_a_broken_socket_is_a_fatal_error, a_pending_icmp_error_does_not_fail_a_send (protocols/tests/unit/wireguard/device.rs), an_unreachable_peer_does_not_kill_the_driver (protocols/tests/unit/wireguard/slot.rs) |
| A tunnel whose session expired is revived while connections use it, and left quiet otherwise. | Revival::due on ConnectionExpired, then format_handshake_initiation every REKEY_RETRY. |
an_expired_session_in_use_is_revived_every_retry_interval, an_expired_session_nobody_uses_stays_quiet, a_handshake_can_be_started_without_a_packet; end to end, the ignored a_tunnel_revives_after_its_peer_was_gone_past_the_handshake_budget |
| No tunnel TCP connection outlives its remote’s silence, its reader, or its application, for long. | Lifetimes: smoltcp keep-alive and timeout per socket; an abort for data with no reader; the orphan linger. |
a_remote_that_vanishes_under_an_idle_connection_is_given_up_on, a_reader_that_leaves_a_sending_remote_resets_it_at_once, an_orphan_whose_remote_went_silent_is_reaped_after_its_linger; an_idle_connection_to_a_live_remote_outlives_the_timeout checks that a live idle connection survives |
| A tunnelled TCP connect reports failure as an error, not as a stream that closes at once. | The oneshot reply in TcpConn::connect_reply, answered on may_send() or tcp::State::Closed; the per-attempt timeout in connect_tcp_any. |
a_tcp_flow_rides_the_tunnel covers the success path |
| Destinations are only tried in families the tunnel has a local address for. | FamilySupport::from_addrs and select_candidate_ips; local_addr_for as a backstop; the supervisor’s validation of address_family against the addresses. |
auto_skips_families_without_a_local_address, the_capability_clause_is_omitted_for_a_kernel_routed_dialer in protocols/tests/unit/helpers/address_family.rs; a_wireguard_address_family_needs_an_address_of_that_family in supervisor/tests/unit/validate.rs |
| A remote close reads as end of file, a reset as an error. | The empty chunk after the last byte for a FIN; a dropped sender, and ConnectionReset in WgStream::poll_read, for a close without one; a closed socket kept until its downlink has ended. |
a_remote_close_reaches_the_reader_as_eof, a_reset_is_not_a_clean_eof, a_half_closed_flow_still_gets_the_whole_reply (protocols/tests/pipeline/wireguard.rs) |
| No two live sockets share a tunnel-side port where smoltcp could confuse them. | PortCursor::next_free against tcp_in_use and udp_in_use; ports released on removal. |
a_port_still_taken_is_skipped_after_the_wrap, a_released_port_is_handed_out_again (device.rs) |
| A connection’s uplink is bounded, and a stalled flow blocks its own writer, not other flows. | Uplink holds at most one item; the channel is read only while nothing is held; service_sockets hands a socket at most CHANNEL_CAP items per pass. |
a_held_item_keeps_the_channel_unread, the_uplink_finishes_only_after_its_last_item in protocols/tests/unit/wireguard/device.rs; a_stalled_tcp_flow_blocks_its_writer in protocols/tests/pipeline/wireguard.rs |
| An unsendable datagram is dropped, not retried. | A UDP send_slice error drops the datagram, unless it is BufferFull for a payload that fits the send ring. |
an_oversized_datagram_does_not_wedge_the_association |
| The driver never blocks on a slow reader, and a stalled reader does not keep it busy. | Downlink uses try_reserve; a full channel leaves data in smoltcp and registers a RoomWaits wait, which runs a pass once the channel has room. |
a_full_downlink_channel_wakes_the_driver_once_it_has_room, a_stalled_reader_does_not_keep_the_driver_busy (protocols/tests/unit/wireguard/device.rs) |
| Reserved bytes are written on every outgoing datagram and cleared on every incoming one before boringtun parses it. | apply_reserved on the flush_tx, send_all and timer paths; the zeroing at the top of decapsulate_all. |
Only wireguard_outbound_live_env_tcp (ignored, see below) can set a non-zero reserved, through ETEMENANKI_WG_RESERVED; the in-process peers use none |
| A TCP flow becomes a stream and a UDP flow becomes a datagram link. | dial branches on dest.network == DialNetwork::Udp. The app turns the other combination into wireguard dialed a TCP flow as UDP (or the reverse). |
a_tcp_flow_rides_the_tunnel, a_udp_flow_rides_the_tunnel |
A name a UDP association could not resolve is looked up again after FAILED_LOOKUP_TTL; a found address is kept. |
Lookups::get and Lookups::record |
a_failed_lookup_is_retried_once_its_ttl_is_up (protocols/tests/unit/wireguard/connector.rs) |
A replaced or removed WireGuard version drains with DrainPolicy::Close. |
the drain-policy closure in plan |
a_wireguard_version_is_always_drained_with_close, an_outbound_turned_into_wireguard_keeps_its_policy (supervisor/tests/unit/plan.rs) |
Failure paths and cancellation
Section titled “Failure paths and cancellation”Errors a caller can see
Section titled “Errors a caller can see”| Where | io::ErrorKind |
Message |
|---|---|---|
WgDevice::start |
InvalidInput |
wireguard: no tunnel-local addresses configured |
WgDevice::start |
NotFound |
wireguard: endpoint domain did not resolve |
WgDevice::start |
as reported | the resolver, bind or connect error itself |
acquire_device |
BrokenPipe |
wireguard: tunnel is down, waiting before the next attempt |
resolve_candidates |
NotFound |
wireguard: destination did not resolve (an empty answer; a resolver error is passed through as is) |
resolve_candidates |
AddrNotAvailable |
wireguard: no usable <strategy> destination address for <host>:<port> (local address supports <families>) |
WgDevice::connect_tcp |
AddrNotAvailable |
wireguard: no tunnel-local address matching destination family |
WgDevice::connect_tcp, connect_udp |
BrokenPipe |
wireguard driver stopped (the command channel or the reply was dropped) |
driver, open_tcp, open_udp |
AddrInUse |
wireguard: every tunnel-side port is in use |
driver, open_tcp |
InvalidInput |
wireguard: connect failed: <smoltcp error> |
driver, open_udp |
InvalidInput |
wireguard: udp bind failed: <smoltcp error> |
driver, service_sockets |
ConnectionRefused |
wireguard: tunnel TCP connect failed |
connect_tcp_any |
TimedOut, whatever the individual reasons |
wireguard: tunnel TCP connect failed for all resolved addresses (<ip>: <reason>; ...) |
WgStream, WgDatagramLink |
BrokenPipe |
wireguard: the tunnelled connection is closed |
WgStream::poll_read |
ConnectionReset |
wireguard: the tunnelled connection was reset (the downlink closed without the remote’s FIN: a reset, a timeout or an abort) |
When the driver stops
Section titled “When the driver stops”The driver task returns, ending the tunnel, when one of these happens:
| Cause | Log |
|---|---|
Every WgDevice handle is dropped, so cmd_rx.recv() yields None. This is the normal shutdown. |
none |
flush_tx or a timer packet (handshake retry, keepalive or revival handshake) hits a fatal send error. |
warn: wireguard: tunnel driver stopping, send failed: <error> |
take_batch hits a fatal error: try_recv while it takes the rest of a batch, or send_all while it answers one. |
warn: wireguard: tunnel driver stopping: <error> |
udp.recv returns a fatal error. |
warn: wireguard: tunnel driver stopping, receive failed: <error> |
A fatal error is one is_fatal_socket_error accepts: NotConnected, BrokenPipe or InvalidInput, meaning the socket itself can no longer be used. Its doc comment gives the reason everything else is survived: almost nothing a connected UDP socket reports is about the socket. ICMP answers to earlier datagrams (refused, unreachable, message too big, administratively prohibited), a local firewall drop, a full conntrack table and an interface going down are each about the path, and WireGuard, being connectionless, recovers once the path does; ending the driver on one would reset every flow on the outbound. Any other error on the receive path is logged at debug (wireguard: receive error: <error>); on every send path the datagram is dropped with a debug line, wireguard: dropping datagram, send error: <error>. boringtun retransmits its handshake from the timers, and once it gives up the driver revives the session while connections use the tunnel (see Reviving an expired session), so a peer that comes back is reached again without a rebuild.
When the driver returns, it drops its Driver value: every smoltcp socket, every in_tx and every uplink receiver. A WgStream whose remote FIN had already been passed on reads end of file; any other reader gets ConnectionReset once the bytes already delivered are read, since its channel closed without the FIN. Writers get BrokenPipe, and WgDevice::is_alive turns false, so the next acquire_device rebuilds.
Cancellation
Section titled “Cancellation”- Dropping a dial future while it waits for the reply. The
oneshotreceiver goes away, and the driver’s laterreply.sendresult is ignored. The uplink sender is dropped with the future, so the uplink channel disconnects, the connection’sUplinkfinishes, andservice_socketscloses and removes the socket as described in Closing. - Dropping a dial future inside
connect_tcp_any. The same as above, for the attempt in flight. The per-attempt timeout drops the attempt in exactly this way before moving to the next candidate. - Dropping a dial future during
acquire_device. The mutex guard is released with the future. IfWgDevice::starthad not yet spawned the task, its socket is simply dropped.
Limits
Section titled “Limits”| Constant | Value | Where | What it limits |
|---|---|---|---|
DEFAULT_MTU |
1420 | config.rs |
Interface MTU when none is configured |
CHANNEL_CAP |
256 | device.rs |
Items in the command channel, and in each per-connection uplink and downlink channel; also the most items one connection hands its socket per pass |
| held uplink item | 1 per connection | device.rs → Uplink |
Items the driver has taken from an uplink channel that the socket has not accepted |
TCP_BUFFER |
64 KiB | device.rs |
Each direction of a smoltcp TCP socket; also the payload storage of each direction of a UDP socket |
| UDP packet metadata | 64 | device.rs → open_udp |
Datagrams per direction a smoltcp UDP socket can hold |
SCRATCH |
64 KiB | device.rs |
scratch and recv_buf, well above an MTU-sized packet plus 32 bytes of WireGuard overhead |
TIMER_TICK |
250 ms | device.rs |
Cadence of Tunn::update_timers |
EPHEMERAL_BASE |
49152 | device.rs |
First tunnel-side port; each PortCursor wraps back here after 65535 and skips ports a live socket holds, so 16 384 ports per protocol |
RECV_BATCH |
64 | device.rs |
Datagrams taken from the peer socket in one pass |
REKEY_RETRY |
5 s | device.rs |
Interval between revival handshakes while an expired session is in use |
Lifetimes::keep_alive |
60 s | device.rs |
Idle time before smoltcp probes a tunnel TCP connection |
Lifetimes::timeout |
180 s | device.rs |
Silence from the remote before smoltcp aborts a tunnel TCP connection |
Lifetimes::orphan_linger |
60 s | device.rs |
Time an orphaned tunnel TCP connection gets to close before it is aborted |
| idle delay | 3600 s | device.rs → compute_sleep |
Sleep when smoltcp has no timer pending |
| out-of-order segments | 16 per socket | protocols/Cargo.toml (assembler-max-segment-count-16) |
Segments smoltcp’s assembler keeps per TCP socket |
| IPv4 reassembly | 4 datagrams | protocols/Cargo.toml (reassembly-buffer-count-4) |
Fragmented IPv4 datagrams smoltcp reassembles at once |
TCP_CONNECT_ATTEMPT_TIMEOUT |
10 s | slot.rs |
Each candidate address in connect_tcp_any |
FAILED_LOOKUP_TTL |
10 s | connector.rs |
How long a UDP association keeps a failed name lookup before it looks the name up again |
REBUILD_BACKOFF_BASE |
1 s | slot.rs |
Base of the rebuild backoff |
REBUILD_BACKOFF_MAX |
30 s | slot.rs |
Cap of the rebuild backoff |
MIN_HEALTHY_LIFETIME |
10 s | slot.rs |
Lifetime below which a stopped tunnel counts as a failure |
The tests that carry traffic through the tunnel dial an in-process peer rather than a real server; the slot tests point the device at 127.0.0.1:1, where nothing listens, or fail before any socket exists. protocols/tests/support/wireguard.rs → spawn_echo_peer(server_priv, client_pub, sink_reads: Arc<AtomicBool>, silent: Arc<AtomicBool>) builds the mirror image of the driver: a second boringtun Tunn bridged to its own smoltcp interface at SERVER_TUN_IP (10.0.0.1/24), with LISTENERS (4) TCP listeners that re-arm after each connection and a UDP socket, all echoing on ECHO_PORT (5555). It also runs a TCP sink at SINK_PORT (5556) with 64 KiB buffers. The sink reads nothing until sink_reads is set, so its 64 KiB receive window closes and the tunnel stops draining a writer to it; it re-arms its listener once closed. A TCP server at CLOSE_PORT (5557) sends GREETING and closes at once, so its FIN follows the greeting; one at RESET_PORT (5558) sends PARTIAL, waits for it to be acknowledged, then aborts, which sends a reset. Both re-arm once closed. One at FLOOD_PORT (5559) keeps its 64 KiB send buffer full for as long as the connection lives. While silent is set, the peer drops every datagram it receives and sends none, timer packets included, like a peer that vanished. The peer binds 127.0.0.1:0, takes the client’s address from each datagram it receives (it sends nothing before the first), zeroes bytes 1 to 3 of every received datagram longer than 3 bytes, and drives its timers every 200 ms. spawn_peer generates two fixed key pairs and returns a Peer with the endpoint, the client’s private key, the server’s public key, sink_reads, the flag a test sets to let the sink read, and silent. The peer notices a change within one of its timer ticks. The client uses CLIENT_TUN_IP (10.0.0.2). The pipeline tests and, through #[path = "../../support/wireguard.rs"], the device unit tests both use this peer.
| Test | File | What it pins |
|---|---|---|
a_tcp_flow_rides_the_tunnel |
protocols/tests/pipeline/wireguard.rs |
Handshake, TCP connect and echo through WgConnector; a second flow on the same connector also echoes; shutdown succeeds |
a_remote_close_reaches_the_reader_as_eof |
protocols/tests/pipeline/wireguard.rs |
A remote that greets and closes reaches the reader as the greeting and then end of file, while the reader’s side is still open |
a_reset_is_not_a_clean_eof |
protocols/tests/pipeline/wireguard.rs |
The bytes sent before a reset are read, then the next read fails with ConnectionReset |
a_half_closed_flow_still_gets_the_whole_reply |
protocols/tests/pipeline/wireguard.rs |
After writing and shutting down its write side, a flow still reads the whole echo |
a_udp_flow_rides_the_tunnel |
protocols/tests/pipeline/wireguard.rs |
A UDP flow becomes a WgDatagramLink; the echo returns, and its source equals the destination sent to |
a_stalled_tcp_flow_blocks_its_writer |
protocols/tests/pipeline/wireguard.rs |
Writing 1 KiB chunks to the sink that does not read, the writer blocks after at most 512 KiB (the expected bound is 385 KiB: the sink’s 64 KiB window, the socket’s 64 KiB, 256 channel chunks and 1 held chunk); a second flow on the same tunnel still echoes; once sink_reads is set, the blocked write completes and 1024 more chunks go through |
an_oversized_datagram_does_not_wedge_the_association |
protocols/tests/pipeline/wireguard.rs |
A 70,000-byte datagram, larger than the 64 KiB send ring, is dropped, and the next datagram on the same association is echoed |
a_held_item_keeps_the_channel_unread |
protocols/tests/unit/wireguard/device.rs |
With an item held, poll_refill stays Pending and the channel fills until try_send reports Full; take then returns the held item first, then the channel in order |
the_uplink_finishes_only_after_its_last_item |
protocols/tests/unit/wireguard/device.rs |
After the sender is dropped, is_finished stays false while an item is held or queued and turns true once the last one is taken and the channel’s end is seen; poll_refill on a disconnected channel returns Ready and records the end |
a_port_still_taken_is_skipped_after_the_wrap, a_released_port_is_handed_out_again |
protocols/tests/unit/wireguard/device.rs |
The cursor skips a port still held after it wraps; after a full lap every port is handed out once, None follows, and a released port comes back |
a_pending_icmp_error_does_not_fail_a_send |
protocols/tests/unit/wireguard/device.rs |
A plain send on a connected socket fails with the ICMP error the previous datagram drew; send_or_drop swallows it |
only_a_broken_socket_is_a_fatal_error |
protocols/tests/unit/wireguard/device.rs |
is_fatal_socket_error is false for ConnectionRefused, ConnectionReset, HostUnreachable, NetworkUnreachable, NetworkDown, PermissionDenied, WouldBlock and TimedOut, and on Linux for EPERM, EACCES, EPROTO, EMSGSIZE, ENETDOWN, ENOBUFS and EHOSTDOWN; true for NotConnected, BrokenPipe and InvalidInput |
an_orphan_whose_remote_went_silent_is_reaped_after_its_linger |
protocols/tests/unit/wireguard/device.rs |
With a 1 s linger and a 60 s timeout, a connection dropped after its peer went silent with data unacknowledged is gone within four lingers |
a_reader_that_leaves_a_sending_remote_resets_it_at_once |
protocols/tests/unit/wireguard/device.rs |
With default lifetimes, dropping a connection to FLOOD_PORT while it sends leaves no connection within 3 s |
a_remote_that_vanishes_under_an_idle_connection_is_given_up_on |
protocols/tests/unit/wireguard/device.rs |
With a 500 ms keep-alive and a 1.5 s timeout, a peer that goes silent under an idle connection ends it, and the reader sees the channel close without a FIN |
an_idle_connection_to_a_live_remote_outlives_the_timeout |
protocols/tests/unit/wireguard/device.rs |
With a 1 s keep-alive and a 3.5 s timeout, an idle connection to a live peer still echoes after twice the timeout |
an_expired_session_in_use_is_revived_every_retry_interval, an_expired_session_nobody_uses_stays_quiet |
protocols/tests/unit/wireguard/device.rs |
On a paused clock: Revival::due is true at once, false straight after, true again after REKEY_RETRY, and true at once for a new outage after recovered; with nothing in use it is false and records no outage |
a_handshake_can_be_started_without_a_packet |
protocols/tests/unit/wireguard/device.rs |
Tunn::format_handshake_initiation yields a 148-byte initiation with no packet to carry |
a_tunnel_revives_after_its_peer_was_gone_past_the_handshake_budget |
protocols/tests/unit/wireguard/device.rs |
#[ignore]d, about 105 s. A connect waits on a silent peer for 95 s, past boringtun’s 90 s budget; once the peer answers again the tunnel has a session within 12 s |
a_full_downlink_channel_wakes_the_driver_once_it_has_room |
protocols/tests/unit/wireguard/device.rs |
RoomWaits keeps one wait per channel, stays Pending while the channel is full, is Ready once the reader takes an item, and drops a forgotten socket’s wait |
a_stalled_reader_does_not_keep_the_driver_busy |
protocols/tests/unit/wireguard/device.rs |
A reader that stops reading FLOOD_PORT leaves the driver running fewer than 40 passes in a second |
a_failed_lookup_is_retried_once_its_ttl_is_up |
protocols/tests/unit/wireguard/connector.rs |
On a paused clock: a failure is kept, then looked up again after FAILED_LOOKUP_TTL; an address is still kept a hundred TTLs later |
an_unreachable_peer_does_not_kill_the_driver |
protocols/tests/unit/wireguard/slot.rs |
A 300 ms connect attempt against 127.0.0.1:1, which answers with ICMP port unreachable, leaves the driver alive |
a_dead_device_is_replaced_on_the_next_request |
protocols/tests/unit/wireguard/slot.rs |
A live device is reused (Arc::ptr_eq); after the test empties the slot and drops its handles, the next request builds a live device |
a_failed_start_backs_off_before_retrying |
protocols/tests/unit/wireguard/slot.rs |
A failed start (InvalidInput) is followed by the BrokenPipe gate error |
a_short_lived_tunnel_counts_as_a_failure |
protocols/tests/unit/wireguard/slot.rs |
died_young for no start, a fresh start and a long-lived tunnel |
repeated_failures_escalate_the_backoff |
protocols/tests/unit/wireguard/slot.rs |
Strictly growing waits for four failures, capped at REBUILD_BACKOFF_MAX after many |
the_backoff_gate_refuses_without_building_another_tunnel |
protocols/tests/unit/wireguard/slot.rs |
No device is stored while the gate is closed |
auto_skips_families_without_a_local_address and the other address_family tests |
protocols/tests/unit/helpers/address_family.rs |
Candidate filtering by FamilySupport and strategy, and the capability clause in the error |
a_wireguard_address_family_needs_an_address_of_that_family |
supervisor/tests/unit/validate.rs |
The spec check of address_family against the addresses |
a_wireguard_version_is_always_drained_with_close, an_outbound_turned_into_wireguard_keeps_its_policy |
supervisor/tests/unit/plan.rs |
A WireGuard version that is changed, replaced by another protocol or removed drains with Close under every policy; an outbound that becomes WireGuard drains its old version under its own |
app_socks_to_wireguard_outbound_on_an_ipv6_endpoint |
app/tests/integration/e2e_wg.rs |
The same round trip to a peer listening on [::1], its endpoint written [::1]:port |
app_socks_to_wireguard_outbound_tcp |
app/tests/integration/e2e_wg.rs |
The real etemenanki-app binary: SOCKS inbound, WireGuard outbound with hex keys, TCP echo through the test file’s own copy of the peer (one listener, TCP only) |
wireguard_outbound_live_env_tcp |
app/tests/integration/e2e_wg.rs |
#[ignore]d. Runs the same app path against a real peer configured through ETEMENANKI_WG_* environment variables (keys, endpoint, addresses, optional MTU, keepalive, reserved, probe target and host) and expects an HTTP response |
Run them from the Etemenanki workspace:
cargo test -p etemenanki-protocols --test pipeline wireguardcargo test -p etemenanki-protocols --lib wireguardcargo test -p etemenanki-protocols --lib address_familycargo test -p etemenanki-supervisor --lib wireguardcargo test -p etemenanki-protocols --lib a_tunnel_revives -- --ignoredcargo test -p etemenanki-app --test integration e2e_wgThe --lib wireguard run includes the device unit tests, which device.rs mounts from protocols/tests/unit/wireguard/device.rs with #[path], as slot.rs and connector.rs do for theirs.