Every failover health check connected to www.google.com:443 and asked
1.1.1.1:53 about www.google.com, through every actor, direct ones
included, on a timer. That is a fixed pattern an observer can match,
direct DNS in the clear, and where Google is blocked a direct actor was
always marked down. The TLS check also sent "GET / HTTP/1.1" with no Host
header, which no browser does.
healthCheckTcpDestination (host:port) and healthCheckUdpDestination
(ip:port), health-check-tcp-destination and health-check-udp-destination
in .conf, now set them; the defaults are unchanged. The DNS check asks
for the TCP destination's name, or the root zone when that is an
address, and the HTTP request carries a Host header, with the port when
it is not 443. An IPv6 address must be in brackets. A malformed value
fails at startup.
A test runs real checks through a direct actor against local listeners.
The failover outbound has always supported a last resort, used when the
last health check found every actor down, but neither config format
passed it on: JSON had no key for it and .conf parsed last-resort and
dropped it. The previous commit took that for a missing feature and only
warned. JSON now takes lastResort, and .conf's last-resort is passed on.
The outbound manager also took a last-resort tag it had not loaded yet
for none at all. It now waits for that tag as it does for actors. A tag
that names no outbound is a configuration error, rather than something
to wait for until the group quietly fails to load. And any outbound
still not loaded at the end -- one it uses is missing, or the build
leaves its protocol out -- is now named in a warning instead of
vanishing.
The docs say what a direct last resort means: everything goes direct
whenever the proxy is found down.
dns-interface in [General] and interface= on a [Proxy] line were parsed
and then dropped, so traffic meant for a chosen interface left through
the default route while the config said otherwise. Both are now errors
that point to OUTBOUND_INTERFACE, which binds every socket leaf opens.
last-resort on a failover group was dropped the same way. Ignoring it
fails closed -- with every actor down, connections fail rather than go
elsewhere -- so it stays accepted, with a warning that says so.
The .conf parser split every key=value at each =, and dropped the
parameter when that gave more than two parts, so a base64 password or
key vanished without a word. The same applied to [Env], [General] and
[Host] lines. A comma could not be written at all, and a positional value
containing = was skipped while still counting as a position, which
shifted the ones after it.
A key=value is now split at its first =. In [Proxy] and [Proxy Group]
lines a value in double quotes is taken whole, commas included, and
positional values are counted among themselves. A quote opens a value
only at its start or right after key=, so one inside a value, as in
password=ab"cd, stays an ordinary character, and a quote that never
closes quotes nothing rather than taking the rest of the line.
Every two-word JSON key is camelCase with a snake_case alias, except
amux's max_recv_bytes and max_lifetime, which took snake_case only.
maxRecvBytes and maxLifetime were ignored without a word, so a limit
meant to retire connections never applied. Both spellings now work.
Both outbounds accepted certificateKey and rawCertificateKey and never
used them: neither presents a client certificate. Someone who set one
believed the server could tell this client apart, and it could not.
Setting either is now a configuration error naming the outbound. The
dead branches that chose between identical no-client-auth builders are
gone.
A JSON vmess outbound with no security, or one leaf does not implement,
was accepted, and every connection through it then failed with
"unsupported cipher". The .conf format already defaulted to
chacha20-ietf-poly1305; JSON now does the same, and any other value is a
configuration error at startup. The value is accepted in any case and
stored lowercase, which is the only spelling the cipher table knows.
A socks inbound with a username checked it on SOCKS5 TCP and nowhere
else. SOCKS4 has no password, and was accepted anyway, so any client
could skip the check by speaking the older protocol. The UDP relay
answered datagrams from any address. And a username with no password
panicked on the right username, which a release build turns into an
abort.
With a username set, SOCKS4 is now refused, and the relay drops datagrams
from any IP address without an open, authenticated UDP ASSOCIATE
connection, as RFC 1928 asks; the association ends with that connection.
It is open before the reply goes out, since a client may send its first
datagram the moment it reads the reply. A username without a password
means an empty password, and a password without a username is a
configuration error instead of silently turning authentication off.
The UDP check is by IP address, since a client's sending port is not
known in advance; the docs say what that leaves open.
Every condition's values are alternatives except geoip's: each country
code was its own condition, ANDed with the rest, so a rule naming two
countries matched nothing.
A rule source that could not be loaded was worse. A missing geo.mmdb, or an
external site list that failed to load or held nothing for its tag, simply
left its condition out, and the rest of the rule matched on its own: a rule
for one country's TCP traffic took all TCP traffic.
A country whose database cannot be opened, and an external list that
cannot be loaded, now match nothing. When that leaves the rule with no
condition of that kind, the whole rule is dropped with a warning, so its
traffic falls through to the rules below it. The tests build a small
MaxMind database of their own; on the old router they fail.
The audit asked for shutdown to be checked with two Go plugins loaded and
connections that close during the handshake or with a read or write
pending. plugin-cleanup/ does that over chain[go-tls, ws, go-trojan], and
over the Rust TLS plugin with leaf's own Trojan, so that a fault the host
shares can be told from one in the Go plugins.
The host now logs, at trace, each engine instance it creates and each one
whose destroy_instance has returned; the cases require the two to balance
and the node to shut down. The Go SDK's destroy waits for the
connection's goroutines, so one that never finished would show up here.
Both chains failed the handshake case before the previous commit: no
instance was destroyed while the server stayed silent.
The dial to an outbound was bounded by OUTBOUND_DIAL_TIMEOUT, and nothing
after it was. A server that accepted and then never answered -- a TLS
ClientHello with no ServerHello, a WebSocket upgrade with no reply -- held
the session, and every plugin instance in its chain, for as long as the
server stayed up. The client could not end it: leaf does not read from
the client until the handshake is done, so it never saw the client leave.
OUTBOUND_HANDSHAKE_TIMEOUT, thirty seconds by default and 0 for none, now
bounds the protocol handshake of stream and datagram outbounds.
A failover is the exception. It already gives each actor its own
failTimeout, and one limit around all of them would cut it off before
its later actors and its last resort. The dispatcher leaves it unbounded
as a whole, and the failover puts the limit around its last resort,
which had none. A select passes on whether its chosen actor is one.
leaf's SOCKS5 outbound had the same fault as the C and Zig plugins: with
credentials configured it offered "no authentication" as well, and
carried on if the server picked it.
It used async-socks5, which always offers both, so the handshake is now
leaf's own and the dependency is gone. With credentials set,
username/password is the only method offered, and a server that picks
anything else is refused before the request goes out. A password set
without a username, which would quietly turn authentication off, is a
configuration error, as it is on the inbound.
That also fixes three things in its UDP path: a reply that could not be
parsed ended the association instead of being dropped; a relay given as
0.0.0.0 sent datagrams to this host rather than to the server; and the
UDP ASSOCIATE request named the server as DST.ADDR, where RFC 1928 wants
the client's sending address or zeros, so a server that enforced it
dropped every datagram. It now sends zeros.
The C and Zig SOCKS5 plugins offered "no authentication" alongside
username/password when credentials were configured, and carried on if
the server picked it. The server, or anyone in the path of an
unprotected connection, could skip the check the deployer asked for.
With credentials set, the greeting now offers username/password alone,
and a server that picks anything else is a fatal handshake error before
the request goes out. Each suite adds a server that skips
authentication; both fail on the old code.
fakeDnsInclude and fakeDnsExclude (always-fake-ip and always-real-ip in
.conf) matched an entry anywhere in the name. One written for example.com
also covered notexample.com and example.com.evil.net, so a name the
deployer never listed could be given a fake address, or a real lookup,
on the strength of a few letters it contained.
An entry now covers that domain and the names under it, label by label
and ignoring case; * still covers everything. A keyword entry that relied
on the old behaviour now matches only a domain of that name, which the
docs say.
docs/configuration.md lists every JSON option, environment variable and
command-line flag: what it does, what it accepts, and what happens when it
is left out, with the .conf keys mapped onto them. Options that decide
whether traffic stays behind the proxy are marked.
docs/security.md explains those choices together: names looked up outside
the proxy, where unmatched traffic goes, direct fallback, IPv6 under TUN,
certificate checks, logs, and how the protocols fare on filtered networks,
without presenting any as safe from a censor. It ends with a configuration
to start from, which has been run.
examples/README.md says what each example is for and what to change before
deploying one. The README links all three and no longer names the TUN
stacks that were replaced.
At info level the dispatcher logged each session's source, destination,
sniffed host and process name, and the Go Trojan plugin logged the
destination of every engine it created. Anyone who could read the logs
could see where users connected, however the proxy link was protected.
Info now records the protocol, inbound, outbound and connect time. The full
line, and the Trojan plugin's, are logged at debug level, which has to be
asked for.
On an unreliable transport, a decode_packet failure ended the receive
side of the session, which leaf then removed. Every reference plugin
reports a reply it rejects -- failed authentication, an address it cannot
parse -- with PLUGIN_FAILURE, and a reply that fails authentication needs
no key. So one forged packet sent to the client's socket discarded every
reply that arrived before the client next sent something.
A frame the engine refuses with PLUGIN_FAILURE on an unreliable
transport is now dropped like any other damaged packet. Any other status
-- an argument the engine cannot use, an unsupported call, an output it
still cannot fit -- says the engine itself cannot go on, and still ends
the session. So does any failure on a reliable transport, since the
stream cannot be resynchronised, and an engine that breaks the ABI's
contract. The ABI documents the exception.
The e2e case now keeps one association, sends a good reply straight behind
each bad one, and adds a forged reply. It fails on the old host.
The address parser fix is about a panic that only a release build turns
into an abort, since a debug plugin's guard catches it. A unit test cannot
show that the process lives, so this case loads the Shadowsocks plugin
built with the release profile, whatever profile the run uses.
A stand-in server speaking Shadowsocks AEAD UDP with leaf's own codec
echoes datagrams, and answers a request for a malformed reply with an
authenticated one whose address is cut short: a lone domain type byte, and
a domain one byte short of its port. The client must refuse both and keep
carrying traffic. On the old parser the case process dies with SIGABRT at
either reply.
Fixtures can now name a cargo profile of their own.
The SOCKS UDP inbound handed the parser its whole receive buffer, zeros
past the packet included, so a short packet parsed as a longer address and
the payload length underflowed. Four bytes from any peer that could reach
the socket aborted a release build. A payload larger than the caller's
buffer hit an assert.
Both the SOCKS and NF inbounds now parse the received bytes only, check
the length of what follows, and drop a datagram that does not fit with a
warning.
The PortLast domain branch read the length byte after checking only that
the buffer was not empty, and its length check left out the length byte
itself. A one-byte address, or one a byte short of its port, read past the
end. Release builds abort on panic, so an authenticated Shadowsocks
datagram with such an address took the whole process down; the plugin's
UDP decoder and the built-in Shadowsocks inbound and outbound all parse
datagrams this way.
The branch now steps over the type and length bytes as the PortFirst one
does. New tests parse every address kind in both layouts and refuse every
truncation of each.
An upstream server was killed from Drop, which never runs when the case
process does not unwind: a plugin that brings the Go runtime down, or the
runner killing a case that overran. One lost run left dozens of sing-box and
mihomo processes behind.
The server now runs under a small shell that holds a copy of its stdin and
kills it at end of file. The case holds the write end, so however the case
ends, the operating system closes it and the server goes with it. Drop takes
the same path.
A new interop lane puts a real leaf with each plugin in front of the servers
people deploy, built from source at pinned revisions: anytls-go, sing-box
stable and its testing branch, mihomo, and the original shadow-tls. Every
pair runs the stream behaviours, plus the server's padding scheme checked on
the wire, fingerprints, and the connections that must fail: wrong password,
hijacked to the real site, TLS 1.2 site in strict mode.
AnyTLS skips half-close-tail, which its protocol cannot carry. ShadowTLS
marks it a known defect: the host shuts the socket's write side while an
engine is still handshaking.
`make interop` runs the lane, `make e2e` leaves it out, and CI runs it in a
job of its own with the built servers cached. The harness no longer hands
out a port twice in one process, and builds upstream Rust servers with their
own toolchain, outside the workspace.
Two protocols leaf does not implement, each a thin Go adapter over the
library existing implementations use: anytls/sing-anytls for AnyTLS, and
sing-shadowtls with metacubex/utls for ShadowTLS, at sing-box v1.14.4's pins.
AnyTLS keeps TLS inside the plugin, since its padding scheme is defined over
TLS records, and shares one client per outbound so a server's own scheme
carries to the next connection. ShadowTLS is a transport under a chain,
usually Shadowsocks.
The ShadowTLS adapter signs the session ID itself rather than through uTLS's
hook: with a browser fingerprint that hook sends Go's own ClientHello, and
breaks on a HelloRetryRequest.
Each has unit tests against the library's server, READMEs, and example
configs. Both binaries are GPL-3.0, from their libraries.
host_ctx is opaque, and leaf puts an instance number in it. The SDK held it
as a Go pointer, so the first stack copy that found a value like 1 stopped
the process with "invalid pointer found on stack". It is now an integer on
the Go side and a pointer only in C.
ConnEngine refused application input behind a busy write loop without
reporting BLOCKED. The host read that as an engine waiting for its output to
be taken, buffered decoded bytes to make room, and failed saturated
two-way transfers as stalled, about one run in ten. It now reports BLOCKED
once the handshake is done and the input buffer is full.
On the application's half close ConnEngine closed the wrapped conn whole,
dropping the reply still on its way. It now calls CloseWrite when the conn
has one and keeps reading.
enginetest.Driver drives an engine the way the host does, for a plugin's own
tests; SharedLogger routes a per-outbound library logger into leaf's log.
`make e2e` runs the end-to-end suite with `--strict`, minus the soak lane;
`make soak` is that lane plus the slow cost meters. `make plugin-test` covers
what an end-to-end run cannot reach -- the host's own loader and wrapper
tests, the ABI parity test, and each plugin's unit tests, one language at a
time -- and `make plugin-test-san` builds the C plugin's tests under address
and undefined-behaviour sanitizers, kept separate because not every toolchain
ships the runtimes.
CI grows a plugin job on Linux and macOS that runs the suite and
`make plugin-test`, and checks that `leaf-cli` still builds with plugin
support, since nothing else in the matrix compiles that feature. The same lane
exists for Windows but is started by hand: the suite has been through Windows
green on ARM64, and this runner is x86-64. A sanitizer lane runs the hostile
cases with the runtime exported so a plugin loads against it, and uploads the
artifact directory when a case fails. The soak workflow is the one that is
nightly: it runs the long lane out of hours with a longer timeout scale and
more meter repetitions, so its numbers are worth comparing between nights.
`.gitignore` learns the artifacts the plugin builds leave in the tree.
`leaf-e2e` starts real leaf instances and drives them from the outside over
SOCKS5, so a case covers the path a deployment takes -- config parsing, plugin
loading, routing, the dispatcher, the C ABI data plane -- and nothing reaches
into leaf to build a handler by hand. Cases are values rather than `#[test]`
functions, so the suite is a matrix of implementation, protocol, transport and
behaviour instead of a wall of copies, and each runs in its own process, free
to crash, hang, or set load-time environment.
The lanes:
- `differential` runs a behaviour natively and again with a plugin substituted
for one stage, and requires the two to agree. The server is stock leaf, so
these are interoperability tests. `protocols`, `halfclose` and `teardown`
extend that across every stack, relay and selector, the end of a request on
each transport, and shutdown.
- `abi`, `loader` and `coexist` check what the host accepts, refuses, and can
load at once, through a real `dlopen`.
- `hostile` and `datagram` drive conformance plugins -- one in Rust, one in Go
-- that misbehave on request, exercising the host's bounds checks, clamps,
buffer growth and `decode_packet` handling.
- `stress` and the meters measure both sides back to back and assert the ratio,
since absolute numbers from a shared runner say little; throughput, latency,
setup cost and cpu cost land in `meters.json` beside the case logs. What the
process is holding is asserted directly instead, against the case's own
allocator, because what matters there is that it stopped growing.
- `blackbox` runs the shipped binary: on a config file, and on a plugin
library through `--verify-plugin`, whose report has to agree with what the
loader itself would do.
Plugins are built by the harness, and a case whose toolchain is missing is
reported as ignored with the reason; `--strict`, which CI passes, makes that a
failure, so the suite cannot go green by running nothing. The suite runs on
Windows too, where a pause is never shorter than 16ms and cases that dribble
bytes bound their pauses instead.
The README gains a Plugins section: what a plugin is, the six that ship with
the tree, how one is configured as an outbound, why `path` must have a
directory part, why nothing is ever scanned for, why leaf refuses a library
anyone can rewrite, and why the optional `sha256` is worth setting. It says
plainly what none of that buys -- a plugin runs with leaf's privileges, so the
checks establish which file was loaded, not that it is friendly -- and how to
vet one with `--verify-plugin` first. It also covers building a leaf that can
load plugins at all, which neither the releases nor CI produce: the Linux
releases are static against musl and have no dynamic loader to call.
examples/ carries configs that run. The shadowsocks one connects through the
Rust plugin; the TLS ones chain a transport plugin under Trojan across the
Rust and Go implementations, with Windows variants where the paths differ,
and both READMEs give the server side needed to try them.
The ABI's claim is that a plugin needs a C compiler and nothing else. These
two are the evidence: the same SOCKS5 stream engine written twice, once in
plain C11 against leaf_plugin_abi.h and once in Zig importing that same
header, with no SDK, no runtime and no dependency beyond libc between them.
Both are state machines over the greeting, the method reply, the request and
the reply, so neither ever blocks or holds a thread. Each carries its own
tests -- socks5_test.c runs the engine against truncated and malformed
replies, and the Zig build runs its tests through `zig build test`.
Writing a plugin in Go means writing the vtables and const-pointer shims cgo
cannot express, handle allocation, panic recovery, the two-pass
get_last_error protocol and address encoding -- once per plugin, by hand.
leaf-abi-go holds all of it once, so a plugin is a package that registers
engines and implements them over byte slices: tls-cabi-go is 143 lines,
trojan-cabi-go 321.
ConnEngine is the other half. crypto/tls insists on a blocking net.Conn,
which the ABI forbids an engine call from being, so it runs the
implementation on goroutines over an in-memory pipe and reports BLOCKED with
a wake while those are what it waits on. A codec needing none of that
implements StreamEngine directly, as trojan does.
The SDK revokes its host handle once Destroy returns, so a goroutine
outliving its engine drops a log line rather than calling into memory the
host has reclaimed, and it masks BLOCKED off when the host offered no wake
callback. Register runs from Go's init and calls out to C; it cannot go the
other way, since entering Go binds a thread to the Go runtime for good and
the thread that loads a plugin is the host's.
The descriptor declares that these plugins embed a language runtime, so the
host never unmaps them.
Two reference plugins on the C ABI, and the first users of the contract.
shadowsocks-cabi-rs is the sample the in-process API used to carry, rewritten
as a stream engine: AEAD ciphers, the SOCKS address codec, and the request
header written when the engine is created rather than on the first push, so a
connection that sends nothing still reaches the far end. The wire header stays
out of the address buffer it is derived from.
tls-cabi-rs wraps rustls as a stream engine, and depends on nothing from leaf,
so the cdylib carries no second copy of the proxy engine.
Both catch a panic at the boundary and report it as an error. A panic that
crosses the ABI is undefined behaviour, and a plugin that faults its host is
worse than one that fails.
The old API handed dynamic libraries Rust trait objects, tying every plugin to
leaf's exact compiler and crate versions and ruling out other languages. It is
removed, along with its shadowsocks sample, which returns on the new ABI in a
later commit.
The host loads plugins over leaf-plugin-abi instead. It validates the
descriptor, dials the endpoint, and drives the engines as sans-io codecs over
its own transport, exposing them as ordinary outbound handlers. Datagram
engines are either unreliable, with a UDP socket of their own, or reliable,
framed over the stream transport. Plugin failures carry the plugin's last error
string, and plugin logs join the session's tracing span.
Everything crossing the boundary is treated as untrusted: counts are checked
against the buffers they describe, reported strings are bounded and escaped,
engines get an opaque id rather than a pointer for host_ctx, and an engine that
takes no input is backpressure rather than failure. A poll does a bounded
amount of work, and a datagram the receiver cannot take is dropped instead of
the session.
An outbound names its path, host and port, and may pin the sha256 of the
library it loads -- the only check on this path that still holds against
someone who can write the file.
`leaf --verify-plugin <path>` runs the same checks without a config file and
prints what the plugin declares: its ABI version, its engines, whether the
outbound must carry host and port, and the digest to pin it to. A build can
then be vetted before it is in the path of any traffic.
Plugins are dynamic libraries, and the boundary between them and leaf has
to be something both sides can name without agreeing on a compiler. This
crate is that boundary and nothing else: dependency-free, no_std, every
repr(C) type and constant in one place, with include/leaf_plugin_abi.h as
the single C declaration for plugins that are not written in Rust.
A plugin exports a descriptor naming its ABI version, its struct sizes,
optional stream and datagram engines, and whether it embeds a language
runtime. abi_major must match exactly; abi_minor is informational and
never gates loading. Each struct freezes a REQUIRED_SIZE prefix for its
major version, and peers validate against that rather than their own
sizeof, so an old plugin runs on a newer host and the reverse.
The contract is written next to the declarations, because the parts that
matter are the ones a signature cannot state: what each object's lifetime
is, that instances move between threads and calls never overlap, that no
call may block -- the readiness callback is what makes that workable --
and that decode_packet reports how much input it consumed, which is the
only way a codec can be driven over a transport with no message
boundaries.
A parity test compiles a C probe and compares sizeof, offsetof and every
constant against the Rust definitions, so the two declarations cannot
drift unnoticed.
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.