Skip to content

TUN

Source files: 56 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/src/tun/mod.rs
  • Etemenanki/protocols/src/tun/config.rs
  • Etemenanki/protocols/src/tun/device.rs
  • Etemenanki/protocols/src/tun/inbound.rs
  • Etemenanki/protocols/src/tun/ipv6.rs
  • Etemenanki/protocols/src/tun/tracked.rs
  • Etemenanki/protocols/src/tun/udp.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/protocols/src/sniff/collector.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/lib.rs
  • Etemenanki/protocols/Cargo.toml
  • Etemenanki/Cargo.toml
  • Etemenanki/concepts/src/core.rs
  • Etemenanki/concepts/src/runtime.rs
  • Etemenanki/environment/src/routing.rs
  • Etemenanki/environment/src/dial/udp.rs
  • Etemenanki/protocols/src/wireguard/connector.rs
  • Etemenanki/supervisor/Cargo.toml
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/topology/spec_plan/plan.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/router.rs
  • Etemenanki/supervisor/src/topology/plane.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/freedom.rs
  • Etemenanki/supervisor/src/topology/outbound/udp_fanout.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/build/apply.rs
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/supervisor/src/system/listener.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/connector.rs
  • Etemenanki/app/src/config.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/app/src/transport.rs
  • Etemenanki/app/src/instance.rs
  • Etemenanki/app/src/main.rs
  • Etemenanki/ffi/src/client.rs
  • Etemenanki/ffi/src/platform.rs
  • Etemenanki/ffi/src/proxy.rs
  • Etemenanki/protocols/tests/pipeline/tun.rs
  • Etemenanki/protocols/tests/unit/tun/udp.rs
  • Etemenanki/protocols/tests/unit/tun/ipv6.rs
  • Etemenanki/protocols/tests/unit/core/mod.rs
  • Etemenanki/app/tests/unit/lower.rs
  • Etemenanki/app/tests/integration/e2e_tun.rs
  • Etemenanki/supervisor/tests/unit/plan.rs
  • Etemenanki/supervisor/tests/unit/validate.rs
  • Etemenanki/supervisor/tests/unit/plane.rs
  • Etemenanki/environment/tests/unit/routing.rs
  • Etemenanki/ffi/tests/proxy.rs
  • katana/src/lower/inbound.rs

The TUN inbound turns a layer-3 network interface into a source of proxied flows. Its device comes from one of two places: the inbound creates the interface itself, assigns its addresses and installs the routes the operator listed (tun::open), or, on Unix, it takes on a descriptor that a platform VPN API already configured (tun::adopt). Either way the device goes to a userspace IP stack, the ipstack crate, which terminates every TCP connection and UDP flow the host routes into the interface. On Unix the device is a file descriptor; on Windows it is a share of a Wintun adapter’s session. An IPv6 TCP connection that the inbound does not relay, or that no egress it may take could reach, is refused at its handshake, before the stack sees it. Each TCP connection then runs as its own ProxyServerRuntime over a PassthroughCore, and all UDP flows from one client source (address and port) run as one runtime over a TunUdpCore. Every flow is dialled through the supervisor’s AppConnector, which routes it on the current plane and registers it in the flow tracker.

This page is for contributors who change protocols/src/tun/ or the supervisor code that binds and serves a TUN device. It assumes the core and runtime model from Server core and Per-connection runtime. The listener lifecycle around the device is on Listeners and the serve loop, and the operator’s view (settings, routing the host into the device) is on the TUN user guide.

The TUN code:

  • creates, addresses and routes an interface (tun::open), or duplicates a descriptor that something else configured (tun::adopt, Unix only);
  • makes the device ready to read (on Unix, registers its descriptor with the Tokio reactor) and configures the IP stack before an apply commits (TunInbound::prepare), so every step that can fail happens while the apply can still be refused;
  • screens the IPv6 a client sends before the stack sees it, refusing a TCP connection that cannot be relayed with a reset (tun/ipv6.rs → Ipv6Screen);
  • runs the ipstack stack over the device, which answers TCP handshakes itself and splits UDP into one stream per (source, destination) pair;
  • runs one runtime per TCP connection and one per UDP client source, and caps both together at max_flows per runtime;
  • waits, after a runtime stops, for up to RELEASE_TIMEOUT until the device handle has closed and every TCP stream is gone (TunInbound::shutdown).

It does not:

  • parse a protocol header or check a credential. The IP stack already knows each flow’s destination, and a device admits no users.
  • route, dial or meter. make_connector returns the supervisor’s AppConnector, which does all three.
  • decide when a runtime starts, restarts or stops. The supervisor’s listener task (supervisor/src/serve.rs → run_tun_inbound) does.

The stream inbounds pair a byte-stream transport (TCP, TLS, WebSocket, gRPC, REALITY) with a protocol core that decodes one client’s stream. A TUN device does not fit that shape: it is one handle that carries every host the OS routes into it, one IP packet at a time. No single stream in it could stand for a connection.

So, like the Hysteria 2 listener, TunInbound takes the whole device. The userspace stack demultiplexes packets into TCP streams and UDP flows, and the inbound spawns one runtime per TCP stream and one per UDP client source. There is no protocol header and no credential, so the cores have nothing to parse.

supervisor/src/topology/inbound/mod.rs → TunSource says where the device comes from:

TunSource::Create(DeviceSpec) TunSource::Fd(SuppliedTun), #[cfg(unix)]
Lowered by etemenanki-app (app/src/lower.rs → lower_tun) the mobile library (ffi/src/client.rs → supply_tun)
Bound with tun::open, which creates, addresses and routes the interface tun::adopt, which duplicates the descriptor and makes it non-blocking
Privilege Root or CAP_NET_ADMIN on Linux, root on macOS, an elevated process on Windows None: nothing is created, addressed or routed
Who owns the interface The inbound. The system removes the interface, and its routes, when its last Device handle closes; on Windows, Wintun deletes the adapter with the last share of its session. The platform, with its addresses and routes
Same device (==) Every DeviceSpec field is equal: name, mtu, addresses, routes The same raw descriptor number and the same mtu
BindSpec display tun <name>, or tun auto when unnamed tun fd <n>
Validation MTU at least 1280, and check_platform MTU at least 1280

TunSource::addresses() lists the addresses the inbound assigns a created device, and none for a supplied one, whose platform assigned them; the IPv6 screen uses them (see Refusing IPv6 connections).

A created device lives until its last handle closes: the listener’s own, and the duplicate the current runtime reads. The listener stops when no inbound in the spec has its bind any more, or when the supervisor shuts down.

Traffic What happens Where
An IPv6 TCP SYN, when ipv6 = false Refused: answered with a RST,ACK, and the stack never sees it. protocols/src/tun/ipv6.rs → Ipv6Screen::judge, on every read in TunDevice
Every other IPv6 packet, when ipv6 = false Discarded before the stack sees it. Ipv6Screen::judge
An IPv6 TCP SYN that the supervisor’s check calls unreachable, with IPv6 on Refused the same way. Ipv6Screen::judge, asking Ipv6Unreachable; see Refusing IPv6 connections
ICMP and every other IP packet that is neither TCP nor UDP Discarded, since the stack has nowhere to send it. Logged at trace as tun: dropping a packet of an unsupported protocol. protocols/src/tun/inbound.rs → TunInbound::run, the IpStackStream::UnknownTransport arm
Data the stack cannot parse as an IPv4 or IPv6 packet Discarded with the same trace line. ipstack hands it over as IpStackStream::UnknownNetwork when NetworkPacket::parse fails. TunInbound::run, the UnknownNetwork arm
A TCP segment that is not a SYN, for a connection the stack has no session for Answered by the stack with ACK and RST (unless the segment is itself a RST); no stream reaches the accept loop. ipstack: IpStackTcpStream::new refuses a first segment without SYN
UDP, when udp = false The IpStackUdpStream is dropped at once; its Drop retires the stack’s session. TunInbound::run
A UDP reply from a peer the client never addressed, or for a flow the link has already retired Dropped: ipstack can only originate a flow from a packet it has seen, so the reply has no flow to ride. Logged at debug as tun: dropping a reply from <addr>: the client never addressed it. protocols/src/tun/udp.rs → TunUdpLink::poll_send_to
A UDP reply whose source is a domain Dropped: an IP packet cannot carry a domain as its source. Logged at debug as tun: dropping a reply from <destination>: a packet cannot carry a domain. TunUdpCore::handle, Event::Datagram
A zero-length UDP reply Not staged: TunUdpCore stages a reply only when its payload is not empty. TunUdpCore::handle, Event::Datagram
A new TCP connection, or a UDP flow that needs a new association, while every max_flows permit is taken Dropped. Logged at debug as tun: dropping a flow; the flow limit is reached. TunInbound::run
A new UDP flow while its association’s queue is full Dropped; the client retransmits. TunInbound::run, TrySendError::Full

Because replies can only come back on a flow the client opened, one association (and, with a single outbound, one outbound socket) serves every peer the client talks to, while nothing reaches the client from a peer it has not sent to. TunUdpLink keys flows by the far end’s full SocketAddr, so a reply is delivered only from the exact address and port the client has sent to, and a reply from another port on the same host is dropped. In NAT terms the client sees a port-restricted cone.

Every flow is dialled by an outbound on the host’s real uplink. If the operator routes the default route, or the outbound’s own server, into a created device, those dials are steered back into the device and the proxy relays its own traffic into itself. Nothing in the inbound tells such a dial apart from a client’s flow; the module docs and the user guide tell operators to route only what should be proxied. On a supplied device the mobile library asks the platform to protect each socket its dialers open, through a socket-policy hook (ffi/src/platform.rs → socket_options); see Mobile library.

The module is gated twice:

  • protocols/Cargo.toml → feature tun = ["dep:ipstack", "dep:tun-rs", "dep:rtnetlink", "dep:route_manager", "dep:etherparse"], off by default so that a crate wanting only the classic protocols does not inherit an interface-management stack. rtnetlink is a Linux-only target dependency and route_manager a macOS and Windows one; on Windows tun-rs also gets its interruptible feature, which lets a reader blocked on the Wintun session be woken to stop. etherparse, ipstack’s own packet library, is what the IPv6 screen reads packets with.
  • protocols/src/lib.rs → #[cfg(all(feature = "tun", any(unix, windows)))] pub mod tun;.

