590 Commits
Author SHA1 Message Date
eric 9c13cf6a45 feat(tun): option to refuse IPv6 (TUN_REJECT_IPV6)
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
2026-12-03 19:27:21 +08:00
eric 3e126eb063 feat(stats): per-host stats and session events behind HOST_STATS
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
2026-12-03 19:27:21 +08:00
eric 263cff16b7 feat(stats): track traffic per outbound and expose it over FFI
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
2026-12-03 19:27:20 +08:00
eric d15623a91f fix(tun): size the netstack queues in bytes, and keep TCP out of the drops
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.
2026-11-27 21:09:58 +08:00
eric f965bc0ee1 fix(tun): stop the persist timer once drained, clamp segment space
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.
2026-11-27 13:41:43 +08:00
eric 16cdec05c3 feat(tun): replace lwip and smoltcp with a built-in Rust netstack
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.
2026-11-26 17:46:47 +08:00
eric 5e8d94759c build(cross): give bindgen clang's mm_malloc.h on the windows-gnu target
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.
2026-09-10 17:59:35 +08:00
eric ff6ffcd489 build(deps): update netstack-lwip to 4943435
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.
2026-09-10 16:06:12 +08:00
eric c4571a4758 fix(windows): bind outbound sockets to the default interface only for tun
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.
2026-09-10 16:04:58 +08:00
eric a7b54a1495 test(leaf): fix two unit tests that only ever held on Unix
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.
2026-09-10 16:04:58 +08:00
eric b83e44ec9f refactor(chain): work out what each actor does before running any of it
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.
2026-09-09 22:58:32 +08:00
eric 63dceed479 fix(config): read an inline private key as a key, not as a filename
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.
2026-09-09 22:07:36 +08:00
eric d2fcffbd76 feat(ws): let a websocket transport signal the end of a request
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.
2026-09-09 21:28:24 +08:00
eric 64d92432ed fix(net): close inbound connections gracefully by default
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.
2026-09-09 13:45:51 +08:00
eric dbc858733c style: rustfmt chain and quic inbound 2026-09-08 14:12:39 +08:00
eric f809b04782 fix(inbound): scope the tracing span guard in the TCP accept path
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.
2026-09-08 14:12:39 +08:00
eric 7ce1f83fe5 fix(stat): keep outbound UDP session alive across datagram split
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.
2026-09-08 14:12:39 +08:00
eric 1d20301570 Revert "feat(inbound): limit data transfer and concurrent connections per IP"
This reverts commit 05e872ac0a.
2026-06-18 13:28:41 +08:00
eric 05e872ac0a feat(inbound): limit data transfer and concurrent connections per IP 2026-06-17 23:28:05 +08:00
eric 7ea00627dc Increase OUTBOUND_DIAL_TIMEOUT default value from 4s to 8s 2026-06-14 13:35:19 +08:00
eric ba6cbd4134 Optimize QUIC timeout and keep-alive configuration for client and server 2026-06-14 13:11:55 +08:00
eric b7184f87be quic: avoid blocking stream opens on pooled connections 2026-06-12 15:59:56 +08:00
eric f967434f9f Add project logo 2026-05-28 15:44:46 +08:00
eric 87f50a0270 Add default method for shadowsocks inbound 2026-05-22 21:25:26 +08:00
eric 7a9101b5f5 Fix QUIC inbound 2026-04-27 20:37:09 +08:00
eric a8971524d6 Add MPTP usage 2026-03-19 07:17:33 +08:00
eric d5ed615f7f fix(mptp): make inbound CID session registration atomic under single write lock 2026-03-19 07:17:17 +08:00
eric 291af8b9f0 Refactor DNS client 2026-03-15 17:53:17 +08:00
eric 26d17f9da7 Add a DNS selector 2026-03-15 17:13:09 +08:00
eric eea1f5a465 Skip invalid DNS server 2026-03-15 16:32:24 +08:00
eric a5e4d2adc9 Use aws-lc-rs 2026-03-14 10:31:18 +08:00
eric f576d34b95 Fix build and test 2026-03-14 10:05:51 +08:00
eric 019bdeaeb0 Improve openssl backend ECH handling 2026-03-14 08:18:21 +08:00
eric 309f9e9c6d Improve ring backend ECH handling 2026-03-14 07:22:35 +08:00
eric b14e2e368d Support DoH 2026-03-14 06:43:26 +08:00
eric a3459cc0d1 Support ECH config DNS lookup 2026-03-13 21:39:37 +08:00
eric 12f77224c6 Support setting environment variables in JSON config 2026-03-13 16:59:51 +08:00
eric 822889c78a Support ECH 2026-03-13 16:58:55 +08:00
eric 4dd6f89493 Fix Apple builds 2026-03-03 16:46:51 +08:00
eric b7453f50ff Fix tests 2026-03-02 08:43:14 +08:00
eric 7a567e833a Save recent connections in stat manager 2026-03-01 12:39:30 +08:00
eric a911e542f6 Resolve direct domains with direct DNS servers 2026-03-01 10:19:08 +08:00
eric d82a54e34e Add docs for MPTP 2026-03-01 08:06:52 +08:00
eric 7d5f1e5544 Add tests for MPTP 2026-03-01 08:00:12 +08:00
eric 3a150d5da3 Fix Android build 2026-03-01 07:50:58 +08:00
eric a79358236e Improve conf section name compatibility 2026-02-28 21:48:07 +08:00
eric 32895f4f8b Fix domain sniffing/override 2026-02-28 21:20:43 +08:00
eric f46cf41410 Improve logging 2026-02-28 20:38:00 +08:00
eric fa8999181e Fix MPTP UDP inbound 2026-02-28 20:21:40 +08:00
eric 50d0be1806 Refactor 2026-02-28 20:21:35 +08:00