The stack completes a TCP handshake before the outbound connection is
made, so an IPv6 connection that leaf cannot complete looks successful to
the application, which then sees a reset instead of falling back to IPv4.
With TUN_REJECT_IPV6=true (read on every TUN start) an IPv6 SYN is
answered with RST and IPv6 UDP is dropped, so applications use IPv4 at
once while IPv6 still cannot leak past the tunnel.
- Limits.reject_ipv6, plumbed into the TCP engine
- tests: IPv6 SYN reset when rejected, IPv4 still accepted; accepted by default
StatManager aggregates activity per host, so clients can see which hosts
are used, through which outbound, and which ones fail and need a rule.
The host is the requested domain, else a sniffed domain (TLS, HTTP, DNS),
else the destination IP. Recording happens only when HOST_STATS is true
(off by default), so servers skip the extra locks and allocations.
Per host (at most 2000 hosts; when full, the least recently seen tenth is
evicted in one pass):
- sessions, bytes of finished sessions, the outbound most recently chosen
- failed sessions (outbound connect/handshake failed, TCP and UDP), not
included in the session count, so hosts that only ever fail show up
- the most recent destination IPs and ports (up to 8 each)
Each session start (sequence number, time in ms, host, outbound) also goes
into a ring of the most recent 20000 events, so clients can correlate
hosts that are accessed together, e.g. the hosts behind one web page.
"handled ... dst=<ip>:<port>" log lines append " sniffed=<domain>" when
the route was picked for a sniffed domain, so UDP flows (e.g. QUIC) to an
IP can be matched to the host they are counted under.
- RuntimeManager::get_host_stats() / get_host_events_since(seq)
- leaf_get_host_stats(rt_id, ctx, cb): sessions, failed, bytes, outbound,
ips and ports as comma-separated strings
- leaf_reset_host_stats(rt_id)
- leaf_get_host_events(rt_id, since_seq, latest_seq, ctx, cb)
- tests: per-host counts, live + finished bytes, reset; event sequencing,
bound, incremental reads; IPs under the sniffed domain; ports; failed
sessions
StatManager now keeps cumulative (sent, recvd) bytes per outbound tag.
A finished session is added once, when its session end is logged; live
sessions are added at query time, so the totals stay exact without
touching the per-byte read/write path.
- RuntimeManager::get_outbound_traffic() returns (tag, sent, recvd)
- leaf_get_outbound_traffic(rt_id, ctx, cb) reports them over FFI,
taking the stat lock synchronously rather than building a tokio
runtime per call
- test: closed + live accounting, and a repeated session end
The queue to the TUN device dropped any packet past 512, TCP segments
included, and a dropped segment stalls its connection until the
retransmission timer fires. It is now two queues: TCP is only dropped
past a backstop (a quarter of the memory budget), UDP is bounded in
bytes (a sixteenth of it, at least 128 KiB) and drops whole datagrams,
oldest first. UDP goes out first, but no more than four packets in a
row while TCP waits.
The queue of datagrams from the TUN device is bounded in bytes too,
dropping the oldest. Config loses max_output_packets and max_udp_queue,
and the NETSTACK_OUTPUT_CHANNEL_SIZE and NETSTACK_UDP_UPLINK_CHANNEL_SIZE
options that fed them go.
An ACK that empties the unsent queue now stops the persist timer, which
otherwise kept the retransmission timer from running. A segment queued
under a larger MSS has no space left instead of a wrapped-around amount.
The TUN inbound now runs a userspace stack under proxy::tun::netstack:
IP parsing, fragment reassembly, UDP and a TCP engine written in Rust.
netstack-lwip and netstack-smoltcp are dropped, and the tun2socks
setting is ignored.
The netstack-lwip update generates its lwIP bindings at build time for the
exact target rather than shipping them checked in, so bindgen now parses
mingw's headers under `--target=x86_64-pc-windows-gnu`. That reaches
`stdlib.h`, and on mingw `stdlib.h` reaches `malloc.h`, which includes
`mm_malloc.h` -- a header the compiler is expected to supply rather than the
sysroot.
clang has one, in its resource directory, and the cross image carries four
copies of it. The libclang bindgen loads simply does not put that directory on
the include path for this target, so the build fails on a header that is
sitting right there:
/usr/x86_64-w64-mingw32/include/malloc.h:84:10:
fatal error: 'mm_malloc.h' file not found
`Cross.toml` links clang's copy into the sysroot clang is already searching --
it found `malloc.h` there -- which is enough, and the glob keeps an LLVM bump
in the image from breaking it again.
Only this target is affected: it is the only one whose headers reach
`mm_malloc.h`. The x86-64 and aarch64 musl targets were built clean to check.
Both `ci.yml` and `release.yml` run `cross` from the repository root, so
neither workflow needs a change.
Thirty-five commits since the pinned 4cc3162, and the reason to take them is
that most are corrections to the lwIP binding rather than features. Among
them: a use-after-free in `UdpSocket::split`, a data race and aliasing UB on
the output path, a UDP callback that shared context unsafely, `sys_now`
arithmetic widened to 64 bits so it no longer overflows on 32-bit targets,
pcbs no longer touched after lwIP has freed them or parked them in TIME_WAIT,
and a timer task that is now aborted when the stack is dropped instead of
outliving it.
The rest is capacity and backpressure work that shows up under connection
churn: pools sized for the connection counts each platform is expected to
reach, a shorter TCP_MSL to cut TIME_WAIT pressure, a smaller window on iOS to
cap per-connection buffering, and `poll_flush`/`poll_write` parking on
transient ERR_MEM rather than failing the connection.
The bindings are now generated at build time for the exact target rather than
checked in, so their layouts always match what is being compiled against.
That needs libclang, which leaf already requires: bindgen is an unconditional
build dependency of the crate.
`inbound-tun` is in the default feature set, so this is on the ordinary build
path rather than an opt-in one.
On Windows this was unconditional: any build with `inbound-tun` compiled in
set OUTBOUND_INTERFACE at startup, whether or not a TUN inbound was
configured. macOS and Linux ask `has_tun_listener() && tun_auto()` first, a
few lines above; Windows now asks the same.
The cost of setting it was every outbound socket that asks for the wildcard
bind getting pinned to the default interface instead, and such a socket
cannot reach a destination that interface does not serve. The QUIC outbound
is the only caller that passes UNSPECIFIED_BIND_ADDR -- the rest pass the
destination, and so take the loopback branch in `bind_socket` -- which is why
QUIC alone failed, and why it failed against a loopback server: quinn's first
Initial packet never left, with WSAEADDRNOTAVAIL, and the connection died at
the dial timeout eight seconds later.
All 30 quic-trojan e2e cases fail without this on Windows and pass with it.
Both failed on Windows, and neither was Windows' fault.
The SOCKS5 outbound's mock server read the greeting as two bytes. The
shortest greeting there is is three -- VER, NMETHODS, and one method -- so
every read after it was off by one, the request went unread, and a socket
dropped with unread bytes in it is reset rather than closed. The client was
then racing the reset for a reply it was already being sent, and won often
enough on Unix to look like a passing test. It now reads the greeting and the
request in full, which is both correct and what makes the close a close.
`an_absolute_path_is_left_alone` asserted that `/etc/leaf/cert.pem` comes back
unchanged. On Windows that path is not absolute -- it names the root of
whichever drive is current -- so `resolve_certificate` resolves it against the
asset directory, correctly, and the test was asking a question with a Unix
answer. It now uses an absolute path for the platform it runs on.
`cargo test -p leaf --features plugin --lib` is 107 of 107 on Windows.
A chain has to answer three questions about every actor -- which of its two
handlers runs, what address it is told to reach, and which actor the caller
should dial before any of it starts -- and it answered them in the middle of
doing the I/O. `next_connect_addr` served two of those questions at once with
subtly different rules on the stream and datagram sides, recomputed per actor
per connection; the datagram fold then made the same decisions again in five
branches with a lookahead. Nothing said that actor zero is the one nearest the
wire, or why only the last one is shown the client's stream.
The rules now live in `outbound/plan.rs` as a function from actors to stages:
one backward pass for what each suffix names, one forward fold for which
handler each actor runs. It touches no sockets, so the seven tests under it
are the first statement anywhere of what a chain is supposed to do -- that a
transport leaves the address to what is inside it, that every actor but the
last is told to reach the next hop, that a datagram stays a stream until the
actor that tunnels it. The handlers are left with the I/O and with naming the
actor in any error, which they never did.
Inbound had the same fold written four times -- two handlers and two functions
for the actors behind a multiplexed transport -- agreeing on the interesting
parts and differing in the rest: one panicked with `unimplemented!()` where
another returned, one timed out each actor and the others did not. One fold
now, and the case that used to panic ends the chain instead.
Behaviour is unchanged with two exceptions, both where the old code was
indefensible: a datagram handed to an actor that speaks only streams was
silently dropped and reported as that actor being handed nothing, and is now
an error naming it; and the datagram lookahead asked about the wrong suffix
for every actor after the first, which no configuration here reaches but which
was wrong on its own terms.
Verified against 178 end-to-end cases that put traffic through chains -- every
stack, every relay shape, quic and amux and ws among them -- plus leaf's own
suite.
A certificate and its key are configured the same way and were read two
different ways. `certificate` was recognised inline -- if it contains
"-----BEGIN", it is the PEM itself -- and `certificateKey` never was: it went
straight to the path branch, so an inline key became a filename made of PEM,
joined onto the asset directory. What the operator saw was "no private keys
found" about a key that was right there in the configuration.
It affected the quic and tls settings on both sides, all four with their own
copy of the same twelve lines. There is one resolver now, used for both halves
of every keypair, and three tests that say which of the three shapes -- inline,
absolute, relative -- goes where.
Found by an end-to-end matrix that configures every stack from one self-signed
certificate held in memory: with `rawCertificateKey` it worked, with
`certificateKey` no quic node would start.
Also: the quic inbound now reads a SEC1 key -- "BEGIN EC PRIVATE KEY", what
openssl hands out for an elliptic curve by default. The tls inbound has always
taken one. That path has no test here; the harness's key is PKCS#8, and the
asymmetry is plain enough between the two files.
A client that has finished sending says so by closing its write side and goes
on reading, and plenty of protocols end a request that way and no other. Over
a websocket transport that signal went nowhere: `poll_shutdown` returned
without sending anything, so the far end learned the request had ended only
when the connection itself went away -- when the downlink grace expires, ten
seconds later, by which time the reply has nowhere to go. The comment above it
said as much.
A Close frame is the obvious candidate and the wrong one. RFC 6455 makes it
the start of closing the whole connection, and tungstenite enforces that at
both ends: once a Close has been received the connection will not carry
another data frame, so the reply still on its way back is lost. Measured, not
assumed -- the server read the origin's answer and then failed to forward it.
An empty binary frame says the same thing and costs nothing. It is an ordinary
data frame carrying no bytes, so a peer that does not understand it hands
nothing to its application and carries on, which is exactly today's behaviour.
This transport's read side has always turned a frame with no bytes into an end
of stream, so between two leaf nodes it is precisely the missing signal. A
write of no bytes now returns early rather than sending one by accident.
Still behind WS_HALF_CLOSE, off by default, for the peer that would rather
error than ignore it. Booleans now also accept 1/yes/on: an option that is
silently ignored, as WS_HALF_CLOSE=1 was, is worse than one that is missing.
Every accepted inbound socket was given SO_LINGER = 0, so closing it sent a
reset. That discards whatever is still queued for the peer: a response whose
end is marked by the close itself -- HTTP/1.0, a body with no length, anything
read to EOF -- can be truncated, and a peer that has received every byte but
not yet read them can still see the transfer fail with a reset.
What it bought was the socket back at once, with no TIME_WAIT. But TIME_WAIT
falls on whoever closes first, and on the common paths that is the client:
leaf is the passive closer and has no TIME_WAIT to avoid. The reclaim is only
ever paid for on the paths where leaf closes first -- the idle timeouts and
the error teardowns -- and those are the paths where a reset is the right
answer anyway.
So it is now off by default and available as TCP_INBOUND_ABORT_ON_CLOSE, for
devices that cannot afford the sockets. Sessions are still bounded by the
existing uplink and downlink idle timeouts.
The entered span guard was held across the await of the connection
handler, so the span stayed entered on the thread while the task yielded
and unrelated tasks were attributed to it. The span variable was also
shadowed right after the guard was taken. Scope the guard to the debug
log and keep a single span.
Datagram::split() takes the inner datagram and then drops the wrapper,
which notified the cleanup task and retired the session counters right
when traffic was about to start. Only end the session on drop if the
datagram was never split; once split, the recv/send halves drive
retirement through move_to_recent. Add tests for both paths.