etemenanki-supervisor 1.1.0 depends on etemenanki-protocols 6.2 with the hysteria, tun and reality features on (supervisor/Cargo.toml), so every front end that links the supervisor compiles the module: etemenanki-app, the mobile library and katana. Only the first two lower a TUN inbound. katana’s src/lower/inbound.rs → lower_inbound produces a BindSpec::Udp for a Hysteria 2 node and a BindSpec::Tcp for every other node, and its credential mapping notes that a panel node is never TUN.

tun::open exists on every Unix target and on Windows, but on Android and iOS it only fails, with io::ErrorKind::Unsupported and tun devices are created by the system VPN API here; adopt its descriptor. There the device must come from adopt.

Platform Device Routes
Linux a kernel tun device netlink (rtnetlink)
macOS a utun device, named utun<N> the routing socket (route_manager)
Windows a Wintun adapter, which needs wintun.dll of the process’s architecture beside the executable the IP helper API (route_manager)
Android, iOS only an adopted descriptor the platform’s

The root Cargo.toml asks for ipstack = "1.0" (the stack), tun-rs = "2.8" (creating the device), rtnetlink = "0.23" and route_manager = "0.2" (installing routes), and protocols/Cargo.toml for etherparse = "0.20"; Cargo.lock resolves them to 1.0.1, 2.8.12, 0.23.0, 0.2.16 and 0.20.3. ipstack has its own TCP implementation; smoltcp is not involved here, and is used only by the WireGuard outbound.

protocols/src/tun/mod.rs declares six public modules, config, device, inbound, ipv6, tracked and udp, and re-exports what a front end or the supervisor needs at the module root: DEFAULT_MAX_FLOWS, DEFAULT_MTU, DEFAULT_UDP_IDLE_TIMEOUT and TunConfig from config; Device, DeviceSpec, check_platform, open and, on Unix, adopt from device; PreparedDevice and TunInbound from inbound; Ipv6Unreachable from ipv6. TrackedTcp, TunUdpLink, TunUdpCore and FLOW_QUEUE stay under their modules.

protocols/src/tun/config.rs holds what the inbound needs once a front end has lowered and the supervisor has validated it:

protocols/src/tun/config.rs
pub const DEFAULT_MTU: u16 = 1500;
pub const DEFAULT_UDP_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
pub const DEFAULT_MAX_FLOWS: usize = 65_536;
pub struct TunConfig<T> {
pub user: Arc<T>,
pub mtu: u16,
pub udp: bool,
pub udp_idle_timeout: Duration,
pub max_flows: usize,
}
Field Meaning What the supervisor sets it to
user What every flow is attributed to, since there is no credential on the wire Principal::anonymous(): no user key, an empty label
mtu The stack’s MTU, and so the largest packet it reads TunSource::mtu(): the DeviceSpec’s or the SuppliedTun’s MTU
udp Relay UDP flows as well as TCP connections TunSpec::udp
udp_idle_timeout ipstack’s per-stream UDP idle timer (IpStackConfig::udp_timeout), one stream per far end TunSpec::udp_idle_timeout
max_flows Permits shared by TCP connections and UDP associations TunSpec::max_flows

The defaults are the front ends’ to apply: etemenanki-app and the mobile library both fill unset values from these three constants. DEFAULT_MAX_FLOWS is a file-descriptor guardrail, since each flow may cost the outbound a socket.

The spec: TunSource, SuppliedTun and TunSpec

Section titled “The spec: TunSource, SuppliedTun and TunSpec”

A TUN inbound is an InboundSpec whose bind is BindSpec::Tun and whose protocol is InboundProtocolSpec::Tun:

supervisor/src/topology/inbound/mod.rs
pub enum TunSource {
Create(DeviceSpec),
#[cfg(unix)]
Fd(SuppliedTun),
}
impl TunSource {
pub fn mtu(&self) -> u16;
pub fn addresses(&self) -> impl Iterator<Item = IpAddr> + '_;
}
#[cfg(unix)]
#[derive(Debug, Clone)]
pub struct SuppliedTun {
pub fd: Arc<OwnedFd>,
pub mtu: u16,
}
supervisor/src/topology/spec_plan/inbound.rs
pub struct TunSpec {
pub udp: bool,
pub udp_idle_timeout: Duration,
pub max_flows: usize,
pub ipv6: bool,
}

The split follows the listener’s identity. Everything about the device, the MTU included, is the bind: plan matches a running inbound by bind ==, so the device is part of the listener’s identity. TunSpec and the inbound’s sniff flag are handler settings, built into the TunHandler. A change to the device or to a handler setting is a disruptive change (see What a reload may change). SuppliedTun implements PartialEq by hand, comparing the raw descriptor number and the MTU; a descriptor’s number is unique while it is open, and both sides hold theirs open. The spec’s other fields are on The spec: desired state.

etemenanki-app parses [inbound.settings] into app/src/config.rs → TunInboundSettings (deny_unknown_fields, every field defaulted) and lowers it in app/src/lower.rs → lower_tun, which returns (BindSpec::Tun(TunSource::Create(device)), InboundProtocolSpec::Tun(tun)). In order, it:

  1. calls reject_inbound_stream(cfg, "tun") (app/src/transport.rs → reject_stream_settings): a [inbound.stream] whose network is set to anything but empty or tcp, or whose security is set to anything but empty or none, is refused with protocol tun does not support stream network "<network>" or protocol tun does not support stream security "<security>";
  2. refuses a listen or port with tun owns a network interface and has no listener; remove listen/port;
  3. deserialises the settings; an unknown key such as mut fails with invalid settings: unknown field `mut`, expected one of `name`, `mtu`, `address`, `routes`, `udp`, `udp_idle_timeout`, `max_flows`, `ipv6`;
  4. parses each address and each route, as below.
TunInboundSettings field Lowered to Default and parsing
name: Option<String> DeviceSpec::name None: the system picks a name. On macOS, validation accepts only utun<N> (check_platform).
mtu: Option<u16> DeviceSpec::mtu DEFAULT_MTU (1500). The floor is the supervisor’s to check, so mtu = 1000 lowers as written (semantic_problems_are_left_to_the_supervisor).
address: Vec<String> DeviceSpec::addresses, as (address, prefix length) Parsed with cidr::IpInet, so host bits may be set; a bare address is a host address. A failure reports bad tun address "<a>": <cidr error>.
routes: Vec<String> DeviceSpec::routes, as (first address, prefix length) Parsed with cidr::IpCidr, so host bits must be zero: routes = ["10.77.1.5/24"] fails with bad tun route "10.77.1.5/24": host part of address was not zero. Installed on Linux, macOS and Windows.
udp: Option<bool> TunSpec::udp true.
udp_idle_timeout: Option<u64> TunSpec::udp_idle_timeout Seconds; DEFAULT_UDP_IDLE_TIMEOUT (60 s).
max_flows: Option<usize> TunSpec::max_flows DEFAULT_MAX_FLOWS (65,536).
ipv6: Option<bool> TunSpec::ipv6 true. With false, every IPv6 TCP connection is refused at its handshake and other IPv6 is dropped, so clients fall back to IPv4 at once.

Every lowering error starts with inbound <tag>: . --test prints it as configuration invalid: inbound <tag>: … and a start as failed to start: inbound <tag>: …. The inbound-level sniffing key (default true) becomes InboundSpec::sniff; a TUN inbound has no user set and no removal policy (users: None, user_removal: None).

The test a_tun_inbound_lowers_to_its_device pins the result: name = "ete0", address = ["10.77.0.1/24", "fd00:77::1/64"] and routes = ["10.77.1.0/24"] lower to a DeviceSpec with mtu 1500, the two addresses with prefixes 24 and 64, and the route (10.77.1.0, 24), beside a TunSpec of udp: true, the two default constants and ipv6: true; ipv6 = false lowers to ipv6: false.

The mobile library lowers the same config with etemenanki-app’s lower and then rewrites the TUN inbound (ffi/src/client.rs → supply_tun). It serves the platform’s descriptor as TunSource::Fd on the config’s one TUN inbound, keeping that inbound’s MTU, UDP settings, flow limit, ipv6 setting and sniffing. When the config names a device name, address or routes, it ignores them and logs at warn: inbound <tag>: the platform owns the tun interface, so its name, addresses and routes in the config are ignored. A config with no TUN inbound gets one tagged tun (the exported constant etemenanki_ffi::TUN_TAG) with every default, IPv6 and sniffing on; a config with two is refused with the config has more than one tun inbound; the platform supplies one device. A TUN inbound bound to anything but a TUN device is refused with inbound <tag>: a tun inbound bound to <bind>, which etemenanki-app’s lowering makes unreachable. Before supply_tun, refuse_servers refuses every inbound that serves a proxy protocol to other hosts; it lets TUN inbounds through. The rest of the library is on Mobile library.

supervisor/src/build/validate.rs owns the rules; a front end checks only syntax.

Rule Where Error, after inbound <tag>:
A TUN protocol is served only on a BindSpec::Tun, and a device serves only TUN validate_inbound, the paired check the protocol cannot be served on <bind>
Two inbounds cannot share one bind validate <bind> is bound by another inbound, for example tun auto is bound by another inbound for two unnamed devices with the same settings
The MTU is at least MIN_TUN_MTU (1280), the IP stack’s own floor validate_inbound, Tun arm tun mtu must be at least 1280
A created device’s spec suits this platform validate_inbound calls tun::check_platform for TunSource::Create only; a supplied device was set up by its platform tun routes are installed only on Linux, macOS and Windows; add them with the OS route tool, elsewhere with routes; on macOS, tun name "<name>": macOS names a tun device utun<N>, or leave it unset for any other name

Each is an ApplyError::Invalid. The whole rule set is on Validation and apply errors.

protocols/src/tun/device.rs:

