A plugin outbound can now give a url instead of a path. With the new
plugin-fetch feature, a start downloads what the cache is missing into
<cache>/<sha256>/<file> before any outbound is built, and points the
outbounds at it; a reload, and testing an outbound, resolve from the cache
only and refuse what they would have to download.
- https only, redirects included, and only together with a sha256 pin.
- Downloads go to a temporary file, are hashed as they arrive, and are
renamed into place only once the digest matches, under the url's own
name, with the platform's library suffix added when it has no
extension, which is what Windows needs to load it. A download past the
declared size, or past 64 MiB without one, is stopped.
- The cache directory comes from FetchOptions or PLUGIN_CACHE_DIR, with
no default: whether a directory is safe to load code from is the
embedding app's call.
- prefetch() reports QUEUED/CACHED for every plugin before any download,
then STARTED, PROGRESS (at most every 100 ms) and exactly one DONE or
FAILED each, on the calling thread; the callback can cancel. A download
that has not finished gets a PROGRESS heartbeat at least once a second,
before STARTED too, so that one stuck connecting or in the handshake
can be cancelled as well as one stuck mid-body.
conf gains a [Plugin] section that declares each plugin once (path, url,
sha256, size) and a `plugin` proxy protocol that refers to it by name,
with args= or args-b64= for arguments that contain commas. Proxy
parameters are now split at the first `=` only, which used to drop any
value that contained one.
leaf-ffi gains leaf_prefetch_plugins, so that an app can download the
plugins as soon as it has the config, and show progress, and the start
that follows finds everything in the cache. Events arrive as a
LeafFetchEvent whose first field is its size, on the calling thread and
never after the call returns. Adds ERR_PLUGIN_FETCH, ERR_CANCELLED and
ERR_UNSUPPORTED, and the plugin and plugin-fetch features. It is tested
by unit tests rather than end to end: the library is a Rust dylib, which
does not link in a Windows debug build (LNK1189).
Twenty-three fetch/ e2e cases download from a per-case https server
whose routes can announce a wrong length, omit it, fail, redirect, or
hold a body at a gate until the case opens it. Every case checks its
events against one statement of the progress contract, and every
failure, cancel and timeout case checks that the cache is left empty.
One checks that testing an outbound reads the cache, including a file
put there by hand, and never downloads.
The READMEs describe plugins in conf files and downloading them, and
plugin-test and CI run the new unit tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`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 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.