protocols/src/tun/device.rs
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceSpec {
pub name: Option<String>,
pub mtu: u16,
pub addresses: Vec<(IpAddr, u8)>,
pub routes: Vec<(IpAddr, u8)>,
}
pub fn check_platform(spec: &DeviceSpec) -> io::Result<()>;
#[cfg(unix)]
pub type Device = std::os::fd::OwnedFd;
#[cfg(windows)]
pub struct Device(Arc<tun_rs::SyncDevice>); // try_clone shares the session
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub async fn open(spec: &DeviceSpec) -> io::Result<(Device, String)>;
#[cfg(any(target_os = "android", target_os = "ios"))]
pub async fn open(spec: &DeviceSpec) -> io::Result<(Device, String)>; // always Unsupported
#[cfg(unix)]
pub fn adopt(fd: BorrowedFd<'_>) -> io::Result<Device>;
#[cfg(target_os = "linux")]
async fn install_routes(routes: &[(IpAddr, u8)], ifindex: u32) -> io::Result<()>; // netlink
#[cfg(any(target_os = "macos", windows))]
async fn install_routes(routes: &[(IpAddr, u8)], ifindex: u32) -> io::Result<()>; // route_manager
#[cfg(unix)]
pub(crate) type DeviceIo = AsyncFd<File>;
#[cfg(windows)]
pub(crate) struct DeviceIo {
session: Arc<tun_rs::SyncDevice>,
interrupt: Arc<tun_rs::InterruptEvent>,
}
pub(crate) struct TunDevice {
io: Arc<DeviceIo>,
screen: Ipv6Screen,
#[cfg(windows)]
readable: Option<tokio::task::JoinHandle<io::Result<()>>>,
}
impl TunDevice {
pub(crate) fn new(device: Device) -> io::Result<Self>;
pub(crate) fn screening(self, screen: Ipv6Screen) -> Self;
pub(crate) fn handle(&self) -> Weak<DeviceIo>;
}

A Device is an open device, which lives until its last handle is dropped; try_clone gives another handle. On Unix it is the device’s descriptor. On Windows it is a share of the adapter’s Wintun session, and the adapter is deleted with the last share.

  • check_platform refuses a spec this platform cannot honour. Outside Linux, macOS and Windows it refuses routes (io::ErrorKind::Unsupported, tun routes are installed only on Linux, macOS and Windows; add them with the OS route tool). On macOS it refuses a name that is not utun followed by digits (io::ErrorKind::InvalidInput, tun name "<name>": macOS names a tun device utun<N>, or leave it unset). Validation and open both call it, so --test and a real start refuse the same specs.

  • open builds the interface with tun_rs::DeviceBuilder:

    1. calls check_platform;
    2. sets the MTU and, when given, the name;
    3. gives the builder the first IPv4 address (ipv4(addr, prefix, None)) and every IPv6 address (ipv6_tuple);
    4. calls build_sync. On Windows a failure is wrapped as creating a Wintun adapter (needs wintun.dll beside the executable, and an elevated process): <error>, because Wintun’s own errors name neither the DLL nor the privilege;
    5. adds every further IPv4 address live with add_address_v4, since the builder takes only one;
    6. reads back the interface name and index, and installs the routes with install_routes(&routes, if_index);
    7. on Unix, switches the device to non-blocking and converts it into an OwnedFd; on Windows, wraps it in Device(Arc<SyncDevice>). It returns the device with the name the system settled on.

    Any failure drops the half-built device, which destroys it, so a failed open leaves no interface behind.

  • adopt, Unix only, takes on a device that something else created and configured, such as a mobile VPN API’s descriptor. It duplicates fd (try_clone_to_owned) and sets O_NONBLOCK on the duplicate with fcntl (through socket2::SockRef, which works on any descriptor). It creates, addresses and routes nothing, so it needs no privilege. The caller keeps fd. A duplicate shares its original’s file status flags, so fd becomes non-blocking too.

  • On Linux, install_routes is the netlink equivalent of ip route add <net>/<prefix> dev <ifindex> for every listed network. With no routes it returns at once. Otherwise it opens an rtnetlink connection, spawns its driver task, adds each route with RouteMessageBuilder::<IpAddr> (destination_prefix, output_interface(ifindex), scope(RouteScope::Link)), then drops the handle and aborts the driver task, whether or not every route went in. A netlink error names the route: route <net>/<prefix>: <netlink error>. A prefix that destination_prefix refuses (longer than its address family allows) is reported with the builder’s own text, without the route; etemenanki-app’s lowering parses routes with cidr, so it never produces one. Routes are never removed explicitly: they are scoped to the device and go with it.

  • On macOS and Windows, install_routes returns at once with no routes; otherwise it adds, with one route_manager::RouteManager, an on-link Route::new(net, prefix).with_if_index(ifindex) for every listed network: the equivalent of route add -interface on macOS, or of an on-link New-NetRoute on Windows. An error names the route: route <net>/<prefix>: <error>. These routes are not removed explicitly either: the system drops a route with its interface.

  • TunDevice is the adapter the stack reads through, where one read is one packet and one write is one packet. Every packet the client sends passes the device’s Ipv6Screen first (see The IPv6 screen): a packet the screen drops or refuses is not handed to the stack, and the read loops for the next one. new gives a screen that passes everything; TunInbound::run installs the real one with screening. poll_flush and poll_shutdown are no-ops. handle() hands out a Weak<DeviceIo>; once the stack’s task has dropped the device, upgrade fails, which is how shutdown learns that the handle has closed.

    • On Unix, DeviceIo is an AsyncFd<File>, registered with the Tokio reactor by new through unsafe { AsyncFd::register(File::from(device)) }; tokio has deprecated the safe AsyncFd::new, and register asks its caller to keep the descriptor open and the same for as long as it is registered. The SAFETY comment gives the reasons this holds: the File owns the descriptor, taken over from the OwnedFd, and only its own drop closes it, after the AsyncFd has deregistered it; the AsyncFd is shared behind an Arc and only ever read through get_ref, so the File is never swapped for another, and a File keeps one descriptor for life. std::io::Read and Write are implemented for &File, so the descriptor is driven without libc, and only registering it takes unsafe. On WouldBlock, try_io clears the readiness and the loop polls again.
    • On Windows, Wintun has no readiness to register. A read calls try_recv on the session; on WouldBlock it waits for packets with spawn_blocking(wait_readable_intr) and polls that wait. DeviceIo’s Drop triggers the InterruptEvent, which frees the blocking thread and the session share it holds. A write calls try_send; when the session’s send ring is full, the packet is dropped, as a congested link would drop it, and logged at trace as tun: the session's send ring is full; a packet is dropped.

protocols/src/tun/ipv6.rs decides what becomes of the IPv6 a client sends, before ipstack sees it:

protocols/src/tun/ipv6.rs
pub type Ipv6Unreachable = Arc<dyn Fn(IpAddr, SocketAddr) -> bool + Send + Sync>;
pub(crate) struct Ipv6Screen {
carry: bool,
unreachable: Option<Ipv6Unreachable>,
}
pub(crate) enum Verdict {
Pass,
Drop,
Refuse(Vec<u8>),
}
impl Ipv6Screen {
pub(crate) fn open() -> Self; // everything passes
pub(crate) fn new(carry: bool, unreachable: Option<Ipv6Unreachable>) -> Self;
pub(crate) fn judge(&self, packet: &[u8]) -> Verdict;
}

The stack completes every handshake it is shown, and a flow is dialled only after the client has spoken, so a connection that cannot be relayed would look established to the client and then die mid-request, after the point where the client would have tried another address. A reset in answer to the SYN is a refused connect instead, which a client answers at once by trying its next address: IPv4, for a name that has both. judge works on one packet, with any packet-information header already skipped:

Packet carry false (ipv6 = false) carry true
IPv4, or anything whose version nibble is not 6 Pass Pass
An IPv6 TCP SYN (SYN set, ACK and RST clear) Refuse Refuse when unreachable(source IP, destination) is true, else Pass
Any other IPv6 packet, or one etherparse cannot slice Drop Pass

With carry on and no unreachable function, every packet passes without being parsed. The refusal follows RFC 9293 §3.10.7.1 for a SYN that reaches no listener: an IPv6 packet from the destination back to the source, hop limit 64 (HOP_LIMIT), carrying a TCP segment with RST and ACK set, sequence number 0 and an acknowledgement of the SYN’s sequence number plus one plus its payload length. If the packet cannot be built, the verdict is Drop, and the client’s SYN times out instead.

TunDevice writes a refusal back into the device itself, prefixed on macOS and iOS with the 4-byte utun header for AF_INET6. This is best effort: an error is logged at trace as tun: a refusal was not sent: <error>, and the client’s retransmitted SYN is refused again.

protocols/src/tun/inbound.rs:

protocols/src/tun/inbound.rs
pub struct TunInbound<T> {
config: Arc<TunConfig<T>>,
sniff: bool,
ipv6: bool,
ipv6_unreachable: Option<Ipv6Unreachable>,
device: Arc<Mutex<Option<Weak<DeviceIo>>>>,
live_tcp: Arc<AtomicUsize>,
}
pub struct PreparedDevice {
device: TunDevice,
stack: IpStackConfig,
}
impl<T> TunInbound<T> {
pub fn new(config: TunConfig<T>) -> Self;
pub fn without_sniffing(mut self) -> Self;
pub fn sniffs(&self) -> bool;
pub fn without_ipv6(mut self) -> Self;
pub fn relays_ipv6(&self) -> bool;
pub fn screening_ipv6(mut self, unreachable: Ipv6Unreachable) -> Self;
pub async fn shutdown(&self);
pub fn prepare(&self, device: Device) -> io::Result<PreparedDevice>;
}
impl<T: Send + Sync + 'static> TunInbound<T> {
pub async fn run<C, F>(&self, prepared: PreparedDevice, make_connector: F, token: CancellationToken)
where
F: Fn(IpAddr) -> C + Send + Sync + 'static,
C: Connector<Flow<T>> + Send + 'static,
C::Future: Send,
C::Stream: Send,
C::Datagram: DatagramLink<Addr = Destination> + Send;
}
  • new starts with sniffing and IPv6 on, no Ipv6Unreachable check, an empty device slot and a live_tcp count of zero. without_sniffing turns sniffing off and sniffs reports it; without_ipv6 stops relaying IPv6 and relays_ipv6 reports it; screening_ipv6 installs the check that refuses an IPv6 connection with nowhere to go. Without IPv6 every IPv6 connection is refused whatever the check says.

  • TunInbound is Clone by hand (no T: Clone bound). Clones share config, device and live_tcp, and copy the flags and the check. The supervisor builds a fresh TunInbound for every handler, so each runtime has its own device slot and its own count.

  • device is a parking_lot::Mutex that run fills with the stack’s Weak handle when it starts; shutdown takes it out. live_tcp counts TCP streams that have not finished dropping (see TrackedTcp); it is incremented and decremented with AcqRel and read with Acquire.

  • prepare does everything serving needs that can fail. TunDevice::new(device) registers the descriptor with the reactor on Unix, and creates the session’s InterruptEvent on Windows. Then IpStackConfig::default() (MTU 1280, UDP timeout 30 s, no packet information, TcpConfig::default()) is changed in three places:

    • mtu(config.mtu), refused below 1280; the error becomes io::ErrorKind::InvalidInput with ipstack’s text;
    • udp_timeout(config.udp_idle_timeout);
    • packet_information(true) on macOS and iOS only, where the device prefixes each packet with a 4-byte header.

    The stack’s TCP settings stay at ipstack’s TcpConfig::default(). Nothing reads the device until it is run. Splitting prepare from run lets an apply fail before it commits: once prepared, serving cannot fail to start.

  • run serves a prepared device; cancelling token ends it. It installs Ipv6Screen::new(ipv6, ipv6_unreachable) on the device, stores the stack’s Weak handle in device, starts IpStack::new(stack, device), creates the flow Semaphore with max_flows permits, and owns all per-flow work in a JoinSet<Option<SocketAddr>>, so dropping its future takes every live flow with it. The stack’s own task reads the device into one buffer of mtu bytes, plus 4 when packet information is on, one packet per read, and writes each outgoing packet with one write.

  • make_connector is called once per TCP connection and once per UDP association, with the client’s IP.

TCP: TrackedTcp, PassthroughCore and serve_stream

Section titled “TCP: TrackedTcp, PassthroughCore and serve_stream”

protocols/src/tun/tracked.rs:

protocols/src/tun/tracked.rs
pub struct TrackedTcp {
stream: Option<IpStackTcpStream>,
live: Arc<AtomicUsize>,
}
impl TrackedTcp {
pub fn new(stream: IpStackTcpStream, live: Arc<AtomicUsize>) -> Self;
pub fn stream(&self) -> Option<&IpStackTcpStream>;
}

TrackedTcp wraps an ipstack TCP stream and counts it in the inbound’s live_tcp. new increments the count; Drop first drops the inner stream (self.stream.take()) and only then decrements it. The order matters: while its protocol task is still running, IpStackTcpStream’s own Drop blocks in tokio::task::block_in_place plus Handle::block_on until that task finishes, and the count must cover that blocking part. After the stream is gone, every AsyncRead and AsyncWrite method returns NotConnected (tun: tcp stream already dropped).

protocols/src/core/mod.rs → PassthroughCore is the core every TUN TCP connection runs:

protocols/src/core/mod.rs
pub struct PassthroughCore<T> {
pending: Option<Flow<T>>,
sniff: bool,
prefix: SniffPrefix,
relay: Passthrough<Single>,
timing: Timing,
}
impl<T> PassthroughCore<T> {
pub const BUF_SIZE: usize = 8 * 1024;
pub fn new(flow: Flow<T>) -> Self;
pub fn sniffing(flow: Flow<T>) -> Self;
pub fn is_established(&self) -> bool;
}

Its destination is known before the first byte, so it parses nothing and relays verbatim in both directions (STAGING_RESERVE = 0). The accept loop builds its Flow with Flow::new(Destination { network: DialNetwork::Tcp, remote: Remote::IpAddr(dst.ip()), port: dst.port() }, user, Some(src.ip())), where user is a NetworkUser with an empty UserAuthorization::UsernamePassword and the configured user as its data. The core’s events:

Event Action
Transport, sniffing and still pending Enter Phase::Sniff on the first bytes, which arms SNIFF_TIMEOUT. Hand the bytes to SniffPrefix::push, which takes at most what is left of the SNIFF_LIMIT budget; the core consumes exactly those. On Verdict::Found or Verdict::Exhausted, open.
Transport, otherwise Open if still pending, refresh the idle deadline, and Effect::Forward the whole slice.
Opening Set flow.sniffed from the prefix, enter Phase::Relay, which pushes SetDeadline(RELAY_IDLE_TIMEOUT), then push Effect::Open { key: Single, target: flow }, and Effect::ForwardHeld over the collected bytes when there are any. The deadline goes before the Open because a forward queued after the open waits out the connect, and so would a deadline queued after that forward, leaving the 300 ms sniff deadline armed to end the flow as idle mid-connect (Timing::enter).
Outbound Refresh the idle deadline and stage the bytes toward the client.
TransportEof Open if still pending (a client that closes without sending still gets its flow), then half-close the outbound (Effect::Shutdown), and push Effect::Finish if the outbound has already ended.
OutboundEof Half-close the transport (Effect::ShutdownTransport), and push Effect::Finish if the transport has already ended.
ConnectFailed, OutboundError Drop the pending flow, push ShutdownTransport and Finish.
Connected Nothing (Ok(0)).
Deadline in Sniff Open with what was collected.
Deadline in Relay Timing enters Closing and pushes Effect::Finish.
Deadline in Handshake The error client did not complete its request in time (handshake_timed_out). Unreachable here: the core leaves Handshake on its first event, before anything has armed that deadline.
TransportDatagram, TransportSendFailed, Datagram, SendFailed Ignored (Ok(0)). A TCP flow has a stream transport and a stream outbound, so none of them arrives.

ProxyCoreDecode::held returns the prefix’s collected bytes (SniffPrefix::held). While the ForwardHeld that reads them is queued, the runtime pins that buffer and delivers no byte event, so the bytes stay in place until the forward has been applied; the held-buffer rule is on Sniffing.

sniffing turns sniffing on only when worth_sniffing says the destination is a bare IP, which on a TUN device it always is. Only TCP is sniffed; TunUdpCore has no sniffer. The sniffers and the collector are on Sniffing. PassthroughCore receives time only through the runtime: it arms the runtime’s one timer with Effect::SetDeadline and learns of expiry through Event::Deadline.

protocols/src/tun/inbound.rs
async fn serve_stream<T, C, P>(tcp: TrackedTcp, core: PassthroughCore<T>, connector: C) -> io::Result<()>
where
T: Send + Sync + 'static,
C: Connector<Flow<T>, Datagram = P>,
P: DatagramLink<Addr = Destination>;

serve_stream builds ProxyServerRuntime::<{ PassthroughCore::<()>::BUF_SIZE }, _, _, _>::new(tcp, core, connector).showing_progress() and polls it as a Stream of Result<Traffic, RuntimeError<io::Error>> steps. Until runtime.core().is_established(), each step is wrapped in tokio::time::timeout(HANDSHAKE_TIMEOUT, runtime.next()); a step that times out ends the flow with io::ErrorKind::TimedOut and tun: the client never spoke. After that, steps are polled without an outer timeout. The outer timeout exists because a runtime delivers no event before the client’s first bytes, so a silent client would otherwise never arm the core’s deadline. A RuntimeError is turned into io::Error::other(e.to_string()); a runtime that ends before it is established returns Ok(()).

protocols/src/tun/udp.rs:

protocols/src/tun/udp.rs
pub const FLOW_QUEUE: usize = 16;
pub struct TunUdpLink {
new_flows: mpsc::Receiver<IpStackUdpStream>,
flows: HashMap<SocketAddr, IpStackUdpStream>,
order: Vec<SocketAddr>,
next: usize,
}
impl TunUdpLink {
pub fn new(first: IpStackUdpStream, new_flows: mpsc::Receiver<IpStackUdpStream>) -> Self;
}
impl DatagramLink for TunUdpLink {
type Addr = SocketAddr;
// poll_send_to, poll_recv_from
}

ipstack opens one IpStackUdpStream per (source, destination) pair. TunUdpLink gathers every stream of one client source into one DatagramLink addressed by the far end. In ipstack’s naming, peer_addr is the packet’s destination (the far end) and local_addr its source (the client).

  • Adopting. new adopts the first flow. Every read first drains new_flows (adopt_pending) and adopts each queued stream under its peer_addr(). A stream for a far end the link already has replaces the old one, which is dropped; order keeps one entry per far end. If the channel is closed and no flow is left, the link reports NotConnected with tun: every flow of this association is gone.
  • Reading. poll_recv_from polls the flows round-robin, starting at next, and returns the first datagram with the far end it came from. next then moves past that flow, so one busy far end cannot starve the others. A flow whose read completes without data or with an error, as when its ipstack timer has fired or its session is gone, is retired (removed from flows and order, with next reset to 0 when it falls off the end), and the scan starts over. When order becomes empty and nothing new is queued, the link reports the same NotConnected error, which ends the association. The runtime reads each packet into min(MAX_DATAGRAM, BUF_SIZE) = 4,096 bytes of room, and IpStackUdpStream clamps a longer payload to that room and drops the tail, as recvfrom does.
  • Writing. poll_send_to looks up the flow named by to. No flow means the client never addressed that peer: the reply is dropped, logged at debug, and reported as sent. A write error is logged at trace as tun: flow to <to> ended on write: <error>, retires that flow and also reports success, so one dead far end never fails the association. Because poll_send_to only ever reports success or Pending, the runtime’s TransportSendFailed path never fires on this link. One write is one packet: ipstack truncates a reply to the MTU minus the IP and UDP headers (1,472 bytes over IPv4 and 1,452 over IPv6 at an MTU of 1500) rather than sending a second packet.
protocols/src/tun/udp.rs
pub struct TunUdpCore<T> {
user: Arc<T>,
source: IpAddr,
opened: bool,
timing: Timing,
}
impl<T> TunUdpCore<T> {
pub const BUF_SIZE: usize = 8 * 1024;
pub fn new(user: Arc<T>, source: IpAddr) -> Self;
pub fn is_established(&self) -> bool;
}
impl<T: Send + Sync + 'static> ProxyCoreDecode for TunUdpCore<T> {
type Key = Single;
type Target = Flow<T>;
type Error = io::Error;
type TransportAddr = SocketAddr;
const STAGING_RESERVE: usize = 4096;
const MAX_DATAGRAM: usize = 4096;
// handle
}

TunUdpCore turns the link into one association with a single outbound key (Single). The runtime is built with ProxyServerRuntime::<{ TunUdpCore::<()>::BUF_SIZE }, _, _, _>::over_datagrams(link, core, connector), so a packet’s transport address is its far end.

Event Core action
TransportDatagram, the first one Effect::Open with a Flow toward that far end (DialNetwork::Udp, Remote::IpAddr), the configured user and source; enter Phase::Relay. is_established() is true from here.
TransportDatagram Refresh the idle deadline; if the payload is not empty, Effect::SendTo toward the far end the packet was addressed to.
Datagram (a reply) Refresh the idle deadline. An IP source is staged with fx.put_to(SocketAddr, data), so the link writes it to the flow of its origin; a failure to stage is staging room below the core's declared reserve. A domain source is dropped.
ConnectFailed, OutboundError Effect::Finish, logged at debug as tun: association ended: <error>.
Deadline in Relay Timing enters Closing and pushes Effect::Finish: nothing moved on the association for RELAY_IDLE_TIMEOUT.
Deadline in Handshake The error client did not complete its request in time. Unreachable: the first datagram enters Relay before anything arms that deadline.
SendFailed The packet is dropped, logged at trace as tun: packet to <destination> dropped: <error>; the association continues.
TransportSendFailed The reply is dropped, logged at trace as tun: reply dropped: <error>; the association continues. TunUdpLink never refuses a write, so this arm does not fire over it.
TransportEof Effect::Finish. A datagram runtime does not deliver it: the link’s end arrives as a transport error instead.
Transport, Outbound Consumed and ignored (Ok(data.len())): the transport is a datagram link and the outbound a FanOutLink, so neither arrives.
OutboundEof, Connected Nothing (Ok(0)).

STAGING_RESERVE 4096 plus MAX_DATAGRAM 4096 fill BUF_SIZE exactly. The runtime’s datagram_limit(), the largest reply it delivers whole, is min(MAX_DATAGRAM, BUF_SIZE - STAGING_RESERVE) = 4,096, so each reply is staged whole as one packet; ProxyServerRuntime’s constructor asserts BUF_SIZE > STAGING_RESERVE. TunUdpCore also receives time only through the runtime; its one deadline goes through Effect::SetDeadline and Event::Deadline.

The supervisor turns the spec into a running device in four places; Listeners and the serve loop covers the parts shared with other listeners.

supervisor/src/topology/inbound/mod.rs
pub struct TunHandler {
pub tag: CompactString,
pub inbound: TunInbound<Principal>,
pub own_addresses: Arc<[IpAddr]>,
}
  • Building the handler. supervisor/src/build/inbound.rs → build_handler builds a TunInbound::new(TunConfig { user: Principal::anonymous(), mtu: device.mtu(), udp, udp_idle_timeout, max_flows }), calls without_sniffing() when spec.sniff is false and without_ipv6() when tun.ipv6 is false, and wraps it in InboundHandler::Tun(TunHandler { tag, inbound, own_addresses }), where own_addresses is device.addresses(): the addresses the inbound assigns the device, which are no way out for a flow that came in through it. A TUN spec on another kind of bind fails with the ApplyError::Build building inbound <tag> failed: inbound <tag>: protocol and bind do not match, which validation makes unreachable. The user table is UserTable::None: a device admits no users. When an apply stages user tables, Listener::user_target gives UserTarget::Tun for a TUN listener, whose UserTarget::prepare accepts only UserTable::None, and Listener::store_users does nothing with it; any other table is refused with the handler is not of the kind its listener serves.
  • Binding. supervisor/src/system/listener.rs → bind opens the device while the apply is being prepared. For TunSource::Create it calls tun::open(spec).await and logs inbound <tag> owns tun device <name> at info; for TunSource::Fd, on Unix, it calls tun::adopt(supplied.fd.as_fd()) and logs inbound <tag> serves a supplied tun device. Either way it duplicates the result with try_clone and returns Bound::Tun { device, first }: the listener keeps device, and first is for the first runtime.
  • Pairing and starting. Pending::pair calls handler.inbound.prepare(first), still in prepare. At commit, Listener::start calls spawn_tun, which creates an unbounded mpsc restart channel and spawns run_tun_inbound on the supervisor’s TaskTracker. The listener keeps ListenerKind::Tun { device, restart } and logs inbound <tag> listening on tun <name> (or tun auto, tun fd <n>) at info.
  • Swapping. Listener::prepare_swap duplicates the listener’s device handle (try_clone) and prepares the duplicate for the new handler; Listener::swap sets the listener’s tag and sends (handler, prepared) on restart. When the actor calls them is on Listeners and the serve loop.
supervisor/src/serve.rs
pub(crate) async fn run_tun_inbound(
mut handler: TunHandler,
mut prepared: PreparedDevice,
mut restart: mpsc::UnboundedReceiver<(TunHandler, PreparedDevice)>,
plane: PlaneCell,
flows: Tracker,
stop: CancellationToken,
);

run_tun_inbound runs one runtime at a time on the listener’s device. For each runtime it takes the handler’s inbound with the IPv6 check installed, handler.inbound.clone().screening_ipv6(ipv6_unreachable(&handler, plane)) (see Refusing IPv6 connections), and builds the connector factory

supervisor/src/serve.rs
move |ip| AppConnector::new(
plane.clone(),
FlowContext { inbound_tag: tag.clone(), source: Some(ip) },
flows.clone(),
None,
)

runs inbound.run(prepared, make, token) under token = stop.child_token(), and races it against restart.recv(). When a (handler, prepared) pair arrives, it cancels token, awaits run, awaits the old handler’s shutdown(), and loops with the new handler and its prepared duplicate unless stop has been cancelled. Cancelling stop cancels token too: run returns, shutdown is awaited, and the task returns. So the runtimes of one listener do not overlap: the next starts only after the previous run has returned and its shutdown wait has ended, which waits for up to RELEASE_TIMEOUT for the old runtime’s device handle and TCP streams to go. The None is the session: a device admits no users, so its flows are not sessions, but every flow is still registered in the flow tracker.

sequenceDiagram
  participant F as Front end
  participant A as Supervisor actor
  participant B as listener bind
  participant P as Pending pair
  participant L as Listener start
  participant R as run_tun_inbound
  F->>A: apply spec with a Tun inbound
  A->>A: validate, plan (Bind, Build)
  A->>A: build_handler, TunInbound new
  A->>B: bind: open or adopt, then try_clone
  B-->>A: Bound Tun with device and first
  A->>P: prepare(first)
  P-->>A: PreparedDevice
  A->>L: commit: start
  L->>R: spawn with handler, prepared, restart channel
  R->>R: run: IpStack reads the device

Every step before the commit can fail, and a failure refuses the apply before anything is committed: a device that cannot be opened is ApplyError::Bind, and a descriptor that cannot be registered is ApplyError::Build. supervisor::check, which etemenanki-app’s --test runs, stops short of both: it validates and builds the handler, but binds and prepares nothing, so it opens no device and needs no privilege.

TunInbound::run selects over three branches: the cancellation token, stack.accept(), and flows.join_next() (enabled only while the JoinSet is not empty).

flowchart TB
  A["stack.accept()"] --> K{"IpStackStream"}
  K -->|"Tcp"| P1{"permit?"}
  P1 -->|"no"| D1["drop the connection"]
  P1 -->|"yes"| T["TrackedTcp, PassthroughCore, spawn serve_stream"]
  K -->|"Udp and udp = false"| D2["drop the stream"]
  K -->|"Udp"| Q{"association for this source?"}
  Q -->|"yes, queue has room"| S["try_send into its FLOW_QUEUE"]
  Q -->|"yes, queue full"| D3["drop the flow"]
  Q -->|"none, or its channel closed"| P2{"permit?"}
  P2 -->|"no"| D4["drop the flow"]
  P2 -->|"yes"| U["TunUdpLink, TunUdpCore, spawn runtime"]
  K -->|"UnknownTransport or UnknownNetwork"| D5["drop the packet"]

A TCP connection takes a permit with permits.clone().try_acquire_owned() before it is wrapped in TrackedTcp; the OwnedSemaphorePermit moves into the spawned task and lives until it returns. The task logs an error from serve_stream at debug as tun: tcp flow <src> -> <dst> ended: <error> and returns None.

associations: HashMap<SocketAddr, mpsc::Sender<IpStackUdpStream>> maps each client source (IP and port) to the queue of its association. A new association gets mpsc::channel(FLOW_QUEUE), its sender goes into the map, and its task runs the runtime, logs an error at trace as tun: udp association of <src> ended: <error>, and returns Some(src). When the join_next branch sees that result, it removes the map entry only if that entry’s sender is closed, so an entry that a newer association of the same source has taken over stays. A try_send that finds the channel closed removes the entry too, and the flow opens a fresh association.

sequenceDiagram
  participant C as Client host
  participant S as ipstack
  participant L as TunInbound run loop
  participant R as serve_stream
  participant O as AppConnector
  C->>S: SYN (routed into the device)
  S->>L: IpStackStream Tcp (on the SYN)
  S-->>C: SYN-ACK, handshake completes in the stack
  L->>L: take a permit, wrap in TrackedTcp
  L->>R: spawn with PassthroughCore
  C->>S: first payload bytes
  S->>R: Event Transport
  R->>R: sniff up to SNIFF_LIMIT or SNIFF_TIMEOUT
  R->>O: Effect Open with the sniffed domain
  O-->>R: outbound stream
  R->>O: held prefix, then relay both ways

ipstack hands the stream to the accept loop on the SYN and completes the client’s TCP handshake itself, before anything is dialled: the stream’s own task, spawned when the stream is created, sends the SYN-ACK first thing. The outbound is dialled only once the client has sent bytes, or has closed its side. Three consequences follow:

  • A successful connect on the client does not mean the destination is reachable. If the dial fails, PassthroughCore handles ConnectFailed through Passthrough::on_outbound_gone, which pushes ShutdownTransport and Finish.
  • A connection the accept loop drops at the max_flows limit has already been sent a SYN-ACK, so the client’s connect can succeed. Dropping the stream ends its session in the stack, and the stack answers a later segment that finds no session with ACK and RST.
  • A protocol whose server speaks first (SMTP, MySQL) stalls through this inbound: the client waits for a greeting, the runtime waits for the client, and serve_stream gives up after HANDSHAKE_TIMEOUT with tun: the client never spoke. Turning sniffing off does not change this, since the flow still opens only on the client’s first event.

The phases of the core’s single deadline (Timing) on a TUN connection:

stateDiagram-v2
  [*] --> Handshake: nothing armed
  Handshake --> Sniff: first bytes, sniffing on (arms SNIFF_TIMEOUT)
  Handshake --> Relay: first bytes with sniffing off, or client EOF
  Sniff --> Relay: Found, Exhausted, SNIFF_TIMEOUT or EOF, then Open
  Relay --> Relay: byte event re-arms RELAY_IDLE_TIMEOUT
  Relay --> Closing: RELAY_IDLE_TIMEOUT expires, Finish pushed

is_established() is true in Relay and Closing, which is when serve_stream drops its outer HANDSHAKE_TIMEOUT. PassthroughCore leaves Handshake on its first event (it opens, or enters Sniff), so its own handshake deadline is never armed; the outer timeout is the only watchdog before that event. Timing does not end a flow itself: on expiry in relay it moves to Closing and pushes Effect::Finish, and the half-close rules push Effect::Finish when both halves have closed or the outbound is gone, without changing the phase.

sequenceDiagram
  participant C as Client source A
  participant L as TunInbound run loop
  participant K as TunUdpLink
  participant U as TunUdpCore
  participant O as FanOutLink
  C->>L: flow A to X (new source)
  L->>K: new link, FLOW_QUEUE channel
  K->>U: TransportDatagram from X
  U->>O: Open, then SendTo X
  C->>L: flow A to Y (same source)
  L->>K: try_send into the queue
  K->>U: TransportDatagram from Y
  U->>O: SendTo Y
  O-->>U: Datagram from Y
  U->>K: put_to Y
  K-->>C: packet from Y to A
  O-->>U: Datagram from Z
  U->>K: put_to Z
  K->>K: no flow to Z, dropped

udp_idle_timeout is passed to IpStackConfig::udp_timeout, ipstack’s per-stream UDP timer, one stream per far end. A stream whose timer has fired returns TimedOut on its next read, and the link retires it. When the last flow retires and nothing new is queued, poll_recv_from returns NotConnected; the runtime ends with RuntimeError::Transport, logged at trace as tun: udp association of <src> ended: transport: tun: every flow of this association is gone, and the association’s permit is released. Separately, the core’s RELAY_IDLE_TIMEOUT deadline pushes Effect::Finish when no datagram has moved in either direction for that long. Flows still queued in the channel when an association ends are dropped with it; the client’s next packet then opens a fresh association.

The TUN inbound hands each flow to the supervisor through the connector make_connector returns. Each TCP connection and each UDP association gets its own AppConnector, whose FlowContext carries the inbound’s tag and source: Some(ip). The Flow carries the client’s IP as its own source too, and the router prefers the flow’s source over the context’s, so both name the same host here.

  • TCP. AppConnector::connect loads the current plane once, routes the flow on it (route_target gives the rules the destination, a sniffed domain, the inbound tag, the source and the network, TCP or UDP), resolves a balancer to a member, and opens the stream on that target. The stream is metered as one flow in the tracker: its FlowMeta carries no session, the inbound tag, the connector context’s source, the target, the matched rule and the plane’s epoch. A route change reaches the next connection; this one keeps the target it opened on unless Supervisor::close_rerouted closes it (below).
  • UDP. connect for a DialNetwork::Udp flow dials nothing: it returns a FanOutLink, which routes each packet on the plane current when the packet is sent and opens one sub-link per routed target (at most MAX_SUBS, 64, at a time; the one least recently sent to goes first), each a tracked flow of its own. So one association can reach several outbounds. A sub-link that fails to open is logged at debug as udp fan-out: opening <id> failed: <error>. charge_datagrams stays off, as it does for every connector but SOCKS UDP’s, and there is no session whose wire bytes it could charge anyway.

A TUN flow belongs to no user: its principal is Principal::anonymous() and its connector has no session, so it counts toward no user’s usage and Supervisor::close does not reach it, while the tracker lists it under the inbound tag with the client’s source, among the flows a kill can select. Supervisor::close_rerouted reaches it as it reaches every tracked flow, and closes it when the current routing would send it to another outbound. The mobile library calls it after Proxy::set_route with close_connections set, and from Proxy::close_rerouted, so that apps reconnect through the new node (Mobile library). See The plane: routing each flow, Outbounds, UDP fan-out and balancers and Tracking flows, stats and speed limits.

With IPv6 on, the screen asks the supervisor about every IPv6 TCP SYN before the stack answers it, and refuses the connection when nothing it could be relayed over reaches IPv6:

flowchart TB
  P["IPv6 packet from the client"] --> C{"ipv6 on?"}
  C -->|"no"| S1{"TCP SYN?"}
  S1 -->|"yes"| R["RST,ACK back to the client"]
  S1 -->|"no"| D["dropped"]
  C -->|"yes"| S2{"TCP SYN?"}
  S2 -->|"no"| PASS["handed to ipstack"]
  S2 -->|"yes"| Q{"Plane::ipv6_unreachable"}
  Q -->|"true"| R
  Q -->|"false"| PASS

The check is supervisor/src/serve.rs → ipv6_unreachable(&handler, plane), an Ipv6Unreachable closure that holds the inbound’s tag, may_sniff = handler.inbound.sniffs() and the device’s own_addresses. For each SYN it builds a FlowContext with the inbound tag and the client’s IP and asks the plane current at that moment, Plane::ipv6_unreachable(destination, &ctx, may_sniff, &own) (supervisor/src/topology/plane.rs). When the answer is true it logs at debug inbound <tag>: refusing <src> -> <dst>: no route to IPv6 from any egress it may take.

Plane::ipv6_unreachable never refuses a port-53 destination while a DNS service is configured, since the service answers it. Otherwise it asks CompiledRoutes::every_outcome, which builds a TCP route target from the destination and the context and calls environment/src/routing.rs → RouteTable::every_outcome: true only if every outcome the flow could still get lacks IPv6. Those outcomes are the rule it matches now (or the default) and, when a domain may still be sniffed from its payload (may_sniff, and no sniffed domain yet), every earlier rule with a domain matcher, which a sniffed domain could make match. A sniffed domain only adds matches, and only to domain matchers, so no rule after the one matching now can be reached. A balancer target lacks IPv6 only when every member does (Target::lacks_ipv6).

supervisor/src/topology/outbound/mod.rs → Outbound::lacks_ipv6(destination, own) decides for one outbound. Only a direct dial and a WireGuard tunnel can tell:

Outbound Lacks IPv6 when
freedom (outbound/freedom.rs → FreedomConnector::lacks_ipv6) its address-family policy does not allow IPv6; or the kernel has no route: UdpDialer::source_toward(destination) fails with NetworkUnreachable, HostUnreachable or AddrNotAvailable; or the source the kernel would pick is one of the device’s own addresses; or that source is link-local and the destination is not
wireguard !WgConnector::reaches(ip): the policy does not allow the family, or the tunnel has no address of it (protocols/src/wireguard/connector.rs)
every proxy outbound, blackhole and dns never: a proxy’s server is assumed to reach what its protocol can address, and IPv6 rides an IPv4 connection to it

UdpDialer::source_toward (environment/src/dial/udp.rs) opens a UDP socket of the destination’s family under the outbound’s socket policy, binds it to the policy’s bind address when there is one, and connects it, which only looks the route up and sends nothing; the local address is the source the kernel would use. Because it runs under the outbound’s policy, the mark and interface its dials carry route the question too. Any other failure, such as a mark the process may not set, logs at debug direct: cannot tell whether <dst> is reachable: <error> and refuses nothing.

Only TCP connections are refused. With IPv6 on, IPv6 UDP and the rest of IPv6 pass to the stack as before.

Invariant Enforced by Pinned by
One UDP association per client source; a second destination rides it without a second Open. The associations map and the FLOW_QUEUE channel in TunInbound::run; opened in TunUdpCore. udp_flows_share_one_association_per_source (protocols/tests/pipeline/tun.rs); the_first_packet_opens_the_association_and_every_packet_is_sent (protocols/tests/unit/tun/udp.rs)
A UDP reply returns as a packet from its origin to the client, addresses and ports swapped; a domain-sourced reply is dropped. fx.put_to in TunUdpCore::handle and the per-far-end lookup in TunUdpLink::poll_send_to. replies_go_back_as_packets_from_their_origin_and_domains_are_dropped; udp_flows_share_one_association_per_source
The UDP core pushes Effect::Finish when its outbound fails or its relay deadline expires. Effect::Finish on ConnectFailed / OutboundError; Timing::expired in relay. the_association_finishes_when_the_outbound_fails_or_idles
A TCP connection is dialled toward the packet’s destination, with the client’s source, only once the client has spoken; the first bytes are carried and the HTTP Host becomes the sniffed domain. PassthroughCore::on_transport and SniffPrefix; Effect::ForwardHeld. a_tcp_connection_becomes_a_stream; a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host, a_sniffing_passthrough_core_opens_on_the_sniff_deadline, passthrough_core_opens_on_the_first_bytes_and_relays_verbatim (protocols/tests/unit/core/mod.rs)
A relaying TCP flow half-closes each side and pushes Effect::Finish on the second; a failed dial, or the relay deadline expiring, pushes Effect::Finish. Passthrough and Timing. passthrough_half_closes_each_side_and_finishes_on_the_second, passthrough_core_finishes_when_the_outbound_fails_or_idles
The one deadline is armed per phase: the handshake deadline once, the idle deadline on every relay byte event, and handshake and sniff expiry are left to the core. Timing::touch, enter and expired. timing_arms_handshake_once_then_idle_per_byte_event, timing_reports_handshake_and_sniff_expiry_to_the_core (protocols/tests/unit/core/mod.rs)
The sniff prefix keeps every byte it took, across pushes, and never takes more than SNIFF_LIMIT. SniffPrefix::push. sniff_prefix_finds_a_host_across_pushes_and_keeps_the_bytes, sniff_prefix_takes_no_more_than_its_budget
A silent TCP client is cut off. tokio::time::timeout(HANDSHAKE_TIMEOUT, …) around each step before the core is established, in serve_stream. No dedicated test
At most max_flows TCP connections plus UDP associations run at once on one runtime. Semaphore::new(max_flows) created by run, try_acquire_owned, and the permit held by the spawned task. No dedicated test
A TCP stream is counted until its blocking Drop has finished. TrackedTcp::drop takes and drops the stream before fetch_sub. Exercised by the teardown of both pipeline tests (Fake::stop awaits shutdown)
A TUN protocol runs only on a TUN bind, with an MTU of at least 1280. validate_inbound. each_protocol_is_served_only_on_its_kind_of_bind, a_tun_device_mtu_is_at_least_1280 (supervisor/tests/unit/validate.rs)
etemenanki-app lowers exactly the device and settings the config names, and leaves the MTU floor to the supervisor. lower_tun. a_tun_inbound_lowers_to_its_device, syntax_errors_are_refused, semantic_problems_are_left_to_the_supervisor (app/tests/unit/lower.rs)
A device change or a settings change is a Disrupt step. plan (the replaces_device check and swap_disruption). a_tun_device_change_opens_a_new_device_and_disrupts, a_tun_settings_change_on_the_same_device_swaps_and_disrupts (supervisor/tests/unit/plan.rs)
The runtimes of one listener do not overlap: the next starts only after the previous one’s run has returned and its shutdown wait (at most RELEASE_TIMEOUT) has ended. run_tun_inbound awaits run and TunInbound::shutdown before it loops. No dedicated test
A created interface and its routes exist while etemenanki-app serves them. Device-scoped routes (RouteScope::Link, output_interface on Linux; on-link routes with the interface index on macOS and Windows); the system removes both when the last handle closes. a_routed_connect_is_answered_while_the_app_runs (app/tests/integration/e2e_tun.rs)
With ipv6 = false, every IPv6 SYN is answered with a RST,ACK the client accepts as a refusal, every other IPv6 packet is dropped, and IPv4 passes. Ipv6Screen::judge with carry false. with_ipv6_off_a_syn_is_answered_with_a_reset_the_client_accepts, with_ipv6_off_everything_else_of_ipv6_is_dropped_and_ipv4_passes (protocols/tests/unit/tun/ipv6.rs); an_ipv6_connect_to_an_unreachable_egress_is_refused_at_the_handshake (protocols/tests/pipeline/tun.rs)
With IPv6 on, only a SYN the check calls unreachable is refused, before the stack answers it; one it does not is accepted as usual. Ipv6Screen::judge with an Ipv6Unreachable check, installed by run. with_ipv6_on_only_a_syn_the_gate_calls_unreachable_is_refused (unit/tun/ipv6.rs); an_ipv6_connect_to_an_unreachable_egress_is_refused_at_the_handshake
An IPv6 connection counts as unreachable only when every target it may still be routed to lacks IPv6: a domain rule a sniffed name could still match counts, so does every member of a balancer, and the DNS service always answers. Plane::ipv6_unreachable, RouteTable::every_outcome, Target::lacks_ipv6. ipv6_is_unreachable_only_when_every_possible_target_lacks_it (supervisor/tests/unit/plane.rs); every_outcome_counts_the_domain_rules_a_sniff_could_still_reach (environment/tests/unit/routing.rs)
A supplied descriptor carries TCP and UDP to the outbound, and its flows are tracked under the inbound tag with the client’s source. adopt, run_tun_inbound and AppConnector. a_tun_device_carries_tcp_and_udp_to_the_outbound (ffi/tests/proxy.rs)
Failure Outcome
open fails at start (no privilege to create an interface, a netlink or route_manager error, on Windows a missing wintun.dll) ApplyError::Bind, which etemenanki-app logs as failed to start: inbound <tag>: binding tun <name> failed: <error> (tun auto when unnamed) and exits with a failure status. On Windows a failed build_sync reads creating a Wintun adapter (needs wintun.dll beside the executable, and an elevated process): <error>. The half-built device is already destroyed.
A route cannot be installed The same ApplyError::Bind, with the source route <net>/<prefix>: <error>, from netlink on Linux or route_manager on macOS and Windows.
open on Android or iOS Unsupported: tun devices are created by the system VPN API here; adopt its descriptor.
adopt or a try_clone in bind fails ApplyError::Bind: inbound <tag>: binding tun fd <n> failed: <error> for a supplied descriptor.
prepare fails: the descriptor cannot be registered with the reactor, the Windows interrupt event cannot be created, or the stack refuses the MTU (unreachable after validation) ApplyError::Build: building inbound <tag> failed: <error>. Nothing has been committed.
The listener’s device handle cannot be duplicated for a swap ApplyError::Build from prepare_swap, with the same text.
TCP client silent before open serve_stream returns TimedOut (tun: the client never spoke), logged at debug as tun: tcp flow <src> -> <dst> ended: tun: the client never spoke.
Runtime error on a TCP flow Converted with io::Error::other(e.to_string()) and logged at debug with the same prefix.
Dial fails on a TCP flow The core shuts the client’s connection down and finishes; the runtime ends without an error.
UDP association ends: every flow retired, outbound failed, idle An error is logged at trace as tun: udp association of <src> ended: <error>; the task returns Some(src) and the map entry is removed.
Write to one UDP flow fails That flow is retired; the association continues.
A refusal of an IPv6 SYN cannot be written to the device Logged at trace as tun: a refusal was not sent: <error>; the client’s retransmitted SYN is refused again.
The Wintun send ring is full The packet is dropped, logged at trace as tun: the session's send ring is full; a packet is dropped.
A runtime’s device handle or TCP streams outlive RELEASE_TIMEOUT shutdown logs tun: device handle or <n> tcp flows still open after 3s at warn and returns.

plan treats a TUN inbound by its bind (supervisor/src/topology/spec_plan/plan.rs):

Change Plan Step::Disrupt reason
Nothing Reuse: the runtime and its flows carry on None
The device (DeviceSpec or SuppliedTun) A Disrupt step the tun device changed; the old device and its flows end
A handler setting: sniff, udp, udp_idle_timeout, max_flows, ipv6 A Disrupt step the tun inbound's settings changed; its runtime restarts and its flows end
The inbound removed StopAccepting, CloseSessions None

etemenanki-app refuses a TUN change: its reload is refused right after planning, before any device is opened or prepared, so what runs is untouched, and it logs at error from app/src/instance.rs → Core::reload_with:

reload refused, keeping the running config: inbound <tag>: <reason>, which would end its live connections; restart to apply it

A restart applies the change. Removing a TUN inbound is not a disruption step: its listener stops, which cancels the runtime’s token and so ends the runtime and its flow tasks, as the next section describes. The plan and apply machinery is on Planning and applying a change, and etemenanki-app’s reload loop on etemenanki-app: running, reloading and shutting down.

run is cancelled by its CancellationToken, a child of the listener’s stop token, which is itself a child of the supervisor’s root. run_tun_inbound cancels it when a restart arrives; cancelling the listener’s stop token cancels it as well. Breaking out of the loop returns from run, which drops the JoinSet (aborting every flow task), the associations map and the IpStack. IpStack’s Drop aborts the stack task that owns the TunDevice, but an abort only lands when the Tokio runtime next schedules that task, so the device handle outlives the drop by a moment. Each IpStackTcpStream dropped with its flow task blocks in its own Drop until its protocol task has finished, which TrackedTcp counts in live_tcp.

shutdown covers that gap. It takes the Weak device handle out of the mutex and polls every RELEASE_POLL (20 ms) until the handle no longer upgrades and live_tcp is zero, for at most RELEASE_TIMEOUT (3 s). On timeout it logs a warning (tun: device handle or <n> tcp flows still open after 3s) and returns.

sequenceDiagram
  participant T as run_tun_inbound
  participant R as TunInbound run
  participant S as ipstack task
  participant H as TunInbound shutdown
  T->>R: cancel the child token
  R->>R: break, drop the JoinSet (flow tasks aborted)
  R->>S: IpStack dropped, task aborted
  R-->>T: run returns
  T->>H: await shutdown
  S-->>H: TunDevice dropped, Weak no longer upgrades
  H->>H: poll every 20 ms until live_tcp is 0, at most 3 s
  H-->>T: returns

Stopping the listener (Listener::stop) cancels the parent token. The two callers differ in when the listener, and with it its own device handle, is dropped:

  • On Step::StopAccepting, the actor removes the listener from its list as it stops it (listeners.swap_remove(at).stop()), so the listener’s device handle closes at once while the runtime winds down. The system removes a created interface once the runtime’s duplicate has closed too.
  • At shutdown, the actor stops every listener first and clears its list only after its task tracker has drained, as the next section describes.

etemenanki-app’s main calls Instance::shutdown(SHUTDOWN_GRACE), 5 s, on SIGTERM or Ctrl-C, which reaches Supervisor::shutdown. Actor::shutdown then, in order:

  1. stops every listener;
  2. cancels its balancer probes;
  3. closes its task tracker and waits on it for at most the grace;
  4. cancels the root token and waits on the tracker again;
  5. clears its listeners, which closes each listener’s device handle.

Stopping a TUN listener cancels its runtime’s token, so the runtime and its flows end as soon as the listener stops, without waiting for the grace. Stream connections, by contrast, may run until they end or the grace passes, when the root token cancels them. The tracker includes each run_tun_inbound task and so its shutdown wait, which gives TCP streams up to RELEASE_TIMEOUT to finish dropping before the Tokio runtime goes.

Constant Value Where Meaning
DEFAULT_MTU 1500 protocols/src/tun/config.rs Device and stack MTU when mtu is unset.
MIN_TUN_MTU 1280 supervisor/src/build/validate.rs Smallest MTU a spec may name; ipstack’s IpStackConfig::mtu refuses less too.
DEFAULT_UDP_IDLE_TIMEOUT 60 s protocols/src/tun/config.rs ipstack’s per-stream UDP timer when unset, one stream per far end; passed to IpStackConfig::udp_timeout, replacing ipstack’s own default of 30 s.
DEFAULT_MAX_FLOWS 65,536 protocols/src/tun/config.rs Permits shared by TCP connections and UDP associations when unset, per runtime; a file-descriptor guardrail, since each flow may cost the outbound a socket.
FLOW_QUEUE 16 protocols/src/tun/udp.rs New UDP flows queued toward one association before further ones are dropped.
RELEASE_TIMEOUT 3 s protocols/src/tun/inbound.rs Longest shutdown waits for the device handle and live TCP streams.
RELEASE_POLL 20 ms protocols/src/tun/inbound.rs Poll interval of that wait.
HANDSHAKE_TIMEOUT 10 s protocols/src/core/mod.rs Per step before a TCP flow opens, applied by serve_stream.
SNIFF_TIMEOUT 300 ms protocols/src/sniff/mod.rs Sniff window before a TCP flow opens without a domain.
SNIFF_LIMIT 4 KiB protocols/src/sniff/mod.rs Bytes inspected for a domain.
RELAY_IDLE_TIMEOUT 300 s protocols/src/core/mod.rs The cores’ idle deadline, armed in Relay and re-armed on every byte event; on expiry Timing pushes Effect::Finish.
PassthroughCore::BUF_SIZE 8 KiB protocols/src/core/mod.rs The BUF_SIZE the TCP runtime is built with; see Per-connection runtime.
TunUdpCore::BUF_SIZE 8 KiB protocols/src/tun/udp.rs The BUF_SIZE the UDP runtime is built with: one datagram plus the staging reserve.
TunUdpCore::MAX_DATAGRAM 4096 protocols/src/tun/udp.rs Largest datagram delivered whole in either direction; a longer client datagram is clamped by IpStackUdpStream to the runtime’s 4,096-byte read and its tail dropped, which only matters with an mtu above about 4 KiB.
TunUdpCore::STAGING_RESERVE 4096 protocols/src/tun/udp.rs Staging room the runtime keeps free before it delivers an event, so each reply is staged whole as one packet.
Packet-information header 4 bytes TunInbound::prepare Prefixed to every packet on macOS and iOS; packet_information is off elsewhere. The stack’s read buffer is mtu bytes, plus these 4 when it is on. The IPv6 screen skips it, and prefixes its refusals with the AF_INET6 header.
HOP_LIMIT 64 protocols/src/tun/ipv6.rs Hop limit of a refusal sent to an IPv6 SYN.
ipstack defaults replaced MTU 1280, UDP timeout 30 s ipstack: IpStackConfig::default() Replaced by the configured mtu and udp_idle_timeout; the TCP settings stay at TcpConfig::default().
SHUTDOWN_GRACE 5 s app/src/main.rs etemenanki-app’s grace for live connections at shutdown; TUN flows end as soon as their listener stops, without waiting for it.
Test File What it proves
with_ipv6_off_a_syn_is_answered_with_a_reset_the_client_accepts, with_ipv6_off_everything_else_of_ipv6_is_dropped_and_ipv4_passes, with_ipv6_on_only_a_syn_the_gate_calls_unreachable_is_refused protocols/tests/unit/tun/ipv6.rs The screen: the refusal is a RST,ACK from the destination to the client, sequence 0, acknowledging the SYN plus its payload (a Fast Open SYN’s data counts), with a checksum the client’s kernel accepts; with IPv6 off a SYN-ACK, data and UDP are dropped and IPv4 passes; with IPv6 on only SYNs are asked about, with the client’s address and the destination.
an_ipv6_connect_to_an_unreachable_egress_is_refused_at_the_handshake protocols/tests/pipeline/tun.rs Through the stack: an IPv6 SYN the check calls unreachable is answered with RST,ACK and one it does not with SYN-ACK; with IPv6 off, a SYN is refused.
the_client_sees_fin_after_the_outbound_closes_with_data_in_flight protocols/tests/pipeline/tun.rs Marked #[ignore]: with ipstack 1.0.1 the FIN is not sent when the outbound’s close races data the client has not yet acknowledged, which waits on an ipstack fix (its issue 89).
ipv6_is_unreachable_only_when_every_possible_target_lacks_it supervisor/tests/unit/plane.rs A direct outbound allowed only IPv4 makes a connection routed to it unreachable, unless a domain rule a sniff could still match leads elsewhere; a balancer refuses only when every member lacks IPv6; a port-53 flow to a DNS service is never refused.
every_outcome_counts_the_domain_rules_a_sniff_could_still_reach environment/tests/unit/routing.rs RouteTable::every_outcome visits every earlier domain rule and the rule matching now (or the default) while a sniff is still possible, and only the rule matching now when it is not, or when a domain was already sniffed; the first outcome that fails is the answer.
udp_flows_share_one_association_per_source protocols/tests/pipeline/tun.rs One association per source; the reply comes back with swapped addresses and ports; a second destination rides the same association and gets its own replies.
a_tcp_connection_becomes_a_stream protocols/tests/pipeline/tun.rs The stack answers the SYN; the dial happens after the request, carries it, and sniffs the Host; the reply returns as a segment.
the_first_packet_opens_the_association_and_every_packet_is_sent protocols/tests/unit/tun/udp.rs The first datagram opens with the right destination and source, arms RELAY_IDLE_TIMEOUT, and every datagram becomes a SendTo; a second far end opens nothing.
replies_go_back_as_packets_from_their_origin_and_domains_are_dropped protocols/tests/unit/tun/udp.rs Replies are staged as packets from their origin; domain-sourced replies are dropped.
the_association_finishes_when_the_outbound_fails_or_idles protocols/tests/unit/tun/udp.rs ConnectFailed and the idle deadline both finish.
passthrough_core_opens_on_the_first_bytes_and_relays_verbatim, passthrough_core_finishes_when_the_outbound_fails_or_idles, a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host, a_sniffing_passthrough_core_opens_on_the_sniff_deadline, a_sniffing_passthrough_core_with_a_domain_target_opens_at_once protocols/tests/unit/core/mod.rs The TCP core’s opening, relay, half-close, failure and sniffing rules.
timing_arms_handshake_once_then_idle_per_byte_event, timing_reports_handshake_and_sniff_expiry_to_the_core, sniff_prefix_finds_a_host_across_pushes_and_keeps_the_bytes, sniff_prefix_takes_no_more_than_its_budget protocols/tests/unit/core/mod.rs The shared pieces both TUN cores build on: Timing arms the handshake deadline once and the idle deadline on every relay byte event, pushes Effect::Finish and moves to Closing on idle expiry, and leaves handshake and sniff expiry to the core; SniffPrefix finds an HTTP Host split across two pushes while keeping every byte, and takes exactly SNIFF_LIMIT bytes of junk before reporting Exhausted.
a_tun_inbound_lowers_to_its_device, syntax_errors_are_refused, semantic_problems_are_left_to_the_supervisor app/tests/unit/lower.rs etemenanki-app’s lowering: the DeviceSpec and TunSpec it produces, the refusal of port and of a route with host bits, and an MTU below the floor left for validation.
each_protocol_is_served_only_on_its_kind_of_bind, a_tun_device_mtu_is_at_least_1280 supervisor/tests/unit/validate.rs TUN only on a TUN bind and nothing else on one; 1279 refused, 1280 accepted.
a_tun_device_change_opens_a_new_device_and_disrupts, a_tun_settings_change_on_the_same_device_swaps_and_disrupts supervisor/tests/unit/plan.rs The plan steps of a device change (MTU 1500 to 1400) and of a settings change (max_flows 1024 to 2048), each with one Disrupt step for inbound tun. The device is a DeviceSpec named tun-test with 198.18.0.1/16; nothing is opened.
a_routed_connect_is_answered_while_the_app_runs app/tests/integration/e2e_tun.rs A real interface: a connect to a routed address is answered by the stack, and stops being answered once the app process and its interface are gone.
a_tun_device_carries_tcp_and_udp_to_the_outbound ffi/tests/proxy.rs A socketpair device supplied as a descriptor: TCP and UDP reach the direct outbound and come back, the outbound’s sockets are protected through the platform, and the flows are listed under inbound tun with source 10.0.0.2 and can be closed.

The pipeline tests need no privileges. protocols/tests/pipeline/tun.rs uses a UnixDatagram::pair() as the descriptor: one end is passed to inbound.prepare(OwnedFd::from(device_end)) and the result to run, and each send or recv on the other end is exactly one IP packet, matching the one-packet-per-read contract of TunDevice. The inbound runs with mtu 1500, udp on, a 1 s udp_idle_timeout and max_flows 16. The tests build packets with etherparse::PacketBuilder (etherparse is an optional dependency of etemenanki-protocols that the tun feature turns on) and parse the stack’s answers with SlicedPacket::from_ip. start_with can turn IPv6 off and install an Ipv6Unreachable check.

A Capture connector stands in for the outbounds. For a TCP flow it returns one end of a tokio::io::duplex and hands the other to the test; for a UDP flow it returns a FakeLink whose sent packets and injected replies travel over unbounded test channels. Fake::stop mirrors the supervisor’s teardown: cancel the token, await the task, drop the wire, then await TunInbound::shutdown. The mobile library’s test drives a socketpair device the same way, through Proxy::start and adopt.

app/tests/integration/e2e_tun.rs runs the real binary with a tun inbound (address = ["10.77.0.1/24"], routes = ["10.77.1.0/24"]) and a blackhole outbound. Nothing can flow back in-process without a loop through the device, so the proof is the TCP handshake: the kernel routes a connect to 10.77.1.5:80 into the device, the stack answers the SYN, and connect succeeds until the process exits. The test first calls open itself on an unnamed device with no addresses and skips with SKIP: cannot create a tun device: <error> on PermissionDenied; any other error fails it. It then tries a connect with a 3 s timeout every 100 ms for up to 10 s, and after terminating the app expects one more attempt to fail.

Terminal window
cargo test -p etemenanki-protocols --features tun --lib tun::
cargo test -p etemenanki-protocols --features tun --test pipeline pipeline::tun
cargo test -p etemenanki-protocols --features tun --lib core::
cargo test -p etemenanki-app --lib lower::
cargo test -p etemenanki-supervisor tun
cargo test -p etemenanki-supervisor ipv6_is_unreachable
cargo test -p etemenanki-environment every_outcome
cargo test -p etemenanki-ffi --test proxy a_tun_device

See Testing for the test layout across the workspace.