Listeners and the serve loop
Source files: 77 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/guard.rsEtemenanki/supervisor/src/carrier.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/system/mod.rsEtemenanki/supervisor/src/system/listener.rsEtemenanki/supervisor/src/system/handoff.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/lib.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/src/entity/usage.rsEtemenanki/supervisor/src/entity/id.rsEtemenanki/supervisor/src/topology/flow.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/build/apply.rsEtemenanki/supervisor/src/build/users.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/concepts/src/runtime.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/sniff/mod.rsEtemenanki/protocols/src/transports/accept.rsEtemenanki/protocols/src/transports/proxy_protocol.rsEtemenanki/protocols/src/transports/stream.rsEtemenanki/protocols/src/transports/ws/endpoint.rsEtemenanki/protocols/src/transports/tls/config.rsEtemenanki/protocols/src/error.rsEtemenanki/protocols/src/socks/server.rsEtemenanki/protocols/src/http/core.rsEtemenanki/protocols/src/http/protocol.rsEtemenanki/protocols/src/trojan/core.rsEtemenanki/protocols/src/vless/core.rsEtemenanki/protocols/src/vmess/core.rsEtemenanki/protocols/src/vmess/accounts.rsEtemenanki/protocols/src/ss_legacy/core.rsEtemenanki/protocols/src/ss_2022/core.rsEtemenanki/protocols/src/ss_2022/crypto.rsEtemenanki/protocols/src/ss_aead.rsEtemenanki/protocols/src/anytls/core.rsEtemenanki/protocols/src/sss/server.rsEtemenanki/protocols/src/sss/core.rsEtemenanki/protocols/src/transports/reality.rsEtemenanki/protocols/src/transports/camouflage.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/protocols/src/hysteria/server/config.rsEtemenanki/protocols/src/hysteria/server/endpoint.rsEtemenanki/protocols/src/hysteria/obfs.rsEtemenanki/protocols/src/tun/inbound.rsEtemenanki/protocols/src/tun/device.rsEtemenanki/protocols/src/tun/config.rsEtemenanki/protocols/src/tun/udp.rsEtemenanki/app/src/main.rsEtemenanki/app/src/instance.rsEtemenanki/supervisor/tests/unit/serve.rsEtemenanki/supervisor/tests/unit/supervisor.rsEtemenanki/supervisor/tests/unit/guard.rsEtemenanki/supervisor/tests/unit/session.rsEtemenanki/supervisor/tests/unit/plan.rsEtemenanki/supervisor/tests/unit/validate.rsEtemenanki/supervisor/tests/hot_swap.rsEtemenanki/supervisor/tests/tracking.rsEtemenanki/supervisor/tests/guard.rsEtemenanki/supervisor/tests/handoff.rsEtemenanki/supervisor/tests/anytls.rsEtemenanki/supervisor/tests/sss.rsEtemenanki/protocols/tests/pipeline/hysteria.rsEtemenanki/protocols/tests/unit/core/mod.rsEtemenanki/protocols/tests/unit/trojan/core.rsEtemenanki/app/tests/integration/e2e_unix.rsEtemenanki/app/tests/integration/e2e_hysteria_inbound.rsEtemenanki/app/tests/integration/e2e_tun.rsEtemenanki/app/tests/integration/e2e_route_context.rskatana/src/manager/node.rs
supervisor/src/system/listener.rs and supervisor/src/serve.rs are where an inbound’s spec becomes a bound socket and then running connections. A listener is bound while an apply is being prepared, so a port or device that cannot be bound refuses the whole spec before anything changes, and it starts serving only when the apply commits. It lives for as long as its BindSpec stays in the spec: a changed inbound on an unchanged bind gets a new handler on the same socket. A stream inbound on a TCP bind may have a second listener, a handoff socket: a Unix socket on which a relay running on the same host hands over TCP connections it accepted, each then served as if the TCP listener had accepted it. Every accepted connection is admitted against its inbound’s two semaphores, which the TCP listener and the handoff socket share, and registered as a session before its transport handshake starts, and is then driven through its protocol core by a small watchdog that bounds the handshake. How each handshake ends is reported to the supervisor’s guard, which can ban a client IP that keeps failing to authenticate and close a gRPC connection whose streams keep failing. A connection’s client is its peer, or the client a PROXY protocol header (for a handed-over connection, the header sent beside it) or, on a WebSocket inbound, a trusted reverse proxy’s upgrade header names. Hysteria 2 and TUN listeners own a UDP socket or a device outright and hand the per-connection work to the protocols crate.
This page is for contributors who add an inbound protocol, change how connections are admitted, or touch anything that runs under a listener’s or a session’s token. Which listeners an apply binds, swaps or stops is decided on Planning and applying a change. How a session is bound to its user, revoked, closed and listed is on Users, principals and sessions. What the connector does with each flow is on The plane: routing each flow, and what a session’s byte counter feeds is on Per-user usage accounting.
Responsibilities
Section titled “Responsibilities”| Concern | Where | Notes |
|---|---|---|
| Bind in prepare | system/listener.rs → bind, Pending::pair |
Opens a TCP or UDP socket, a Unix or handoff socket under a staging name beside its path, or a TUN device, then builds what serving needs. Nothing is served yet, and nothing at a Unix path is touched. |
| Serve in commit | system/listener.rs → Listener::start |
Moves a Unix or handoff socket over its path, then spawns the task that serves a pending pair. It cannot fail. |
| Listener identity | topology/inbound/mod.rs → BindSpec |
An unchanged bind keeps its socket across applies. Each of an inbound’s binds, its own and its handoff socket, is a listener of its own. |
| Admission caps | serve.rs → InboundCaps; supervisor.rs → caps_for |
One set per stream inbound, shared by its listeners: a listener an apply adds beside a kept one counts against the kept one’s caps. |
| Handler swap | Listener::prepare_swap, Listener::swap |
Stream listeners: the next socket accepted gets the new handler. A Hysteria 2 listener applies it inside its running endpoint, and a TUN listener restarts its runtime on it (see Handler swaps). |
| User tables | Listener::user_target, UserTarget::prepare, Listener::store_users; build/inbound.rs → UserTable |
A user change stores a new table into the running handler; the handler is not rebuilt. |
| Accepting and admission | serve.rs → run_stream_inbound |
The inbound’s two semaphores, taken without waiting. |
| Sessions at accept | run_stream_inbound → Sessions::open |
Every accepted socket is a session before its transport handshake starts. |
| PROXY header | serve.rs → Connection::serve_socket |
On an inbound with proxy_protocol, a TCP connection’s client is the one a PROXY protocol v2 header names, when one is sent. |
| Handed-over connections | system/handoff.rs → receive; serve.rs → Connection::serve_socket |
On a handoff socket each connection is a relay’s control connection, carrying one TCP socket and a PROXY protocol v2 header naming its client. The socket is checked, the relay is answered with one byte, and the socket is served through the same path as an accepted TCP connection. |
| Ban check | serve.rs → Connection::serve_tcp; guard.rs → Guard::is_banned |
A TCP connection from a banned IP, accepted or handed over, is dropped before its transport handshake. |
| Transport fan-out | serve.rs → Connection::serve_tcp |
InboundTransport::accept yields one byte stream per socket, or one per HTTP/2 stream for gRPC, and returns a Disposition. |
| REALITY camouflage | serve.rs → Connection::serve_tcp |
A REALITY socket that is not a client of ours comes back as Disposition::Camouflage, and serve_tcp relays it to the cover site without its handshake permit and without telling the guard. |
| Real-IP header | serve.rs → real_ip_source |
On a WebSocket inbound with real_ip, the client a trusted proxy names in an upgrade header is the stream’s client, held to the same bans. |
| Protocol dispatch | serve.rs → serve_connection |
The SOCKS driver, a ProxyServerRuntime over the protocol’s core, or for sss the boxed serve_sss: its pre-authentication gate, then a runtime. A VLESS Vision stream is wrapped in the Vision adapter before it gets there. |
| Handshake watchdog | serve.rs → drive |
HANDSHAKE_TIMEOUT per runtime step until the core is established. |
| Authentication guard | guard.rs → Guard, Report; carrier.rs → Carrier |
Counts refused credentials per client IP (an IPv6 client by its /64) and per gRPC connection; bans the IP or closes the connection at the policy’s limit. |
| Carrier hint | carrier.rs → Carrier; guard.rs → Report::carrier_hint |
The next VMess stream of a gRPC connection tries the user the connection’s last authenticated stream matched. |
| VMess hot tier | serve.rs → refresh_hot_tiers |
Once a second, a stream listener refreshes its VMess validator’s hot tier when the validator says it is due. |
| Hysteria 2 | serve.rs → run_hysteria_inbound |
One session per QUIC connection; the endpoint is changed in place. |
| TUN | serve.rs → run_tun_inbound |
One runtime per device at a time, restarted on a swap; flows have no session; IPv6 connections no egress could reach are refused. |
| Stopping | Listener::stop |
Stops accepting. Stream and Hysteria 2 connections run on. |
This code does not parse protocols (the cores in etemenanki-protocols do), route or dial (the AppConnector it hands each connection does), or decide which listeners to bind, swap or stop (the plan does). The one session it ends on its own is a gRPC connection the guard closes (see Tokens and tasks for what else does). Its only accounting is feeding each session’s Wire counter.
Every front end reaches it the same way, by applying a spec: etemenanki-app runs one supervisor for its config, and katana runs one per node. The serving code itself is not public. serve, guard and carrier are pub(crate) modules in supervisor/src/lib.rs, system is public but its modules, blocking, listener and, on Unix only, handoff, are pub(crate), and build::inbound is pub(crate). A front end sees the types in topology::inbound (BindSpec, HandoffSpec, TunSource, SuppliedTun and the handler types) and the policies in policy, but no public API takes a handler, so only the crate builds them (in build::inbound).
Key types
Section titled “Key types”BindSpec: what is bound, and the listener’s identity
Section titled “BindSpec: what is bound, and the listener’s identity”#[derive(Debug, Clone, PartialEq, Eq)]pub enum BindSpec { Tcp { host: String, port: u16 }, Udp { host: String, port: u16 }, Unix(PathBuf), Handoff(HandoffSpec), Tun(TunSource),}
impl BindSpec { pub(crate) fn socket_path(&self) -> Option<&Path>;}
#[derive(Debug, Clone, PartialEq, Eq)]pub struct HandoffSpec { pub path: PathBuf, pub mode: u32, pub gid: Option<u32>,}
#[derive(Debug, Clone, PartialEq, Eq)]pub enum TunSource { Create(DeviceSpec), #[cfg(unix)] Fd(SuppliedTun),}
impl TunSource { pub fn mtu(&self) -> u16; pub fn addresses(&self) -> impl Iterator<Item = IpAddr> + '_;}
#[cfg(unix)]#[derive(Debug, Clone)]pub struct SuppliedTun { pub fd: Arc<OwnedFd>, pub mtu: u16,}The bind is the listener’s identity. An inbound is served on every bind InboundSpec::binds() yields: its own bind, then BindSpec::Handoff(handoff) when its handoff is set. plan matches each of those binds to the running ones by ==, not by tag, and Actor::prepare finds the running Listener of each the same way (listeners.iter().position(|l| l.bind == wanted)). Two binds are the same when every field is equal, so a handoff socket whose mode or group changed is a new bind at the same path. A DeviceSpec compares its name, mtu, addresses and routes, so any change to the device is a different bind. SuppliedTun implements PartialEq by hand: two are equal when they hold the same raw descriptor number and the same mtu. The code relies on a descriptor number being unique while it is open, and both are held open.
Validation makes the bind a usable key. validate refuses a bind that an earlier inbound already has, or two binds at one socket path however else they differ (<bind> is bound by another inbound; socket_path() is the path of a Unix or Handoff bind), and validate_inbound pairs each protocol with one kind of bind: SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS and sss with Tcp or Unix (AnyTLS, which needs TLS, only Tcp in effect), Hysteria 2 with Udp, TUN with Tun (the protocol cannot be served on <bind>). A Handoff bind is never an inbound’s own bind: it exists only as the second listener of an inbound whose handoff is set, which only a stream protocol on a Tcp bind may be (only a stream inbound on a tcp listener takes a handoff socket). Off Unix it refuses a Unix bind (unix sockets are not served on <os>) and a handoff socket (handoff sockets are not served on <os>), and only a Tcp bind may read a PROXY header (only a tcp listener reads a PROXY protocol header). A TCP and a UDP bind on the same port are different binds. The rules and their tests are on Validation.
BindSpec implements Display, which every listener log line and bind error uses:
| Variant | Displayed as | Example |
|---|---|---|
Tcp |
{host}:{port} |
0.0.0.0:1080 |
Udp |
udp {host}:{port} |
udp 0.0.0.0:443 |
Unix |
unix:{path} |
unix:/run/etemenanki/socks.sock |
Handoff |
handoff:{path} |
handoff:/run/etemenanki/handoff/443.sock |
Tun(Create) |
tun {name}, or tun auto when name is None |
tun ete0 |
Tun(Fd) (Unix) |
tun fd {raw fd} |
tun fd 7 |
TunSource::Create is a device the inbound creates, addresses and routes itself, which needs the privilege to create an interface: root or CAP_NET_ADMIN on Linux, root on macOS, an elevated process on Windows, where the Wintun driver also needs wintun.dll. The system removes the device when its last handle closes. TunSource::Fd, which exists only on Unix, is a device handed over already configured, such as a mobile VPN API’s descriptor, whose platform owns the interface, its addresses and its routes. The FFI crate builds this variant. The listener serves duplicates of fd and closes them when it stops; fd itself closes when its last holder, the spec included, drops it. TunSource::mtu() returns the MTU from either variant; validation requires at least 1280 (MIN_TUN_MTU). TunSource::addresses() yields the addresses the inbound assigns a created device, and none for a supplied one, whose platform assigned them.
HandoffSpec is a stream inbound’s handoff socket: the Unix socket at path (absolute, at most 107 bytes), the socket file’s permission bits mode, such as 0o660, which decide who may connect and so hand connections over, and gid, the group the file is given, or None to leave the process’s own. It exists on every platform, but only Unix serves it. How it is bound is under Handoff sockets, and what each connection on it carries under Handed-over connections. Its fields and who sets them are on The spec: desired state.
Handlers
Section titled “Handlers”pub enum InboundHandler { Stream(Arc<StreamInbound>), Hysteria2(Hy2Handler), Tun(TunHandler),}
impl InboundHandler { pub(crate) fn share(&self) -> Option<InboundHandler>;}
pub struct StreamInbound { pub tag: CompactString, pub protocol: StreamProtocol, pub transport: InboundTransport, pub sniff: bool, pub proxy_protocol: bool, pub real_ip: Option<RealIpSpec>,}
pub enum StreamProtocol { Socks(ArcSwap<SocksInbound<Principal>>), Http(ArcSwap<HttpServerConfig<Principal>>), Trojan(ArcSwap<trojan::Validator<Principal>>), Vless { users: ArcSwap<vless::Validator<Principal>>, vision: bool, }, Vmess(Arc<AccountValidator<Principal>>), Shadowsocks(ArcSwap<Resolved<Principal>>), Ss2022(ArcSwap<Ss2022Users>), Anytls { users: ArcSwap<anytls::Validator<Principal>>, padding: Arc<PaddingScheme>, }, Sss { users: ArcSwap<sss::Validator<Principal>>, settings: Arc<sss::ServerSettings>, },}
pub struct Ss2022Users { pub config: Arc<Ss2022ServerConfig<Principal>>, pub validator: Option<Arc<ss_2022::Validator<Principal>>>,}
pub struct Hy2Handler { pub tag: CompactString, pub connection: Arc<Hy2ConnectionConfig<Principal>>, pub quic: quinn::ServerConfig, pub obfs: Option<Obfs>, pub max_connections: usize,}
pub struct TunHandler { pub tag: CompactString, pub inbound: TunInbound<Principal>, pub own_addresses: Arc<[IpAddr]>,}A handler is everything a listener serves with, split from the listener so that a changed inbound can get a new one on the same socket.
StreamInboundis what the accept loop serves every socket with. Every listener of an inbound serves its one handler:InboundHandler::sharereturns anotherInboundHandler::Streamover the sameArc<StreamInbound>for the inbound’s handoff socket, andNonefor a Hysteria 2 or TUN handler, whose inbound has one bind. So a swap, or a user table stored into the handler’s cells, reaches the TCP listener and the handoff socket alike.tagis what routes match on and what each session is filed under.transportis the layer under the protocol; a Unix listener carries none and never reads it, and a handoff socket runs it over each handed-over TCP socket.sniffsays whether a core reads a domain out of a flow addressed by IP.proxy_protocolsays whether a TCP connection may start with a PROXY protocol v2 header naming its client (seeConnection::serve_socket); a handed-over socket is never read for one, because its client came in the header sent beside it.real_ip, the spec’sRealIpSpec, says which upgrade header names a WebSocket connection’s client and which proxies are trusted to set it; the transport reads the header, andserve_tcpdecides whether it counts (see The client a trusted proxy names).StreamProtocolholds what each connection’s core is built from. Every user-dependent part sits behind anArcSwap, so a user change stores a new table into the running handler and never rebuilds it. VMess is the exception in form, not in effect: it keeps oneArc<AccountValidator>and swaps its user set itself, a set prepared against the running validator (AccountValidator::prepare_users) and then installed (AccountValidator::install). The install keeps the validator’s replay state and address hints, and the prepared set carries over the match times and hot-tier places of the users who stay. The type parameter isPrincipal, the per-user payload every protocol’s user table hands back on a successful handshake (see Users, principals and sessions). Three variants hold a setting beside their table, outside theArcSwap, so only a new handler changes it: VLESS’svision, whether each connection is wrapped in the XTLS Vision adapter (the request must then carry the Vision flow); AnyTLS’spadding, the scheme pushed to clients; and sss’ssettings, the chains, limits and rejection every stream is served with. A change to any of them swaps the handler, so live connections keep what they started with and new ones get the new value.StreamProtocol::name()returns the name used in log lines:socks,http,trojan,vless,vmess,shadowsocks,shadowsocks-2022,anytlsorsss.Ss2022Usersis a Shadowsocks 2022 inbound’s user table: the server config with its key and users, and in multi-user mode the lookup for the identity header.Hy2Handleris what a Hysteria 2 listener applies inside its one endpoint, because two QUIC endpoints cannot share a port.connectionis the per-connection config, with the user table (authenticator), the circuit budget (circuit_permits), the bandwidth and congestion settings and the QUIC transport settings (quic) inside it.quicbeside it is the TLS material new handshakes are answered with.TunHandleris the TUN inbound itself, built whenever the inbound is new or changed, andown_addresses, the addresses the inbound assigned the device (none for a supplied device). A flow that came in through the device has no way out through them.
Building handlers and user tables
Section titled “Building handlers and user tables”pub(crate) fn build_handler<U: UserId>( spec: &InboundSpec, users: &Admissions<U>, circuits: Option<&Arc<Semaphore>>, socket: &SocketOptions,) -> io::Result<InboundHandler>;
pub(crate) enum UserTable { Socks(SocksInbound<Principal>), Http(HttpServerConfig<Principal>), Trojan(trojan::Validator<Principal>), Vless(vless::Validator<Principal>), Vmess(Vec<(Uuid, Arc<Principal>)>), VmessPrepared(PreparedUsers<Principal>), Shadowsocks(Resolved<Principal>), Ss2022(Ss2022Users), Hysteria2(Authenticator<Principal>), Anytls(anytls::Validator<Principal>), Sss(sss::Validator<Principal>), None,}
pub(crate) fn user_table<U: UserId>(spec: &InboundSpec, users: &Admissions<U>) -> io::Result<UserTable>;
impl UserTable { pub(crate) fn fits(&self, protocol: &StreamProtocol) -> bool; pub(crate) fn prepare_for(self, protocol: &StreamProtocol) -> UserTable; pub(crate) fn store_into(self, protocol: &StreamProtocol);}build_handler builds a whole handler when an inbound is new or changed. Both it and user_table run while an apply is staged, on the blocking pool (supervisor.rs → stage_users), not on the actor’s task; their errors are reported in prepare, in inbound order, as if built there. It builds the user table first, with user_table, and then:
| Protocol | What build_handler makes |
|---|---|
| Hysteria 2 | hy2_handler: the masquerade (Masquerade::default(), or Masquerade::new(status, body, content_type)); circuit_permits, which is the running listener’s semaphore when circuits is Some and a new Semaphore::new(max_circuits) otherwise; the connection config, Hy2ConnectionConfig::new(authenticator, masquerade, circuit_permits), then its sniff, udp from udp_idle_timeout, bandwidth, ignore_client_bandwidth, congestion and quic from the spec; quic from hy2_endpoint::server_config(cert_pem, key_pem); obfs mapped from the spec; max_connections. |
| TUN | TunInbound::new(TunConfig { user: Principal::anonymous(), mtu: device.mtu(), udp, udp_idle_timeout, max_flows }), with without_sniffing() unless the spec sniffs and without_ipv6() unless its ipv6 is set; own_addresses from TunSource::addresses. |
| Every stream protocol | A StreamInbound with the table in its StreamProtocol variant, and proxy_protocol and real_ip from the spec. VMess’s validator is AccountValidator::from_users(users).with_clock_check(clock_check), where anything but an explicit clock_check: false keeps the check; it starts with an empty hot tier. VLESS’s vision is whether its flow is VlessFlow::Vision. AnyTLS’s padding is PaddingScheme::from_lines of its padding_scheme, or PaddingScheme::default() without one, and a scheme that does not parse fails the build as InvalidInput. sss’s settings are the spec’s SssServerSettings. The transport is InboundTransport::Tcp on a Unix bind. On any other bind, for every protocol InboundProtocolSpec::transport() names (all the stream protocols at this revision), build_transport(transport, real_ip, socket) makes Tcp, Tls (no ALPN), Ws, Grpc or Reality; the last is build_reality’s RealityServer, which dials its cover site with Dialer::new(socket), the supervisor’s socket policy, and the system resolver, outside the routing plane (The spec). TLS comes from TlsServerConfig::from_pem(cert, key, alpn); when it is layered under WebSocket its ALPN is http/1.1, and under gRPC h2. A WebSocket route is built in place: WsRoute::new(path), then .host(host) when a host is given, which requires the request’s Host to match it, then .real_ip_header(header)? when real_ip is set, and the result is InboundTransport::Ws { route, tls }. real_ip_header fails with InvalidInput not a header name: "<name>", a backstop behind validation’s refusal of the same name. |
A certificate or key that does not parse fails here and becomes ApplyError::Build, displayed as building inbound <tag> failed: <error>. etemenanki-app’s --test shows it for a Hysteria 2 certificate file with no certificate in it:
ERROR etemenanki_app: configuration invalid: building inbound hy2-in failed: hysteria2: the certificate file contains no certificateshy2_endpoint::server_config builds the TLS half: a TLS 1.3-only rustls config with ALPN h3. The transport parameters it also sets (QuicOptions::server() with CUBIC) are never used. The listener accepts each connection with its own, endpoint::for_connection(base, &config.quic, congestion) (protocols/src/hysteria/server/endpoint.rs): the connection config’s QUIC settings, and a congestion controller factory serving that connection alone (Negotiated, see Congestion control). The rest is on Hysteria 2: server. The errors of server_config are hysteria2: could not read the certificate: <error>, hysteria2: the certificate file contains no certificates, hysteria2: could not read the private key: <error>, hysteria2: the key file contains no private key, hysteria2: certificate and key do not match: <error>, hysteria2 tls setup failed: <error> and hysteria2 quic tls setup failed: <error>.
Other checks in build_handler and user_table guard what validation, which plan runs before prepare, already refuses as ApplyError::Invalid (inbound <tag>: <reason>): the masquerade that Masquerade::new checks, each Shadowsocks 2022 user key that normalise_psk checks, and the combinations behind inbound <tag>: protocol and bind do not match and missing tls. etemenanki-app’s --test prints the validation text for the first two:
ERROR etemenanki_app: configuration invalid: inbound hy2-in: hysteria2: 233 is the authentication success status and cannot be used for the masqueradeERROR etemenanki_app: configuration invalid: inbound ss-in: user alice@example.com: shadowsocks-2022: PSK too short (16 < 32)A UserTable is the user-dependent part of a handler, built from the users the inbound admits. Which credential each protocol reads, what each table holds in an open or shared mode, and the labels user_table fills in are on Users, principals and sessions. fits says whether a table is the kind a StreamProtocol stores. prepare_for does what storing it would do ahead of time: a Vmess table becomes VmessPrepared, a set built against the running validator (AccountValidator::prepare_users); every other table is complete already. store_into stores it:
UserTable |
Stored by | Into |
|---|---|---|
Socks, Http, Trojan, Vless, Shadowsocks, Ss2022, Anytls, Sss |
store_into |
ArcSwap::store on the matching StreamProtocol cell (the users cell of Vless, Anytls and Sss) |
VmessPrepared |
store_into |
AccountValidator::install on the running validator, one pointer store |
Vmess |
store_into |
AccountValidator::set_users, which prepares and installs in one call; a table that went through UserTarget::prepare arrives prepared instead |
Hysteria2 |
Listener::store_users |
Hy2Inbound::set_authenticator |
None |
Listener::store_users |
Nothing: a TUN device admits no users |
What a bind produces
Section titled “What a bind produces”pub(crate) enum Bound { Stream(StreamListener), Udp(std::net::UdpSocket), Tun { device: Device, first: Device },}
pub(crate) enum StreamListener { Tcp(TcpListener), #[cfg(unix)] Unix { listener: tokio::net::UnixListener, file: SocketFile, }, #[cfg(unix)] Handoff { listener: tokio::net::UnixListener, file: SocketFile, },}
#[cfg(unix)]pub(crate) struct SocketFile { path: PathBuf, id: (u64, u64), publish_to: Option<PathBuf>,}
pub(crate) enum AcceptedSocket { Tcp(tokio::net::TcpStream), #[cfg(unix)] Unix(tokio::net::UnixStream), #[cfg(unix)] Handoff(tokio::net::UnixStream),}
impl AcceptedSocket { pub(crate) fn refuse(self);}
impl StreamListener { pub(crate) async fn accept(&self) -> io::Result<(AcceptedSocket, Option<IpAddr>)>;}StreamListener::acceptreturns the peer’s IP for TCP (the port is dropped) andNonefor a Unix socket, which has no IP peer. A handoff socket yieldsAcceptedSocket::Handoff, a relay’s control connection, also withNone: its client is known only once the relay’s message is read, which the connection’s own task does, so a slow relay holds up no one else’s.AcceptedSocket::refuseturns a socket away at accept. For a control connection it first answers the relay0x01: the connection on offer is still the relay’s alone. Any other socket is just dropped.- Dropping a
StreamListenerreleases what it holds. So a listener bound by an apply that is then refused leaves nothing behind, and a stopped accept loop releases its port by dropping the listener. A Unix or handoff listener is bound under a staging name and moved over its path only when it starts, at commit (see Publishing at commit), so a refused apply never touches a file a running listener holds. SocketFileis the filesystem entry a Unix or handoff listener created:path, where the file is (its staging name until it is published), the file’s device and inode (SocketFile::newreads them right after the bind, and removes the file when it cannot), andpublish_to, the path it is published at, until it is. A rename keeps the device and inode. ItsDropremovespathonly whilesymlink_metadata(path)still reports that device and inode, so a file someone else has since put at the path is left alone. A failed removal is logged atdebugascould not remove <path>: <error>and otherwise ignored.fileis declared afterlistener, so the descriptor closes before the file is removed.Bound::Tuncarries the device, which the listener keeps, andfirst, a second handle on it (try_clone) for the first runtime.etemenanki_protocols::tun::Deviceis the device’s descriptor, anOwnedFd, on Unix, and a share of the adapter’s Wintun session on Windows; the device lives until its last handle is dropped.- The Unix and handoff variants exist only on Unix.
Pending pairs, listeners and swaps
Section titled “Pending pairs, listeners and swaps”pub(crate) enum Pending { Stream(StreamListener, Arc<StreamInbound>, Arc<InboundCaps>), Hysteria2 { tag: CompactString, inbound: Hy2Inbound<Principal>, endpoint: OpenedEndpoint, circuits: Arc<Semaphore>, obfs: Option<Obfs>, }, Tun { device: Device, prepared: PreparedDevice, handler: TunHandler, },}
pub(crate) struct Listener { pub tag: CompactString, pub bind: BindSpec, stop: CancellationToken, kind: ListenerKind,}
enum ListenerKind { Stream(watch::Sender<Arc<StreamInbound>>, Arc<InboundCaps>), Hysteria2 { inbound: Hy2Inbound<Principal>, tag: Arc<ArcSwap<CompactString>>, circuits: Arc<Semaphore>, obfs: Option<Obfs>, }, Tun { device: Device, restart: mpsc::UnboundedSender<(TunHandler, PreparedDevice)>, },}
pub(crate) enum Swap { Stream(Arc<StreamInbound>), Hysteria2(Hy2Handler), Tun(TunHandler, PreparedDevice),}
pub(crate) struct Users(UserTable);
pub(crate) enum UserTarget { Stream(Arc<StreamInbound>), Hysteria2, Tun,}- A
Pendingis a bound handle paired with the handler it will serve, with everything serving needs already built; a stream pair also carries the caps of the inbound it serves. It is the only thingListener::startaccepts, so starting cannot fail. - A
Listeneris a bound handle and the task serving it.tagis the tag of the inbound it currently serves, kept current byswap.bindis the key the actor finds it by.stopis a child of the supervisor’s root token, so shutdown reaches every listener. ListenerKindholds what the actor needs to reach the running task: thewatchsender of a stream listener’s handler and its inbound’s caps, whichListener::capsreturns so a listener added beside it can join them; the Hysteria 2 inbound handle (a clone of the one the task runs), a shared cell with its current tag, its circuit budget and its obfuscation; the TUN device’s own handle and the sender of the runtime’s restart channel.SwapandUsersare a handler and a user table already checked against the listener they go to. ASwapis made in prepare; aUsersis made while the apply or user edit is staged. Both are consumed in commit.UserTargetis a listener as a user table is prepared for it, away from the listener and off the runtime: a stream listener’s current handler, or only the kind of a Hysteria 2 or TUN listener. The handler a stream listener serves changes only at an apply’s commit, so the one taken is the one the table is stored into.
Shared, Connection and WireCounted
Section titled “Shared, Connection and WireCounted”#[derive(Clone)]pub(crate) struct Shared { pub plane: PlaneCell, pub sessions: Arc<Sessions>, pub flows: Tracker, pub tracker: TaskTracker, pub guard: Arc<Guard>,}
impl Shared { fn connector(&self, tag: CompactString, source: Option<IpAddr>, wire: Wire, stop: &CancellationToken) -> Option<(AppConnector, Arc<Session>)>; fn connector_for(&self, tag: CompactString, source: Option<IpAddr>, session: Arc<Session>) -> AppConnector; fn spawn_until<F>(&self, token: CancellationToken, fut: F) where F: Future<Output = ()> + Send + 'static;}
fn until_cancelled<F>(token: CancellationToken, fut: F) -> impl Future<Output = Option<()>>where F: Future<Output = ()>;
struct Connection { inbound: Arc<StreamInbound>, peer: Option<IpAddr>, carrier: Arc<Session>, stop: CancellationToken, shared: Shared, live: Arc<OwnedSemaphorePermit>, handshake: Arc<OwnedSemaphorePermit>,}
struct WireCounted<S> { inner: S, wire: Option<Arc<Wire>>,}Shared is what every accept loop shares with the supervisor, cloned into each task. Its fields:
| Field | Type | Used for |
|---|---|---|
plane |
PlaneCell |
The routes and outbounds every connector dials through (The plane) |
sessions |
Arc<Sessions> |
The session registry: open at accept, and root() for Hysteria 2 shutdown |
flows |
Tracker (crate::track) |
Where every flow is registered and metered (Tracking) |
tracker |
tokio_util::task::TaskTracker |
Every accept loop and connection task, so shutdown can wait for them |
guard |
Arc<Guard> (crate::guard) |
Who keeps failing to authenticate: the ban check before a TCP connection’s transport handshake, and the Report each stream ends its handshake in (The authentication guard) |
The two trackers are unrelated: flows is the supervisor’s flow registry, and tracker is Tokio’s task tracker. Its methods:
| Method | What it does |
|---|---|
connector |
Registers a new session with Sessions::open and returns a connector for its flows, or None when the listener’s stop is already cancelled. |
connector_for |
Builds a connector for a session already registered: AppConnector::new(plane, FlowContext { inbound_tag, source }, flows, Some(session)). |
spawn_until |
Spawns until_cancelled(token, fut) on the task tracker. |
until_cancelled is fut.with_cancellation_token_owned(token) (tokio_util): it ends as soon as the token is cancelled, dropping the future where it stands, and never starts a future whose token is already cancelled. It is a combinator rather than an async block over a select!, because such a block would keep the future it captured and the copy it moved into the select!, making each task twice the size of a connection’s future.
Connection is one accepted socket and what serving it needs: the handler, the peer IP, the socket’s own session (carrier), the listener’s token, Shared, and the two admission permits.
WireCounted wraps the SOCKS driver’s stream. poll_read adds the bytes a successful read filled as up, poll_write adds the count a successful write returned as down, and flush and shutdown pass through. What that counts is on Per-user usage accounting.
Data flow
Section titled “Data flow”Binding in prepare, serving in commit
Section titled “Binding in prepare, serving in commit”sequenceDiagram participant A as Actor (apply) participant B as listener bind participant P as Pending pair participant L as Listener start participant T as serving task Note over A: prepare, fallible, nothing visible A->>B: bind(tag, BindSpec) for each new bind B-->>A: Bound socket, Unix socket at its staging name, or TUN device handles A->>P: pair(bound, handler, the inbound's caps) P-->>A: Pending with Hysteria 2 endpoint opened or TUN device prepared Note over A: a later failure drops every Pending, which releases it Note over A: commit, infallible A->>L: start(bind, pending, shared, root child token) L->>L: publish a Unix or handoff socket at its path L->>T: spawn run_stream_inbound, run_hysteria_inbound or run_tun_inbound L-->>A: Listener, logged as inbound tag listening on bind
Tokens and tasks
Section titled “Tokens and tasks”flowchart TB root["root token (Sessions::root)"] stop["listener stop token, child of root"] sess["session token, child of root"] acc["run_stream_inbound"] hot["refresh_hot_tiers, one per stream listener"] sock["serve_socket, one per accepted socket"] conn["serve_connection, one per byte stream"] hy["run_hysteria_inbound"] hyconn["QUIC connection tasks (JoinSet in Hy2Inbound::run)"] tun["run_tun_inbound"] tunflow["flow tasks (JoinSet in TunInbound::run)"] cf["Carrier of a gRPC connection"] root --> stop root --> sess stop -. ends .-> acc stop -. ends .-> hot stop -. drains .-> hy stop -. ends .-> tun acc --> hot acc --> sock sock --> conn sess -. drops .-> sock sess -. drops .-> conn sess -. closes .-> hyconn cf -. cancels .-> sess hy --> hyconn tun --> tunflow
The accept loops, the Hysteria 2 and TUN listener tasks, every stream listener’s hot-tier refresher and every stream connection task run on the supervisor’s TaskTracker. The per-connection tasks of a Hysteria 2 listener and the per-flow tasks of a TUN device live in a JoinSet owned by the protocols crate’s run future, so they end when it does. A listener’s token stops only its accepting task and, for a stream listener, its refresher. A connection runs under its session’s token, which is a child of the root and not of the listener, so stopping a listener leaves the connections it accepted running. The serving code cancels a session’s token in one place: a gRPC connection’s Carrier cancels the carrier session’s token once carrier_max_failures of its streams in a row have failed authentication (The authentication guard). Otherwise a session’s token is cancelled by a removal policy, Supervisor::close, the removal of its inbound, shutdown, or a first flow that presents a principal already revoked or would exceed its user’s device limit (see Users, principals and sessions); the session’s own Drop cancels it too. TUN is the exception: its flows are tasks of the runtime the listener’s token stops.
One accepted socket
Section titled “One accepted socket”The sequence follows one client of a VLESS-over-TLS inbound from accept to the end of its relay.
sequenceDiagram participant C as Client participant L as run_stream_inbound participant S as Sessions participant K as serve_socket task participant T as InboundTransport participant V as serve_connection task participant D as drive and runtime C->>L: TCP connect L->>L: try_acquire live permit, then handshake permit L->>S: open(tag, peer, counted wire, stop) S-->>L: carrier session, token is a child of root L->>K: spawn_until(session token, serve_socket) Note over K: PROXY v2 header, when the inbound reads one, then the ban check K->>T: accept(tcp, sink) T->>C: TLS handshake within TRANSPORT_HANDSHAKE_TIMEOUT T->>V: sink(stream) spawns serve_connection on the same session V->>D: ProxyServerRuntime over VlessCore C->>D: request header Note over D: first flow admitted on the session binds its user Note over D: core established, drive drops its handshake permit and reports success D->>D: relay, adding transport bytes to the session wire Note over V: the task ends, dropping its permits and the session
One handed-over socket
Section titled “One handed-over socket”A relay running on the same host has accepted a client’s TCP connection and hands it over on the inbound’s handoff socket, whose listener serves the same handler as the TCP listener.
sequenceDiagram participant R as Relay on the same host participant L as run_stream_inbound participant K as serve_socket task participant T as serve_tcp R->>L: connect to the handoff socket L->>L: Sessions::open with no source L->>K: spawn_until(session token, serve_socket) R->>K: one sendmsg, the PROXY v2 header and the TCP socket as SCM_RIGHTS K->>K: receive within 5 s, one recvmsg, then the checks K-->>R: 0x00 taken, or 0x01 refused Note over K: the control connection is closed K->>K: carrier.set_source(the header's client) K->>T: serve_tcp(tcp, source) Note over T: ban check, transport, protocol, as for an accepted TCP socket
Binding: listener::bind
Section titled “Binding: listener::bind”pub(crate) async fn bind(tag: &str, bind: &BindSpec) -> io::Result<Bound>;Actor::prepare calls bind for every bind of a desired inbound (InboundSpec::binds()) that no running listener holds, and maps an error to ApplyError::Bind { inbound, bind, source }, displayed as inbound <tag>: binding <bind> failed: <error>. tag is used only in log lines.
BindSpec |
What bind does |
Returns |
|---|---|---|
Tcp { host, port } |
std::net::TcpListener::bind((host, port)), set_nonblocking(true), tokio::net::TcpListener::from_std |
Bound::Stream(StreamListener::Tcp) |
Udp { host, port } |
std::net::UdpSocket::bind((host, port)) |
Bound::Udp |
Unix(path) |
On Unix, see below. Elsewhere it fails with io::ErrorKind::Unsupported and unix socket <path>: not served on this platform, a backstop behind validation’s refusal. |
Bound::Stream(StreamListener::Unix) |
Handoff(spec) |
On Unix, bind_handoff(spec): see Handoff sockets. Elsewhere it fails as a Unix bind does, with the handoff socket’s path, behind validation’s handoff sockets are not served on <os>. |
Bound::Stream(StreamListener::Handoff) |
Tun(Create(spec)) |
etemenanki_protocols::tun::open(spec).await, which returns the device and its name, then try_clone for first. Logs inbound <tag> owns tun device <name> at info. |
Bound::Tun |
Tun(Fd(supplied)) (Unix) |
etemenanki_protocols::tun::adopt(supplied.fd.as_fd()), a non-blocking duplicate; then try_clone for first. Nothing is created, addressed or routed, so no privilege is needed. Logs inbound <tag> serves a supplied tun device at info. |
Bound::Tun |
host does not have to be an IP literal. Both bind calls take (host, port) through ToSocketAddrs, which resolves a name with the system resolver, and bind the first resolved address that succeeds; the error is the last address’s when none does.
tun::open (protocols/src/tun/device.rs) does the device work:
check_platform(spec): on a platform other than Linux, macOS and Windows, a spec with routes is refused withtun routes are installed only on Linux, macOS and Windows; add them with the OS route tool. On macOS, a name other thanutun<N>is refused withtun name "<name>": macOS names a tun device utun<N>, or leave it unset. Validation calls the same function for aTunSource::Create, so--testand a start agree.- Build the device with the MTU, the name when one is given, the first IPv4 address and every IPv6 address (
ipv6_tuple). On Windows, a failure here readscreating a Wintun adapter (needs wintun.dll beside the executable, and an elevated process): <error>. Each further IPv4 address is added to the live device. - Read back the name the system settled on, and install each route on the interface, by its index: on Linux through rtnetlink as a link-scope route, on macOS and Windows as an on-link route through
route_manager. Routes are never removed explicitly: the system drops them with the interface when its last handle closes. - On Unix, set the device non-blocking and return its descriptor; on Windows, return a
Devicesharing the Wintun session.
Any failure drops the half-built device, which destroys it. A duplicate shares its original’s file status flags, so adopt, which exists only on Unix, makes the supplied descriptor non-blocking too. On Android and iOS, tun::open fails with tun devices are created by the system VPN API here; adopt its descriptor. The device side is on TUN.
Unix socket files
Section titled “Unix socket files”#[cfg(unix)]const STAGING_ATTEMPTS: usize = 16;
#[cfg(unix)]fn check_path(path: &Path) -> io::Result<()>;
#[cfg(unix)]fn staging_path(path: &Path) -> PathBuf;
#[cfg(unix)]fn bind_staged<T>(path: &Path, bind: impl Fn(&Path) -> io::Result<T>) -> io::Result<(T, PathBuf)>;A Unix socket is not bound at its path while an apply is prepared. It is bound under a staging name beside its path, in the same directory, and moved over the path when its listener starts, at commit, so a refused apply removes only the staged file and never touches what is at the path. staging_path draws the name afresh for every bind: a dot and random letters, at least eight where the path leaves room for them, and never so many that the staged path is longer than a socket path may be (MAX_SOCKET_PATH, 107 bytes). So each bind gets a staging file of its own, and preparing never touches a running listener’s file.
bind_staged does the staging for a Unix and a handoff bind alike:
check_path(path)looks at what is at the path withsymlink_metadata, which does not follow a symlink, and touches nothing:- a stale socket file at the path, such as one a crashed run left, is replaced when the listener is published at commit;
- a file that is not a socket, a symlink included, is someone else’s file:
bindfails withio::ErrorKind::AlreadyExistsand<path> exists and is not a socket; NotFoundpasses; any other error is returned.
- It draws a staging name and binds the socket there. Binding over a file that already has the name fails with
AddrInUse, and a new name is drawn, at mostSTAGING_ATTEMPTS(16) times; after that the bind fails withAddrInUseandno free name to stage <path> under. Nothing found at a staging name is removed.
On Unix, bind creates a Unix listener in three steps:
bind_staged(path, …)withstd::os::unix::net::UnixListener::bind, which creates the socket file at the staging name.SocketFile::new(staged, path)records the new file’s device and inode withsymlink_metadata, and the path it is to be published at. If that fails, the staged file is removed and the error returned.set_nonblocking(true)andtokio::net::UnixListener::from_std. A failure here drops theSocketFile, which removes the staged file.
etemenanki-app shows both outcomes. With listen set to a path that holds a regular file, --test passes, because a dry run binds nothing, and a start fails:
ERROR etemenanki_app: failed to start: inbound in: binding unix:/run/etemenanki/socks.sock failed: /run/etemenanki/socks.sock exists and is not a socketWith a free path, the start logs the listener and removes the file again on SIGTERM:
INFO etemenanki_supervisor::system::listener: inbound in listening on unix:/run/etemenanki/socks.sockA Unix listener has no local IP and no peer IP. It carries no transport: validation refuses any shape other than plain TCP on it (a unix socket carries no transport; its shape must be plain tcp), and SOCKS with udp on it needs udp_bind (socks over a unix socket has no local IP for UDP associate; set udp_bind or turn udp off). What a UDP ASSOCIATE over a Unix socket may hear is on SOCKS.
Handoff sockets
Section titled “Handoff sockets”#[cfg(unix)]fn bind_handoff(spec: &HandoffSpec) -> io::Result<(tokio::net::UnixListener, SocketFile)>;bind_handoff binds through socket2 rather than UnixListener::bind, which listens as it binds: the socket is to have its mode and group before it listens, so no one connects in between under whatever the umask allowed. Like a Unix socket, it is bound under a staging name of its own (bind_staged) and published at its path at commit.
- The directory. When
path’s parent does not exist (metadatareturnsNotFound), it is created with any missing parents (DirBuilderwithrecursive(true)and mode0o750), set to0o750again withset_permissions, because the umask may have narrowed the mode it was created with, and given the groupgidwithchownwhengidis set. An existing directory is left as it is; any othermetadataerror is returned. - Bind.
bind_staged(path, …), as for a Unix bind: a file at the path that is not a socket is refused, a stale socket there is left to be replaced at commit, and the socket,Socket::new(Domain::UNIX, Type::STREAM, None), is bound at a fresh staging name. - Guard.
SocketFile::new(staged, path). From here on, any failure removes the staged file. - Mode and group.
set_permissions(staged, mode), thenchown(staged, None, Some(gid))whengidis set. The rename that publishes the file keeps both. - Listen.
listen(libc::SOMAXCONN). Every handed-over connection arrives on a control connection of its own, so a burst of clients at the relay is a burst of connects here, and the backlog is the longest the system offers. set_nonblocking(true), thentokio::net::UnixListener::from_std.
A failure at any step is ApplyError::Bind, inbound <tag>: binding handoff:<path> failed: <error>: a file at the path that is not a socket (<path> exists and is not a socket), no free staging name, a directory that cannot be created, or a group the process may not give the directory or the socket (chown fails). a_handoff_socket_takes_over_a_stale_file_and_is_set_up_as_asked pins the setup: a missing directory is made 0750 in the group, the socket is 0660 in the group, and the file is gone after shutdown; a stale socket file at the path is replaced; and a regular file there refuses the start with Bind and is left as it was.
A changed mode or gid is a new bind at the same path, so the new socket is bound beside the running one, under a staging name of its own, while the running listener keeps its file. When the apply is refused, by this bind or by any later step, the pending listener is dropped, its SocketFile removes the staged file, and the running socket is still at its path with its old mode and group. a_refused_apply_keeps_a_running_handoff_socket_at_its_path refuses a mode change through another inbound’s bind failure, and a_regroup_whose_chown_is_refused_keeps_the_running_handoff_socket a group change whose chown fails; in both the running socket still accepts connections at its path, and nothing is left at the staging name.
A handoff socket is a stream listener like the TCP one beside it: Pending::pair pairs it with the inbound’s StreamInbound, and Listener::start serves it.
Dry runs bind nothing
Section titled “Dry runs bind nothing”supervisor::check(spec) runs on a fresh actor: Actor::stage plans the spec and stages its users on the blocking pool, which admits them and builds every handler and user table; Actor::prepare with bind = false then builds every outbound and route; and drop_off_runtime drops the spec on the blocking pool. No new listener is bound or paired, so no port is taken, no handoff directory is created, no Hysteria 2 endpoint is opened and no TUN device is created. It refuses what a start would, short of a port or device that cannot be bound. etemenanki-app’s --test runs it and prints Configuration OK. on success, or logs configuration invalid: <error> at error and exits with a failure status.
Pairing and starting
Section titled “Pairing and starting”Pending::pair
Section titled “Pending::pair”impl Pending { pub(crate) fn pair(bound: Bound, handler: InboundHandler, caps: &Arc<InboundCaps>) -> io::Result<Self>;}caps are the admission caps of the inbound the listener will serve, which Actor::prepare works out once per inbound (see Admission). Only a stream pair keeps them.
Bound + InboundHandler |
What pair builds |
|---|---|
Stream + Stream |
Nothing more: Pending::Stream(listener, inbound, caps), with a clone of the caps |
Udp + Hysteria2 |
check_obfs (a Salamander key Salamander::new would refuse fails here, not at commit); circuits is connection.circuit_permits; Hy2Inbound::new(ListenerConfig { connection, quic, obfs, max_connections }); inbound.open(socket) builds the QUIC endpoint on the socket. |
Tun + Tun |
handler.inbound.prepare(first): registers the second handle with the Tokio runtime and configures the IP stack (MTU, UDP timeout, packet information on macOS and iOS). |
| Any other pair | io::ErrorKind::InvalidInput, the handler is not of the kind its listener serves |
An opened endpoint admits nobody until it is served. Hy2Inbound::open:
- stores the Salamander key of the inbound’s
obfs, or none, into the inbound’s sharedSalamanderSwitch, so the endpoint obfuscates from its first packet.openfails on a keySalamander::newrefuses (shorter thanMIN_PSK_LEN, 4 bytes), althoughpairhas already refused one withcheck_obfs; - calls
endpoint::from_socket(socket, None, switch, gate)withgate = RecvGate::default(), a closed gate.from_socketsets the socket non-blocking, wraps it for quinn’s Tokio runtime, and wraps it again inSalamanderSocket::switchableeven when there is no key, so obfuscation can be switched on, off or to another key under the running endpoint. With no server config the endpoint refuses handshakes, and with the gate closed it reads nothing off the socket, so clients’ packets wait in the kernel as they would for a socket nobody serves yet.runopens the gate withRecvGate::open.
A PreparedDevice is likewise read by nothing until its runtime starts. TunInbound::prepare registers the device handle with the runtime through TunDevice::new and sets the stack’s IpStackConfig. Its mtu setter refuses less than 1280, which is why validation’s MIN_TUN_MTU is 1280; prepare turns that refusal into InvalidInput. Dropped unserved, an opened endpoint and a prepared device both close, and the inbound is as it was.
The mismatch cannot happen after validation, which pairs every protocol with its kind of bind; the check keeps start infallible whatever the caller passes. The error, like every failure of pair (a refused key, from_socket or quinn’s endpoint creation failing, TunInbound::prepare failing), becomes ApplyError::Build.
Listener::start
Section titled “Listener::start”impl Listener { pub(crate) fn start(bind: BindSpec, pending: Pending, shared: &Shared, stop: CancellationToken) -> Self;}Actor::commit calls it for every pending pair with stop = root.child_token(), after the plane is published and removed users are revoked and before it stops the listeners the plan no longer wants, and appends the listener to Actor::listeners.
| Pending | start spawns on the task tracker |
ListenerKind |
|---|---|---|
Stream |
On Unix, first StreamListener::publish (below). Then run_stream_inbound(listener, rx, caps, shared, stop), with rx the receiving end of watch::channel(inbound) |
Stream(tx, caps) |
Hysteria2 |
run_hysteria_inbound(inbound.clone(), tag_cell, endpoint, shared, stop), with tag_cell = Arc::new(ArcSwap::from_pointee(tag)) |
Hysteria2 { inbound, tag: tag_cell, circuits, obfs } |
Tun |
run_tun_inbound(handler, prepared, rx, plane, flows, stop) through spawn_tun, with rx the receiving end of an unbounded mpsc channel |
Tun { device, restart: tx } |
Every start logs inbound <tag> listening on <bind> at info, target etemenanki_supervisor::system::listener.
Publishing at commit
Section titled “Publishing at commit”#[cfg(unix)]impl StreamListener { fn publish(&mut self);}
#[cfg(unix)]impl SocketFile { fn publish(&mut self);}A Unix or handoff listener’s bind has one step left at commit: StreamListener::publish calls SocketFile::publish, which renames the staged file over publish_to with std::fs::rename and records the path as the file’s own; a TCP listener has nothing to publish. The rename replaces what is at the path: a stale socket, or the file of a listener this commit stops, such as a handoff socket whose mode or group changed. The commit starts new listeners before it stops old ones, and the stopped listener’s SocketFile then finds another inode at the path and leaves it alone.
start cannot fail, so a failed rename is only reported, at error: could not move <staged> over <path>, so no one reaches the listener there: <error>. The listener then runs with its file still under the staging name, which its Drop removes.
Swapping handlers and user tables
Section titled “Swapping handlers and user tables”A desired inbound with a running listener on one of its binds either is unchanged or gets a new handler (Step::SwapHandler) on every such listener: Actor::prepare calls prepare_swap on each with its own handle on the one new handler (InboundHandler::share). An unchanged inbound may still get a new user table. The plan’s rules are on Planning and applying a change. The listener side:
impl Listener { pub(crate) fn prepare_swap(&self, handler: InboundHandler) -> io::Result<Swap>; pub(crate) fn swap(&mut self, swap: Swap, shared: &Shared); pub(crate) fn user_target(&self) -> UserTarget; pub(crate) fn store_users(&self, Users(table): Users); pub(crate) fn circuits(&self) -> Option<&Arc<Semaphore>>;}
impl UserTarget { pub(crate) fn prepare(&self, table: UserTable) -> io::Result<Users>;}Handler swaps
Section titled “Handler swaps”| Listener | prepare_swap (prepare) |
swap (commit) |
|---|---|---|
| Stream | Refuses a handler of another kind | Sets tag, then send_replace(inbound) on the watch sender. The accept loop reads the handler at each accept, so the next socket gets the new one. |
| Hysteria 2 | Refuses another kind; check_obfs on the new key |
If obfs differs: set_obfs (its expect states that prepare_swap checked the key). Then tag and the tag cell, the recorded circuit budget, set_connection_config, set_quic and set_max_connections. |
| TUN | Refuses another kind; takes a second handle on the listener’s device (try_clone) and prepares it |
Sets tag and sends the handler and prepared handle on restart. If the send fails because the runtime task has already ended, spawn_tun starts a new runtime task on them and replaces the sender. |
a_protocol_change_on_the_same_port_keeps_the_socket_and_old_connections pins a stream swap with a SOCKS inbound changed to HTTP on the same port: a relay opened before the apply keeps relaying, a new client speaks HTTP, and a socket accepted just before the apply but handshaking after it is still answered as SOCKS.
What a Hysteria 2 swap reaches is set by each setter of Hy2Inbound:
| Setter | Reaches |
|---|---|
set_connection_config |
Connections that arrive afterwards, with the config’s bandwidth, ignore_client_bandwidth, congestion and QUIC settings: each connection is accepted with transport parameters from the config current at its arrival. |
set_quic |
New handshakes: the running endpoint takes the TLS material at once. Live connections keep what they negotiated. |
set_max_connections |
Arrivals from now on. Lowering it closes no live connection; new ones are refused until enough have ended. The limit is a count checked per arrival, not a semaphore, so it can change under live connections. |
set_obfs |
Every packet, both ways, from the moment it returns. Every connection negotiated under the old key is closed, since it cannot continue under the new one; the endpoint stays bound and keeps accepting. Setting the key already in use closes nothing. |
The circuit budget is carried over when the running and the desired inbound on the bind are both Hysteria 2 with the same max_circuits (same_circuits in supervisor.rs): stage_users passes the running listener’s Listener::circuits(), taken into its ListenerView by Actor::lend, to build_handler, so the new connection config carries the running semaphore and live circuits keep counting against it. A different size gets a new semaphore, a fresh budget beside the circuits still held under the old one.
A changed Hysteria 2 obfuscation is a Step::Disrupt, because it ends live connections. An apply without ApplyOptions::allow_disruptive is refused with ApplyError::Disruptive when its plan holds one. katana applies its specs with allow_disruptive set, so a Hysteria 2 obfuscation change applies there. etemenanki-app refuses a change to a TUN inbound’s device or settings, and a restart applies it.
etemenanki-app refuses such a reload, a TUN change included, and logs reload refused, keeping the running config: inbound <tag>: <reason>, which would end its live connections; restart to apply it; a restart applies it. See etemenanki-app: running, reloading and shutting down.
A masquerade, certificate, UDP or connection-limit change on a Hysteria 2 inbound is a plain swap, not a Step::Disrupt (a_hysteria2_masquerade_change_swaps_without_disrupting), and so is a change to its bandwidth, ignore_client_bandwidth, congestion or quic, which reaches the connections that arrive afterwards. A change to a VMess inbound’s clock_check builds a new validator and swaps the handler without disruption too (a_vmess_clock_check_change_swaps_the_handler_without_disruption).
User tables
Section titled “User tables”A user table is prepared against the listener’s UserTarget, which Actor::lend takes for every running listener (Listener::user_target) before the change is staged on the blocking pool, and stored at commit:
| Listener | UserTarget::prepare accepts |
store_users |
|---|---|---|
| Stream | A table that fits the handler’s protocol, then prepare_for it: a VMess set is built against the running validator here |
store_into the handler’s protocol; for VMess, AccountValidator::install |
| Hysteria 2 | UserTable::Hysteria2 |
Hy2Inbound::set_authenticator(Arc::new(authenticator)), stored into the current connection config: connections authenticated from now on use it |
| TUN | UserTable::None |
Nothing |
Any other table is refused with the handler is not of the kind its listener serves. A stream inbound’s table is prepared against, and stored into, the listener on its own bind; its handoff socket’s listener serves the same StreamInbound, so the table reaches it too. Both the apply path (stage_users) and the user-edit path (stage_user_edit, for set_users, upsert_user and remove_user) end here. Neither stores a table before every table of the change is prepared, and both revoke removed users’ principals first, so a handshake against a table about to be replaced finds its principal revoked. That ordering and what it does to live sessions are on Users, principals and sessions.
In one apply, an inbound gets a swap or a user table, never both: a changed inbound’s handler is built with the new users already, and only an unchanged one whose admissions differ gets a table. So set_connection_config and set_authenticator never race on one Hysteria 2 listener, and since the actor runs one command at a time, no other caller can race them either.
The stream accept loop
Section titled “The stream accept loop”const ACCEPT_ERROR_BACKOFF: Duration = Duration::from_millis(100);const MAX_HANDSHAKES_PER_INBOUND: usize = 204_800;const MAX_LIVE_CONNECTIONS_PER_INBOUND: usize = 4_194_304;
pub(crate) struct InboundCaps { handshakes: Arc<Semaphore>, live: Arc<Semaphore>,}
impl InboundCaps { pub(crate) fn new() -> Arc<Self>;}
pub(crate) async fn run_stream_inbound( listener: StreamListener, handler: watch::Receiver<Arc<StreamInbound>>, caps: Arc<InboundCaps>, shared: Shared, stop: CancellationToken,);Before it accepts anything, run_stream_inbound spawns the listener’s hot-tier refresher on the task tracker, refresh_hot_tiers(handler.clone(), stop.clone()) (see The VMess hot-tier refresher). The loop is a biased tokio::select! of stop.cancelled() over listener.accept(). Biased means the stop is checked first on every turn, so once the listener is stopped not one more socket is accepted. On stop the loop breaks and drops the listener, which closes the port or removes the socket file while it is still the one the listener created.
Accept errors
Section titled “Accept errors”fn should_backoff_accept_error(e: &io::Error) -> bool;async fn backoff_or_cancelled(token: &CancellationToken) -> bool;io::ErrorKind |
Meaning | Handling |
|---|---|---|
ConnectionAborted, Interrupted |
One client went away before accept, or a signal interrupted the call. The listener is fine. |
debug accept error: <error>, then accept again at once |
| Anything else | Usually resource exhaustion, such as running out of file descriptors, which would fail again at once | warn accept error, backing off 100ms: <error>, then backoff_or_cancelled sleeps ACCEPT_ERROR_BACKOFF |
The backoff keeps a persistent error from turning the loop into a busy spin that floods the log. backoff_or_cancelled races the sleep against the stop token and returns true when the token wins, and the loop then breaks without finishing the sleep. An accept error never ends the loop by itself.
Admission
Section titled “Admission”The two semaphores belong to the inbound, not to a listener: an InboundCaps holds both, and every listener of the inbound, its TCP listener and its handoff socket alike, counts against the same pair, so a second listener is no second pool. Actor::prepare works the caps out once for each inbound it builds, before it binds any of its listeners:
fn caps_for<'a>(kept: impl Iterator<Item = Option<&'a Arc<InboundCaps>>>) -> Arc<InboundCaps>;caps_for is given, for each of the inbound’s binds (binds()), the caps of the running listener on that bind (Listener::caps, None for a Hysteria 2 or TUN listener). It returns the first caps it finds, so a listener added beside a kept one joins the kept one’s pool, whichever of the inbound’s binds is kept, and new caps (InboundCaps::new()) when no listener is kept. A listener keeps its caps in ListenerKind::Stream for as long as it runs, and a handler swap does not touch them, so connections accepted before a swap still count. an_inbounds_listeners_share_one_set_of_caps pins which caps a listener gets.
| Semaphore | Capacity | Taken | Released |
|---|---|---|---|
live |
MAX_LIVE_CONNECTIONS_PER_INBOUND (4,194,304) |
First, at accept | When the connection has ended |
handshakes |
MAX_HANDSHAKES_PER_INBOUND (204,800) |
Second, at accept | For a protocol drive serves, drive drops its handle to the permit once its core reports established |
Both are taken with try_acquire_owned: the loop never waits for a permit. When one is exhausted the loop logs at debug, turns the freshly accepted socket away (AcceptedSocket::refuse) and continues, which drops the socket (the client sees the connection close) and any permit taken for it:
dropping inbound connection; live connection limit reacheddropping inbound connection; handshake limit reachedRefusing at once keeps the loop responsive and keeps a burst from piling up sockets nobody serves. The live cap is a guardrail, not a quota: a busy inbound carries hundreds of thousands of mostly idle connections, so the cap sits far above normal traffic. It is also above typical per-process file-descriptor limits, so do not expect it to act before descriptors run out. Running out shows up as an accept error, which the 100 ms backoff above handles. Operator-facing limits are on Limits and timeouts.
A session from the first moment
Section titled “A session from the first moment”With both permits taken, the loop:
- reads the current handler,
handler.borrow().clone(), which holds thewatchchannel’s read lock only while theArcis cloned; - opens the socket’s session,
shared.sessions.open(inbound.tag, peer, Wire::counted(), &stop), with the socket’s peer as its source: none for a handoff control connection, whose client is set once the relay’s message is read. The session is registered, and listed bySupervisor::sessions, from this moment, with no user until its first flow binds one. Its transport handshake is closed with its inbound too.openchecks the stop token under the registry’s lock and returnsNoneonce it is cancelled; the loop then refuses the socket and breaks, dropping it. That check is what lets a removed inbound’s session sweep miss nothing (a_stopped_listener_opens_no_session); - builds a
Connectionwith the handler, the peer, the session ascarrier, clones ofstopandShared, and both permits; - spawns
connection.serve_socket(socket)withshared.spawn_until(carrier.token(), …).
The peer IP is carried rather than dropped at accept because routing needs it: RouteMatch::SourceCidr has nothing to match without it, and it is the one client a SOCKS UDP ASSOCIATE hears. The inbound tag feeds RouteMatch::InboundTag the same way. Both reach the route through FlowContext (The plane). On an inbound that reads PROXY headers, the client a header names is the source instead, and on a WebSocket inbound with real_ip, the client a trusted proxy names in the upgrade (see below).
The VMess hot-tier refresher
Section titled “The VMess hot-tier refresher”const HOT_TIER_POLL: Duration = Duration::from_secs(1);
async fn refresh_hot_tiers(handler: watch::Receiver<Arc<StreamInbound>>, stop: CancellationToken);async fn refresh_hot_tier(validator: Arc<AccountValidator<Principal>>);A VMess validator tries a few likely users before it scans every user, and one of those guesses is its hot tier: copies of the key schedules of the up to 4,096 users matched most recently, newest first. The validator never reorders anything during a handshake. It counts the admitted matches that only its full scan found, and once 16 have counted since the last refresh was prepared, hot_tier_due() turns true; prepare_hot_tier resets the count. Running the refresh is the supervisor’s job. The validator side is on VMess: keys and authentication.
Every stream listener runs one refresher, whatever its protocol. refresh_hot_tiers ticks every HOT_TIER_POLL (1 s), the first time one poll after the listener starts, with MissedTickBehavior::Delay, so a listener refreshes at most once a second. At each tick it reads the handler current in the listener’s watch channel. When that handler is VMess and its validator’s hot_tier_due() is true, it clones the validator out of the channel and awaits refresh_hot_tier: prepare_hot_tier() runs on the blocking pool (system::blocking::off_runtime), as a user set is built, and install_hot_tier(prepared) then swaps the result in on the listener’s task. For any other handler, or a tier not due, it waits for the next tick. Because the handler is read at every tick, a swap to a new VMess handler is followed from the next tick on.
The refresher returns once the listener’s stop is cancelled; a refresh already started runs to its end first. An install that finds the validator’s users or hot tier changed since the prepare read them drops the prepared tier, so a refresh racing a user change never installs a tier that names another user set’s slots.
Connection::serve_socket
Section titled “Connection::serve_socket”impl Connection { async fn serve_socket(self, socket: AcceptedSocket); async fn serve_tcp(self, tcp: tokio::net::TcpStream, source: Option<IpAddr>);}serve_socket settles what the accepted socket carries and who its client is, then serves it:
AcceptedSocket::Unix:serve_connectionruns inline on the Unix stream, withlocal_ip = None, a connector for the carrier session withsource = None, andReport::new(guard, None, None), a report with no client IP and no gRPC connection to count against. No transport runs and no keepalive is set.AcceptedSocket::Tcp: the client is the socket’s peer, or the one a PROXY protocol header names (below). Thenserve_tcp(tcp, source).AcceptedSocket::Handoff:handoff::receive(control)takes the TCP socket the relay sent on its control connection, and the client the header beside it names (Handed-over connections).Noneends the task, which drops the session. Otherwisecarrier.set_source(source)records the client before any flow binds the session, andserve_tcp(tcp, source)serves the socket. No PROXY header is read off the handed-over socket, whateverproxy_protocolsays.
serve_tcp serves a TCP socket whose client is source, however it was accepted. local_ip is taken from tcp.local_addr(); for a handed-over socket that is the address its client connected to at the relay. The SOCKS driver puts it in its replies and, unless udp_bind is set, binds the UDP ASSOCIATE relay on it. Then serve_tcp checks the client against the guard and runs InboundTransport::accept(tcp, sink).
const PROXY_HEADER_TIMEOUT: Duration = Duration::from_secs(10);The client’s address, source, starts as the socket’s peer. When the inbound’s proxy_protocol is set, serve_socket first reads a PROXY protocol v2 header off the front of the socket, tokio::time::timeout(PROXY_HEADER_TIMEOUT, proxy_protocol::read_v2(&mut tcp)):
| Outcome | What happens |
|---|---|
| A header naming a client | source becomes the client’s IP. |
| No header, or a header naming no client | source stays the socket’s peer. |
| A read error, such as a malformed header | The connection is dropped, logged at debug as dropping a connection from <peer>: <error> (the peer printed with {:?}, so Some(203.0.113.7)). |
No header complete within PROXY_HEADER_TIMEOUT (10 s) |
The connection is dropped without a log line. |
Only version 2, the binary form, is read. carrier.set_source(source) then records the result in the carrier session, before any flow binds it, so Supervisor::sessions lists the client and the device limit counts it. The reader itself is described on TCP and TLS transports.
Next, when source is an IP the guard has banned (Guard::is_banned), serve_tcp returns before the transport handshake: the socket closes and its session is dropped. A handed-over socket is held to the same check with the client its header named. A Unix connection has no IP and is never checked. Connections already open from that IP run on.
For the gRPC transport, serve_tcp then makes one Carrier over the carrier session’s token (Carrier::new(token)), shared by every stream of the connection. Each stream the transport yields is served with Report::new(guard, source, carrier), where source is the stream’s client and carrier is that Carrier on gRPC and None otherwise (The authentication guard).
pub const TRANSPORT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]#[non_exhaustive]pub enum InboundTransport { Tcp, Tls(ServerConfig), Ws { route: WsRoute, tls: Option<ServerConfig> }, Grpc { paths: Arc<GrpcPaths>, tls: Option<ServerConfig> }, /// REALITY, over TCP. #[cfg(feature = "reality")] Reality(super::reality::RealityServer),}
#[non_exhaustive]pub enum Disposition { /// Every stream the socket yielded went to the sink. Done, /// The socket is not a client of ours: run the relay. Only REALITY /// yields this, and the sink never saw the socket. Camouflage(Camouflage),}
impl InboundTransport { pub async fn accept<F>(&self, tcp: TcpStream, mut sink: F) -> io::Result<Disposition> where F: FnMut(Accepted);}accept enables TCP keepalive on the socket, runs the transport’s own handshake within TRANSPORT_HANDSHAKE_TIMEOUT, and calls sink for each byte stream:
InboundTransport |
Streams | Returns |
|---|---|---|
Tcp |
One, the socket itself | Done |
Tls |
One, after the TLS handshake | Done |
Ws |
One, after the WebSocket upgrade (over TLS when configured) | Done |
Grpc |
One per HTTP/2 stream on the tunnel service’s paths | Done, when the HTTP/2 connection ends |
Reality |
One, TransportStream::Reality, for a client that authenticated |
Done |
Reality |
None, for anyone else: the socket goes to the cover site | Camouflage(relay) |
InboundTransport and Disposition are #[non_exhaustive] in the protocols crate, so a later transport is an addition. A timeout fails with io::ErrorKind::TimedOut and tls handshake timed out, websocket handshake timed out or grpc handshake timed out; REALITY keeps its own deadline for its decision, and one that runs out hands the socket to the cover site rather than closing it. Any transport error ends serve_tcp with debug inbound transport failed: <error>, and the socket and its session are dropped. How REALITY decides is on REALITY transport. The transports are on TCP and TLS transports and WebSocket and gRPC transports.
The sink closure first settles the stream’s client: on a WebSocket inbound with real_ip, a trusted proxy’s upgrade header may name it (see the next section). It then decides the stream’s session:
- One stream per socket (TCP, TLS, WebSocket). The stream is served as the carrier session:
connector_for(tag, source, carrier), andserve_connectionis spawned under the carrier’s token. - gRPC. Each HTTP/2 stream is a session of its own, opened through
Shared::connector(tag, source, Wire::counted(), &stop)with aWireof its own, and served under its own session’s token. A stream arriving once the listener is stopped opens no session and is not served.
Last, on a VLESS inbound whose handler has vision set, the sink wraps the stream with TransportStream::into_vision_server while its concrete type is still in hand, and serve_connection gets the Vision stream: the VLESS core then reads plain VLESS over it. Only a REALITY stream can be wrapped; any other fails with vless vision rides only over reality, logged at debug as <tag>: vision setup failed: <error>, and the stream is dropped. Validation refuses Vision off REALITY first. On a VLESS inbound without Vision the core looks the user id up before it reads the flow, so an unknown id is refused with PermissionDenied, and counts toward the IP ban, whatever flow it asks for, while a known user’s Vision request is refused with Unsupported (vless flow (xtls vision) is not served by this core). The adapter is on XTLS Vision.
A socket that goes to the cover site
Section titled “A socket that goes to the cover site”When accept returns Disposition::Camouflage(relay), the socket was not a REALITY client of ours and now belongs to the cover site. serve_tcp logs <tag>: <source> goes to dest: <reason> at debug, with the reason a category the relay names, never a key or a client identifier. It then drops its handshake permit, since the connection is past the handshake, keeps its live permit, and runs relay.run(RELAY_IDLE_TIMEOUT) itself, inside the connection’s task: the relay copies both ways until both sides close, and ends after RELAY_IDLE_TIMEOUT (300 s) without a byte either way. An error ends it with debug <tag>: relay to dest ended: <error>.
The relay is a live connection like any other: it counts against the inbound’s live cap, and it ends when its session is closed, by an inbound’s removal or at shutdown, because the task runs under the carrier session’s token. Nothing about it is reported to the guard. The code’s reason: a probe must not see the server react, and the browsers behind a prober’s address must not pay for it. a_camouflaged_connection_gives_its_handshake_permit_back pins all of this.
The client a trusted proxy names
Section titled “The client a trusted proxy names”fn real_ip_source(real_ip: &RealIpSpec, header: &RealIpHeader, source: Option<IpAddr>) -> Option<IpAddr>;impl TransportStream { pub fn real_ip_header(&self) -> Option<&RealIpHeader>;}A WebSocket inbound behind a reverse proxy such as nginx sees every connection come from the proxy. The proxy can name the client in a header of the upgrade request, X-Real-IP or a list such as X-Forwarded-For, and an inbound with real_ip takes the client from it, as nginx’s realip module does. build_transport gave the inbound’s WsRoute the header name, so the transport reads that header off every upgrade, trusting nothing, and real_ip_header() on the yielded stream returns what it found: Missing, Malformed, or Addresses in the header’s order, IPv4-mapped IPv6 given as IPv4. It is Some only for a WebSocket stream whose route reads a header. How the header is parsed is on WebSocket and gRPC transports.
The header counts only on a connection from a proxy in the trusted networks. When the inbound has real_ip and the stream carries a header result, the sink calls real_ip_source(real_ip, header, source); otherwise the client stays source. RealIpSpec::trusts(ip) canonicalises ip and asks whether any network in trusted holds it.
| The connection’s client | Header | The stream’s client |
|---|---|---|
Not in any trusted network, or none (None) |
any | Unchanged: the header is ignored, so a client cannot name itself someone else |
| A trusted proxy | Addresses(list) |
The rightmost address in list that no trusted network holds; the leftmost when they hold every one |
| A trusted proxy | Missing |
The proxy, logged at debug as trusted proxy <ip> sent no <header> header; serving it as the client |
| A trusted proxy | Malformed |
The proxy, logged at debug as trusted proxy <ip> sent a <header> header that lists no addresses; serving it as the client |
Each proxy appends the address it heard from, so the entries trusted proxies appended sit at the right end of a list. The rightmost entry no trusted network holds is the address the outermost trusted proxy, the one farthest from the inbound, heard from; anything left of it may have been written by the client itself.
When the client this names differs from the connection’s, the sink holds it to the guard before anything is served:
- Bans. A client the guard has banned (
Guard::is_banned) is not served: the sink returns and the stream is dropped. A WebSocket socket carries only that one stream, so the socket and its session end with it. Nothing is logged. - The session. A transport that is not multiplexed (always the case for WebSocket) calls
carrier.set_source(named), so the socket’s session lists that client and, since this happens before any flow binds the session, the device limit counts it (Users, principals and sessions). - Everything after. The named client is the
sourcethe sink passes on: toconnector_for, so routing’ssource_cidrand the flow tracker see it, to the protocol coreserve_connectionbuilds, and to the stream’sReport, so a refused credential counts against that client’s IP and a ban falls on it, not on the proxy.
Handed-over connections
Section titled “Handed-over connections”A relay running on the same host may accept a client’s TCP connection itself and hand the socket over on the inbound’s handoff socket. supervisor/src/system/handoff.rs receives it; from then on the supervisor serves it exactly as a connection its TCP listener accepted, with the client the relay names.
const TAKEN: u8 = 0x00;const REFUSED: u8 = 0x01;const RECEIVE_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) async fn receive(control: UnixStream) -> Option<(TcpStream, Option<IpAddr>)>;pub(crate) fn refuse(control: &UnixStream);
struct Received { len: usize, fds: Vec<OwnedFd>, truncated: bool,}
fn adopt(received: Received, buf: &[u8]) -> io::Result<(TcpStream, Option<IpAddr>)>;fn recv_with_fds(socket: BorrowedFd<'_>, buf: &mut [u8]) -> io::Result<Received>;pub const MAX_V2_LEN: usize = 4096;
pub struct Header { pub source: Option<SocketAddr>, pub len: usize,}
pub fn decode_v2(bytes: &[u8]) -> io::Result<Header>;The module exists only on Unix (system/mod.rs declares it under #[cfg(unix)]).
The wire contract
Section titled “The wire contract”Each connection on a handoff socket is a control connection carrying one client’s TCP connection:
- The relay connects to the handoff socket, a Unix stream socket. Who may connect is set by the socket file’s mode and group and its directory’s (see Handoff sockets).
- Within
RECEIVE_TIMEOUT(5 s) of the supervisor accepting the control connection, the relay sends one message with onesendmsg. Its bytes are a whole PROXY protocol v2 header naming the client, at mostMAX_V2_LEN(4,096) bytes, with nothing after it. Its ancillary data is exactly one descriptor asSCM_RIGHTS: the client’s connected TCP socket. - The supervisor answers with one byte:
0x00(TAKEN) once the socket is taken, which makes it the supervisor’s to serve, or0x01(REFUSED) when it is not, and the connection is then still the relay’s alone. - The supervisor closes the control connection.
The header is decoded by decode_v2 (protocols/src/transports/proxy_protocol.rs), which read_v2 and parse_v2 share, and every fixed field is held to the protocol: the signature, version 2, a LOCAL or PROXY command, one of the address families the protocol defines (TCP or UDP over IPv4 or IPv6, a Unix stream or datagram address, or unspecified; a LOCAL header’s family and address block are ignored), an address block long enough for that family, and a total length within MAX_V2_LEN. Header::len says where the header ends. The client is the source address of a PROXY header over TCP on IPv4 or IPv6, canonicalised (to_canonical, so an IPv4-mapped IPv6 address is the IPv4 address). A LOCAL header, or a PROXY header naming a UDP, Unix or unspecified address, names no client, and the handed-over socket’s own peer is the client. A header’s TLVs, inside its address block, are read past and never interpreted. How the same decoder serves a TCP listener’s PROXY header is on TCP and TLS transports.
Receiving: receive and adopt
Section titled “Receiving: receive and adopt”receive owns the control connection. It reads the message with one recvmsg into a buffer of MAX_V2_LEN + 1 bytes, one more than the longest header, so a byte after a header of the full length is read too and refused like any other trailing byte. The read runs through UnixStream::async_io(Interest::READABLE, …) under tokio::time::timeout(RECEIVE_TIMEOUT, …):
| What arrives | What receive does |
Answer |
|---|---|---|
| Nothing: the relay hung up without sending a byte or a descriptor | Returns None |
None |
| Nothing within 5 s | Logs debug handoff: no message within 5s, returns None |
None |
| A read error | Logs debug handoff: reading the message failed: <error>, returns None |
None |
| A message | adopt checks it |
0x00 when adopt takes the socket, otherwise 0x01 and debug handoff: refused: <reason> |
adopt checks the message in this order, and the first failure is the refusal’s reason:
| # | Check | Reason when it fails |
|---|---|---|
| 1 | No ancillary data was cut off (MSG_CTRUNC) |
more ancillary data than one descriptor |
| 2 | Exactly one descriptor came | not exactly one descriptor |
| 3 | The bytes decode as a v2 header (decode_v2) |
the decoder’s text, such as PROXY protocol v2: the header is cut short, PROXY protocol v2: not version 2 or PROXY protocol v2: the header is too long |
| 4 | Nothing came after the header | bytes after the PROXY header |
| 5 | The descriptor is a stream socket (Socket::type) |
not a stream socket, or the system’s error for a descriptor that is no socket |
| 6 | Its peer is an IP address (Socket::peer_addr), which also says it is connected: a Unix socket has a path, and an unconnected or listening one has no peer |
not an IP socket, or the system’s error for one with no peer |
Once every check passes, the socket is made close-on-exec where it is not already, non-blocking, and a tokio::net::TcpStream, and the client is the header’s source or the socket’s peer, canonicalised. adopt always names a client, so a handed-over connection’s source is never None.
recv_with_fds is the one place descriptors are received by hand: neither std nor socket2 receives them. It is the module’s only unsafe code, a zeroed msghdr over the buffer and a control buffer of eight u64s (aligned for the cmsghdr the kernel writes, with room for a few descriptors, so a relay sending more is found out rather than leaving descriptors behind), the recvmsg call, and a walk of the control messages with the CMSG_FIRSTHDR, CMSG_DATA and CMSG_NXTHDR macros. Every descriptor of every SCM_RIGHTS message is read unaligned and wrapped in an OwnedFd at once, so each one that is not taken, a refused one or the second of two, is closed when adopt returns. On Linux and Android the call passes MSG_CMSG_CLOEXEC, so a received descriptor is close-on-exec from the start and a child forked in between never inherits it; elsewhere adopt sets close-on-exec on the socket it takes.
Answers and the control connection
Section titled “Answers and the control connection”answer writes the byte with try_write. A fresh connection’s send buffer is empty, so it never waits. A relay already gone is not an error: the failure is logged at debug as handoff: the relay was not answered: <error>, and the socket is served, or dropped, all the same. receive takes the control connection by value, so it is closed when receive returns, whatever the outcome.
A control connection can also be refused unread. When the accept loop turns it away at accept, AcceptedSocket::refuse calls handoff::refuse, which answers 0x01 and drops the connection. A descriptor the relay already sent on it is never received, and is released with the connection.
Serving the socket
Section titled “Serving the socket”receive runs in the connection’s own task, under the session that the accept loop opened for the control connection, so a slow relay holds up no one else’s handover. Once the socket is taken, serve_socket records the client with carrier.set_source and calls serve_tcp, so everything after is what a connection accepted by the TCP listener gets:
- a client the guard has banned is dropped before the transport handshake, and a refused credential counts against the client the header named (
a_handed_over_client_failing_to_authenticate_is_banned); - the inbound’s transport runs over the socket, TLS, WebSocket and gRPC included, and on gRPC each stream is a session of its own with the same client (
tls_grpc_and_vmess_run_over_a_handed_over_connection); - the session’s source, which the device limit counts and
Supervisor::sessionslists, is the client, and so is the source routing and the flow tracker see.
The session is dropped, and the control connection closed without an answer, if the session’s token is cancelled while the message is awaited (at shutdown, for example). A refused handover changes nothing for the relay’s connection: a_malformed_handoff_is_refused_and_the_connection_stays_the_relays sends nine handovers that must be refused (no descriptor, two descriptors, a UDP socket, a Unix socket, a listening socket, bytes after the header, one byte after a header of the full MAX_V2_LEN, a header of the wrong version, a header cut short), sees each answered 0x01 and closed, and then relays bytes both ways over the relay’s own connection. A control connection closed without a message gets no answer, and the next handover is taken.
serve_connection: one driver per protocol
Section titled “serve_connection: one driver per protocol”async fn serve_connection<S>( inbound: Arc<StreamInbound>, stream: S, local_ip: Option<IpAddr>, connector: AppConnector, live: Arc<OwnedSemaphorePermit>, handshake: Arc<OwnedSemaphorePermit>, report: Report,) where S: AsyncRead + AsyncWrite + Unpin + Send + 'static;serve_connection reads source from the connector (the client’s IP, or None over a Unix socket) and sniff from the handler, and matches on the protocol. Each drive arm passes the core as a closure that builds it (|| TrojanCore::new(..)), with the stream, the connector, the handshake permit and the report:
StreamProtocol |
Driver | Core | Runtime BUF |
|---|---|---|---|
Socks |
SocksInbound::serve on socks.load_full(), over WireCounted |
None | n/a |
Http |
drive |
HttpCore::new(config.load_full(), sniff, source) |
HttpCore::<Principal>::BUF_SIZE = MAX_HEAD = 65,536 |
Trojan |
drive |
TrojanCore::new(validator.load_full(), sniff, source) |
16,384 |
Vless |
drive |
VlessCore::new(users.load_full(), sniff, source), over the Vision stream when vision is set |
16,384 |
Vmess |
drive |
VMessCore::new(validator.clone(), now_unix, sniff, source).with_hint(hint), with hint = report.carrier_hint() |
32,768 |
Shadowsocks |
drive |
ShadowsocksCore::new(resolved.load_full(), sniff, source) |
20,480 |
Ss2022 |
drive |
Ss2022Core::with_system_clock(users.config, users.validator, sniff, source), after users.load_full() |
MAX_RECORD_LEN = 65,569 |
Anytls |
drive |
AnyTlsCore::new(users.load_full(), padding.clone(), sniff, source) |
16,384 |
Sss |
serve_sss, boxed (see below) |
SssCore::new(users, max_datagram, sniff, source) once the gate admits the stream |
TCP_BUF_SIZE = 16,384 for a TCP stream, UDP_BUF_SIZE = 67,584 for a UDP one |
Each core is instantiated on Principal, and each BUF_SIZE is an associated constant of the core, passed through as the runtime’s const generic so each protocol gets buffers sized for its largest frame. Shadowsocks 2022’s is the largest record a peer may send: MAX_PACKET_SIZE (65,535) plus RECORD_OVERHEAD (a 2-byte length and two 16-byte tags, 34 bytes). BUF caps each of the runtime’s three buffers per connection (transport read, transport staging, outbound scratch), and none is allocated at that size up front: the read buffer starts small and the staging buffer empty, both growing with the bytes that pass through them, and the scratch buffer is allocated at the first outbound read (concepts/src/runtime.rs → ProxyServerRuntime). So a connection that never gets past its handshake holds only a small read buffer. Three buffers at their cap are 202,752 bytes for an sss UDP stream, 196,608 for HTTP, 196,707 for Shadowsocks 2022, 98,304 for VMess, 61,440 for Shadowsocks, and 49,152 for Trojan, VLESS, AnyTLS and an sss TCP stream. The buffers are described on The server runtime.
Whatever the driver returns, an error is logged at debug with the protocol name and the client address, and an Ok is silent:
vless connection from Some(203.0.113.7) ended: inbound handshake timed out after 10ssocks connection from None ended: client did not complete its request in timeThe sss path
Section titled “The sss path”An sss stream is gated before any runtime exists. serve_sss runs sss::accept(stream, &settings, &users), which wraps the stream in the inbound’s transform chains and reads its header under the header time T_h and the pre-authentication budget. An admitted stream is driven over the decoded side of the chains with a runtime sized for its command, TCP or UDP, so its session counts sss bytes after the transforms are undone. A refused one is logged at debug as <tag>: sss stream from <source> refused: <reason> and drained or handed to the fallback the settings name; it keeps its handshake permit while it drains, as a stream still waiting for its header would, and gives it up for a fallback, which is past the handshake like REALITY’s camouflage. A refusal is never reported to the guard, so the server’s behaviour does not depend on which check failed.
serve_connection boxes the call, because the sss runtime sits over the transform stream as well as the transport, and every other protocol’s connection future would otherwise grow to its size. serve_sss is a plain function returning gate.then(…), not an async fn, so the gate and what follows are two states of one future (an_sss_connections_future_holds_one_runtime_and_little_besides). The gate, the core and the chains are on sss and sss transforms.
The SOCKS path
Section titled “The SOCKS path”SOCKS does not fit a core: its UDP side lives on a second socket that the control connection only keeps alive. It gets its own driver:
impl<T: Send + Sync + 'static> SocksInbound<T> { pub async fn serve<S, C>( &self, stream: S, local_ip: Option<IpAddr>, source: Option<IpAddr>, connector: C, ) -> io::Result<()> where S: AsyncRead + AsyncWrite + Unpin, C: Connector<Flow<T>>, C::Datagram: DatagramLink<Addr = Destination>;}- The driver bounds its whole handshake with its own
tokio::time::timeout(HANDSHAKE_TIMEOUT, …)and fails withclient did not complete its request in time. It then relays aCONNECTor drives aUDP ASSOCIATE; see SOCKS. - No runtime reports what the stream moved, so
serve_connectionwraps it inWireCountedwith the session’s wire, and the SOCKS greeting, authentication and request count toward the session like any other bytes. - The connector is passed as
connector.charging_datagrams(). A UDP association’s datagrams never cross the control stream, so the payload of each datagram its sub-links send or receive is added to the session’s wire instead (Per-user usage accounting).
drive: the handshake watchdog
Section titled “drive: the handshake watchdog”pub trait Established { fn is_established(&self) -> bool; fn user_hint(&self) -> Option<UserHint> { None }}
type Step = Result<Traffic, RuntimeError<io::Error>>;
async fn drive<const BUF: usize, Core, S>( stream: S, make_core: impl FnOnce() -> Core, connector: AppConnector, handshake: Arc<OwnedSemaphorePermit>, report: Report,) -> io::Result<()>where S: AsyncRead + AsyncWrite + Unpin, Core: ProxyCoreDecode<Target = Flow, Error = io::Error, TransportAddr = ()> + Established;drive builds ProxyServerRuntime::<BUF, Core, _, _>::new(stream, make_core(), connector).showing_progress(), a Stream that yields one Traffic delta per unit of work. It needs those yields: between two of them it can ask runtime.core().is_established() and stop watching at the right moment. The core is built inside drive, not handed in: an async fn keeps its arguments in its future for as long as the future lives, so a core passed in would be held twice, once there and once in the runtime (a_connections_future_holds_one_runtime_and_little_besides).
stateDiagram-v2 [*] --> Handshake Handshake --> Handshake: Some(Ok), counted, core not established Handshake --> Relay: core established, handshake permit dropped, report.succeeded(user_hint) Handshake --> TimedOut: no step within HANDSHAKE_TIMEOUT Handshake --> Failed: Some(Err), report.failed() when a credential was refused Handshake --> Ended: None Relay --> Relay: Some(Ok), counted Relay --> Failed: Some(Err) Relay --> Ended: None TimedOut --> [*] Failed --> [*] Ended --> [*]
- Handshake. While the core is not established, each
runtime.next()is wrapped intokio::time::timeout(HANDSHAKE_TIMEOUT, …).Some(Ok(traffic))is counted and the loop goes on.- A timeout returns
io::ErrorKind::TimedOutwithinbound handshake timed out after 10s(the text is built fromHANDSHAKE_TIMEOUT.as_secs()). Some(Err(e))returnsio::Error::other(e.to_string()), so the log shows the runtime’s text. WheneisRuntimeError::Coreof kindio::ErrorKind::PermissionDenied, the core refused the client’s credential (protocols/src/core/mod.rsreserves that kind for a refused credential before establishment), anddrivecallsreport.failed()first.RuntimeErrorprefixes a transport failure withtransport:and a core error withproxy core:(for exampleproxy core: client did not complete its request in time); its other variants are the runtime’s own texts:effect targets an unknown outbound key,open reuses a live outbound key,forward range outside the event slice or held buffer,core consumed an impossible byte count,protocol frame exceeds the read buffer,stream effect on a datagram outbound or vice versaandbytes staged toward a datagram transport without a peer. When each is raised is on The server runtime.Nonemeans the runtime finished before establishing, for example because the client closed or the core refused the request and finished.drivereturnsOk(()).
- Relay. Once the core is established,
drivedrops its handshake permit (handshake.take()on theOptionit holds it in), callsreport.succeeded(runtime.core().user_hint()), and polls the runtime until it ends, counting every step and converting aRuntimeErrorthe same way.
Counting feeds the session: each step’s transport_rx is added to the session’s Wire as up and transport_tx as down, in both phases. Those are the bytes of the protocol stream after its transport, handshake included. What they mean for billing is on Per-user usage accounting.
What established means
Section titled “What established means”Every stream core answers is_established from its Timing (protocols/src/core/mod.rs): true in Phase::Relay and Phase::Closing. A core enters Phase::Relay once its request is parsed and its flow is opening, so established means the request is accepted, not that the outbound is connected. A core still collecting a sniffing prefix (Phase::Sniff, bounded by SNIFF_TIMEOUT, 300 ms) is not established, so the watchdog covers sniffing too.
Two timers, one constant
Section titled “Two timers, one constant”A runtime delivers no event to its core until the client sends something, and a core arms its handshake deadline at its first byte event. A client that connects and says nothing would therefore sit in the runtime forever. drive closes that gap from outside, and the two timers complement each other:
| Timer | Armed by | Measures | Catches |
|---|---|---|---|
drive’s tokio::time::timeout |
Every runtime.next() before establishment |
Time between runtime steps | A client that never speaks, or goes quiet |
The core’s Timing deadline |
The first byte event, once | Time since the request started | A client that keeps sending but never completes its request |
Both use HANDSHAKE_TIMEOUT from protocols/src/core/mod.rs, 10 s.
The Established trait
Section titled “The Established trait”is_established is an inherent method on each core, and a generic function cannot call an inherent method. serve.rs declares Established and implements it with the established! macro, which forwards to the inherent method for HttpCore<Principal>, TrojanCore<Principal>, VlessCore<Principal>, ShadowsocksCore<Principal>, Ss2022Core<Principal>, AnyTlsCore<Principal> and SssCore<Principal>. A new core drive should serve must be added to that list.
user_hint names the user the handshake matched, for the next stream of the same gRPC connection (see The user a gRPC connection last matched). The macro’s cores keep the default, None: they find their users without a hint. VMessCore<Principal> implements the trait by hand, forwarding both methods to its inherent ones; its user_hint() is Some once its auth id has matched.
The authentication guard
Section titled “The authentication guard”supervisor/src/guard.rs turns away clients that keep failing to authenticate. Each supervisor has one Guard, created with the actor and shared with every accept loop through Shared::guard. Every byte stream drive serves ends its handshake in a Report: a credential the core refused (PermissionDenied) counts as a failure, and an established core as a success. Two kinds of connection never reach a Report: a REALITY socket relayed to its cover site, which yields no stream, and an sss stream refused by its gate, which never reaches drive. The guard keeps two counts from those reports, each switched on by a policy. A gRPC connection’s count lives in its Carrier (supervisor/src/carrier.rs), which also keeps the user its last authenticated stream matched:
pub struct Policies { pub user_removal: UserRemovalPolicy, pub drain: DrainPolicy, pub ip_ban: Option<IpBanPolicy>, pub carrier_max_failures: Option<NonZeroU32>,}
pub struct IpBanPolicy { pub max_failures: NonZeroU32, pub window: Duration, pub duration: Duration,}pub(crate) const SWEEP_INTERVAL: Duration = Duration::from_secs(30);
#[derive(Default)]pub(crate) struct Guard { /* carrier_max_failures: AtomicU32, bans: Mutex<Bans> */ }
impl Guard { pub(crate) fn set_policy(&self, policies: &Policies); pub(crate) fn is_banned(&self, ip: IpAddr) -> bool; pub(crate) fn sweep(&self);}
pub(crate) async fn sweep_until(guard: Arc<Guard>, stop: CancellationToken);
pub(crate) struct Report { /* guard, source: Option<IpAddr>, carrier: Option<Arc<Carrier>> */ }
impl Report { pub(crate) fn new(guard: Arc<Guard>, source: Option<IpAddr>, carrier: Option<Arc<Carrier>>) -> Self; pub(crate) fn carrier_hint(&self) -> Option<UserHint>; pub(crate) fn succeeded(&self, user: Option<UserHint>); pub(crate) fn failed(&self);}pub(crate) struct Carrier { failures: AtomicU32, token: CancellationToken, last_user: Mutex<Option<UserHint>>,}
impl Carrier { pub(crate) fn new(token: CancellationToken) -> Self; pub(crate) fn failed(&self) -> u32; pub(crate) fn succeeded(&self, user: Option<UserHint>); pub(crate) fn last_user(&self) -> Option<UserHint>; pub(crate) fn close(&self);}A Report carries the stream’s client IP (source, None over a Unix socket) and, on a gRPC connection, the connection’s Carrier. failed and succeeded update whichever of the two it has. A Carrier is made once per gRPC connection, in Connection::serve_tcp, over the carrier session’s token, and shared by every stream of the connection:
Carrier method |
What it does |
|---|---|
failed |
Adds one to failures and returns the failures in a row so far |
succeeded(user) |
Resets failures to 0; stores user as last_user when it is Some, and keeps the one stored when it is None |
last_user |
The user the last authenticated VMess stream matched, or None before any did |
close |
Cancels the token, which closes the connection |
Bans per client IP
Section titled “Bans per client IP”With Policies::ip_ban set, the guard counts each client IP’s failed authentications. It files them under a BanKey (private to guard.rs), which BanKey::of takes from the client’s address after IpAddr::to_canonical:
| Client address | Counted and banned as |
|---|---|
IPv4, such as 203.0.113.7 |
that address |
IPv4-mapped IPv6, such as ::ffff:203.0.113.7 |
its IPv4 address, 203.0.113.7 |
Any other IPv6, such as 2001:db8:1:2::1 |
the /64 it is in (its first four 16-bit segments), 2001:db8:1:2::/64 |
An IPv6 client picks its addresses within its /64 freely, and privacy addresses rotate on their own, so a count or a ban on one address would end at the next. Every rule below holds for the key: failures from any address in a /64 add to one count, a success from any of them clears it, and a ban turns every one of them away. In the rest of this section, an IP means that key.
- The first failure starts a window. A failure more than
windowafter the window started, or after a ban that is over, starts the count afresh. - The failure that brings the count to
max_failuresbans the IP forduration, logged atinfounder the targetetemenanki_supervisor::guardasbanned <key> for <s>s after <n> failed authentications, where<key>is the IPv4 address or the /64:banned 203.0.113.7 for 300s after 30 failed authentications,banned 2001:db8:1:2::/64 for 300s after 30 failed authentications. A failure from an IP already banned is not counted. - A success clears the IP’s count, but not a ban: a ban runs to its end.
- While an IP is banned,
serve_tcpdrops each new TCP connection from it, accepted or handed over, before the transport handshake (seeConnection::serve_socket), and a WebSocket stream for which a trusted proxy names it right after the upgrade (see The client a trusted proxy names). Connections already open run on.
The records sit in one map behind a lock (parking_lot::Mutex). sweep_until runs Guard::sweep every SWEEP_INTERVAL (30 s), the first time 30 s after start, with MissedTickBehavior::Delay, and drops the record of every IP that is neither banned nor inside its window. SupervisorBuilder::start spawns it with tokio::spawn after the sampler and keeps it among the background tasks, which shutdown stops last, through background_stop.
Failed streams on one gRPC connection
Section titled “Failed streams on one gRPC connection”A gRPC connection carries many streams, and each authenticates on its own. With Policies::carrier_max_failures set, the connection’s Carrier counts its failed streams in a row (Carrier::failed); a success in between resets the count. The failure that reaches the limit calls Carrier::close, which cancels the carrier session’s token and so closes the connection, logged at debug as closing a gRPC connection from <source> after <n> failed streams in a row (the source printed with {:?}). None never closes a connection for this.
The user a gRPC connection last matched
Section titled “The user a gRPC connection last matched”A gRPC connection’s streams are almost always one client’s, so the next VMess stream of a gRPC connection tries the user the connection’s last authenticated stream matched:
drivereports a success asreport.succeeded(runtime.core().user_hint()). For VMess that is aUserHintnaming the matched user, andCarrier::succeededstores it as the connection’slast_user; every other core reportsNone, which keeps the user already stored. A failure keeps it too.- The
Vmessarm ofserve_connectionbuilds its core with.with_hint(report.carrier_hint()).carrier_hintis the carrier’slast_user, andNonefor a stream with no carrier, so a WebSocket, TLS or plain TCP connection’s single stream gets no carrier hint.
The hint only chooses which user’s key the validator tries first. The auth id’s check, the clock check and the replay set decide as they would after a full scan, so a stale or wrong hint never admits another user: the validator goes on to its other guesses and then to every user. A UserHint is opaque: it is Copy and PartialEq, and its Debug prints UserHint(<redacted>), never the user’s UUID. How the validator uses it is on VMess: keys and authentication.
The policy, at commit
Section titled “The policy, at commit”Actor::commit hands every committed spec’s policies to Guard::set_policy, so the guard’s policy changes only when an apply commits; a refused apply leaves it as it was. set_policy stores carrier_max_failures (0 for None) and ip_ban. Turning bans off clears every record, which lifts every ban. Without a ban policy, no failure is counted (without_a_ban_policy_nothing_is_counted). Who sets these policies is on The spec: desired state.
Hysteria 2 listeners
Section titled “Hysteria 2 listeners”A Hysteria 2 inbound owns its UDP socket and QUIC endpoint for as long as its bind is in the spec. Everything inside a QUIC connection, from the credential exchange to the proxy streams and datagrams, is the protocols crate’s; see Hysteria 2: server. This section covers what the supervisor does around it.
pub(crate) async fn run_hysteria_inbound( inbound: Hy2Inbound<Principal>, tag: Arc<ArcSwap<CompactString>>, endpoint: OpenedEndpoint, shared: Shared, stop: CancellationToken,);impl<T> Hy2Inbound<T> { pub fn open(&self, socket: std::net::UdpSocket) -> io::Result<OpenedEndpoint>; pub async fn shutdown(&self);}
impl<T: Send + Sync + 'static> Hy2Inbound<T> { pub async fn run<C, F>(&self, endpoint: OpenedEndpoint, make_connector: F, token: CancellationToken) where F: Fn(IpAddr, ConnectionBytes) -> (C, CancellationToken) + Send + Sync + 'static, C: Connector<Flow<T>> + Clone + Send + 'static, C::Future: Send, C::Stream: Send, C::Datagram: DatagramLink<Addr = Destination> + Send;}
#[derive(Clone)]pub struct ConnectionBytes(quinn::Connection);
impl ConnectionBytes { pub fn bytes(&self) -> (u64, u64);}From prepare to serving
Section titled “From prepare to serving”While the apply is staged, build_handler builds the QUIC server config from the certificate and key; in prepare, listener::bind binds the UDP socket and Pending::pair opens the endpoint on it. So a failure in any of them refuses the apply before anything changes. Once the task started at commit runs, run installs the QUIC server config and records the endpoint under the inbound’s lock. So a set_quic called before that is the config run installs, and one called after it is applied to the running endpoint. run then opens the receive gate and loops over a biased tokio::select!, in this order:
- the token, once: cancelling it switches
runto draining; - a finished connection task, so finished tasks are reaped before new clients pile on;
- the next incoming client.
endpoint.accept()yieldingNonemeans the endpoint has closed, and the loop ends.
Each client takes a place under max_connections through an Admitted guard: a fetch_update on a shared count that succeeds only while fewer than the limit, read at that arrival, are taken. The guard moves into the connection’s task and gives the place back when the task ends. A client that finds no place, or arrives while run is draining, is refused with a QUIC refusal. An admitted connection’s task also records the obfuscation token current at its arrival, which is how set_obfs closes exactly the connections negotiated under the key it replaces. A draining run returns once its last connection task has ended; one whose endpoint closed first waits out the remaining tasks and returns.
One session per QUIC connection
Section titled “One session per QUIC connection”run calls make_connector once per connection, as soon as its QUIC handshake completes, with the client’s IP and a ConnectionBytes. The supervisor’s closure:
- reads the inbound’s current tag from the tag cell. A listener kept across an apply may serve a renamed inbound, so the tag is read per connection;
- opens a session with
Shared::connector(tag, Some(ip), Wire::quic(bytes), &stop)and returns the connector and the session’s token. The connector is cloned for each of the connection’s proxy streams and for its datagram channel, so they are all one session; - when the listener was stopped while the client was in its handshake, returns a connector with no session and a token that is already cancelled. The connection is closed at once, so no session escapes the close of a removed inbound.
Cancelling the returned token closes that one connection with QUIC application error code 0x107 (DISCONNECT_CODE, HTTP/3’s H3_EXCESSIVE_LOAD) and the reason disconnected by the server, and nothing else. A connection closed because the obfuscation changed gets the same code with obfuscation changed.
ConnectionBytes holds the quinn::Connection and reads (udp_rx.bytes, udp_tx.bytes) from its stats: every UDP datagram of the connection, handshake, QUIC framing and TLS included. Wire::quic reads it whenever the session’s bytes are read, so a Hysteria 2 session counts its QUIC connection’s bytes rather than the payload it carried (a_hysteria2_session_bills_its_quic_connections_bytes). Because it holds the connection, it keeps reading the connection’s counts for as long as the session’s wire holds it.
Stopping and shutdown
Section titled “Stopping and shutdown”run_hysteria_inbound runs inbound.run(endpoint, make, stop) and races it against the session registry’s root token:
runreturns first. Cancellingstopmakesrundrain: clients that arrive afterwards are refused, and the connections already served carry on until they end or are closed through their session. When the last one has ended,runreturns, andinbound.shutdown()releases the port.- The root is cancelled first. That happens only at
Supervisor::shutdown, once its grace is over. A client still in its QUIC handshake has no session a root cancel could reach, so the task runsrunandinbound.shutdown()together:shutdowncloses the endpoint under the drainingrun, which ends every connection and handshake on it at once, andrunreturns with them.shutdown_does_not_wait_out_a_stalled_hysteria2_handshakepins that a stalled handshake does not hold shutdown up.
Hy2Inbound::shutdown closes the endpoint with application code 0x100 (CLOSE_CODE) and waits, bounded, for its port to come free; it returns at once when no endpoint is running. Its steps and timeouts are on Hysteria 2: server.
TUN listeners
Section titled “TUN listeners”A TUN inbound owns a layer-3 device. A userspace IP stack in the protocols crate terminates every TCP connection and UDP flow the OS steers into it; see TUN.
pub(crate) async fn run_tun_inbound( handler: TunHandler, prepared: PreparedDevice, restart: mpsc::UnboundedReceiver<(TunHandler, PreparedDevice)>, plane: PlaneCell, flows: Tracker, stop: CancellationToken,);The restart loop
Section titled “The restart loop”The listener keeps the device’s own handle, and each runtime is handed a second handle prepared before the change that started it was committed. run_tun_inbound loops:
- Build the connector factory: for each flow,
AppConnector::new(plane, FlowContext { inbound_tag: tag, source: Some(ip) }, flows, None), whereipis the flow’s source. - Run
handler.inbound.clone().screening_ipv6(ipv6_unreachable(&handler, plane)).run(prepared, make, token)undertoken = stop.child_token(), raced againstrestart.recv(). The screen is described under Inside one runtime. - If a restart arrives, cancel
tokenand wait forrunto return. Ifrunreturns becausestopfired, there is no next runtime. handler.inbound.shutdown().await: wait, polling everyRELEASE_POLL(20 ms) for up toRELEASE_TIMEOUT(3 s), until the old runtime’s device handle has closed and no TCP stream is left. When the wait runs out, it logswarntun: device handle or <n> tcp flows still open after 3sand goes on.- With a restart and
stopnot cancelled, take the new handler and prepared handle and loop. Otherwise return.
So a runtime is cancelled, and its device handle and TCP flows are given up to RELEASE_TIMEOUT to be released, before the next one starts. The restart channel is unbounded, but only the actor writes to it, once per apply that swaps this listener. When the listener is dropped, its sender goes with it, recv returns None, and the loop ends the same way.
Swapping a TUN handler ends the device’s flows, so the plan marks the swap as a disruption, as it does a change of the device itself. etemenanki-app refuses a TUN change on reload; a restart applies it.
Inside one runtime
Section titled “Inside one runtime”TunInbound::run serves one prepared device until its token is cancelled. Each runtime has its own max_flows semaphore, created by run, so a restart starts from a fresh count.
| What the IP stack yields | What run does |
|---|---|
| An IPv6 TCP connection the screen refuses | Answered with a RST to its SYN before the stack sees it, so the client tries its next address at once. See below. |
| A TCP connection | Takes a flow permit with try_acquire_owned, or drops the connection with debug tun: dropping a flow; the flow limit is reached. Serves it through serve_stream over a PassthroughCore (sniffing unless the handler turned it off); an error is logged at debug as tun: tcp flow <src> -> <dst> ended: <error>. |
A UDP flow while udp is off |
Dropped. |
| A UDP flow from a source that has an association | Handed to that association through its bounded channel (FLOW_QUEUE, 16); a flow that finds the channel full is dropped, and the client retransmits. |
| A UDP flow from a new source | Takes a flow permit, or is dropped with the same debug line, and starts that source’s one association: a runtime over TunUdpCore. Its end is logged at trace as tun: udp association of <src> ended: <error>. |
| Any other protocol, ICMP included | Dropped, trace tun: dropping a packet of an unsupported protocol. |
The defaults a front end fills in come from protocols/src/tun/config.rs: DEFAULT_MTU 1500, DEFAULT_UDP_IDLE_TIMEOUT 60 s and DEFAULT_MAX_FLOWS 65,536. The stack, the associations and the TCP tracking are on TUN.
The device screens the IPv6 a client sends before the stack sees it:
- With the inbound’s
ipv6off (TunInbound::without_ipv6), every IPv6 TCP connection is refused and every other IPv6 packet dropped. - With it on, each IPv6 TCP connection is put to the closure
ipv6_unreachablebuilds inserve.rs. It asksPlane::ipv6_unreachableof the plane current when the SYN arrives, with the flow’s context (the inbound tag and the client’s address), whether the inbound sniffs, and the handler’sown_addresses. When no target the route table may send the connection to could reach IPv6, the connection is refused, logged atdebugasinbound <tag>: refusing <src> -> <dst>: no route to IPv6 from any egress it may take. How the plane decides is on The plane: routing each flow.
Flows without sessions
Section titled “Flows without sessions”A TUN device admits no users: its user table is UserTable::None, every flow carries Principal::anonymous(), and the connector has no session. So TUN flows are not listed by Supervisor::sessions, Supervisor::close does not reach them, and they count toward no user’s usage. The flows are still registered and metered in the flow tracker, with no session. TCP flows through the device get their own silent-client watchdog in the protocols crate (serve_stream applies HANDSHAKE_TIMEOUT per step until its PassthroughCore is established and fails with tun: the client never spoke).
Stopping listeners and shutting down
Section titled “Stopping listeners and shutting down”What Listener::stop ends
Section titled “What Listener::stop ends”Listener::stop cancels the listener’s token.
| Listener | What stops | What runs on |
|---|---|---|
| Stream | The accept loop, which drops the listener: the port closes, a Unix or handoff socket file is removed while it is still the one the listener created | Every accepted or handed-over connection, under its session’s token |
| Hysteria 2 | Admission: new clients are refused | Every QUIC connection with a session, until it ends or its session is closed. The endpoint closes, and the port is released, after the last one. |
| TUN | The runtime, whose token is a child of the listener’s: every flow on the device ends with it | Nothing |
Actor::commit stops a listener for Step::StopAccepting, when an inbound was removed or no longer asks for that bind (it moved, or its handoff socket was removed, moved or changed), and removes it from Actor::listeners with swap_remove. The listener is dropped right after, which also drops the TUN device’s own handle, the Hysteria 2 handle the actor held and the stream handler’s watch sender.
The plan decides whether the connections go too:
| Change | Steps | Connections |
|---|---|---|
| Inbound removed | StopAccepting, then CloseSessions |
Closed: Sessions::close(Scope::Inbound(tag)) cancels every session of the tag (removing_an_inbound_closes_its_sessions) |
| Inbound moved to another bind | Bind, StopAccepting |
Not closed by the plan: sessions belong to the tag, which is unchanged |
| Inbound renamed on the same bind | SwapHandler, CloseSessions of the old tag |
The old tag’s sessions are closed; the listener is kept |
| Handoff socket added | Bind of the handoff socket, SwapHandler |
Not closed: the TCP listener keeps its socket, and both listeners serve the new handler |
| Handoff socket removed | SwapHandler, StopAccepting of the handoff socket |
Not closed: the connections it handed over run on |
| Handoff socket moved, or its mode or group changed | Bind of the new one, SwapHandler, StopAccepting of the old one |
Not closed |
For a handoff socket whose mode or group changed, the new socket is moved over the path when it starts, before the old listener stops, and the old listener leaves the path to it (see Publishing at commit).
StopAccepting comes before CloseSessions, and Sessions::open checks the stop token under the same lock the sweep takes, so a connection being accepted as its inbound is removed either is swept or never opens a session.
Actor::commit reports the listener steps in its ApplyReport:
| Field | Filled from |
|---|---|
swapped |
Every SwapHandler |
restarted |
Every Disrupt |
rebound |
A Bind whose tag the running spec already had with another bind of the same kind (its own bind elsewhere, or another handoff socket), each inbound once; a bind for a new tag, or a handoff socket added, is not listed |
removed |
Every CloseSessions |
a_hysteria2_obfuscation_change_needs_allow_disruptive reads these: an allowed obfuscation change lists the inbound in restarted and not in rebound.
Supervisor::shutdown
Section titled “Supervisor::shutdown”Supervisor::shutdown(grace) asks the actor, which:
- stops every listener, and cancels every balancer’s probe token;
- closes the task tracker and waits up to
gracefor every task on it to finish; - cancels the root token. Every session token is its child, so every connection task still running is dropped, and every Hysteria 2 listener closes its endpoint at once;
- waits for the task tracker again, without a limit, and clears
Actor::listeners; - stops the background tasks, the sampler, the guard’s sweep and the usage sink, and awaits them; the sampler and the sink report once more now that every session has ended and folded in its last bytes.
etemenanki-app passes SHUTDOWN_GRACE, 5 s, when it receives SIGTERM or Ctrl-C. When the last Supervisor handle is dropped without a shutdown, the actor runs shutdown(Duration::ZERO) itself. TUN flows get no grace: step 1 stops their runtime.
A removal grace timer (UserRemovalPolicy::CloseAfter) runs on the same task tracker and ends when the root token is cancelled. So a pending removal timer keeps step 2 waiting for the whole grace, and step 3 ends it rather than waiting out its deadline (shutdown_ends_pending_grace_timers).
Adding a stream protocol
Section titled “Adding a stream protocol”A protocol whose server is a ProxyCoreDecode core, served over TCP or a Unix socket, plugs in at these places:
-
Spec. Add a variant to
InboundProtocolSpecinsupervisor/src/topology/spec_plan/inbound.rs, and say inInboundProtocolSpec::transport(), an exhaustive match, whether it runs over a transport. One that does is then built over it and held to the transport rules without more code. -
Validation.
validate_inboundinsupervisor/src/build/validate.rsalready pairs every protocol other than Hysteria 2 and TUN with a TCP or Unix bind, and runs the transport rules, REALITY’s VLESS-only refusal included, for every transporttransport()returns. Add the protocol’s own checks: a required shape, as AnyTLS’sTls, orneeds_userswhen it has no open mode, as Trojan, VLESS, VMess, AnyTLS and sss do. See Validation. -
Credentials. Return the credential kind that admits a user in
credential_kind(supervisor/src/build/users.rs). -
User table. Add a
UserTablevariant, build it inuser_table, and add the pair toUserTable::fitsandUserTable::store_into. -
Handler. Add a
StreamProtocolvariant insupervisor/src/topology/inbound/mod.rsthat holds the table in anArcSwap(or in a type that swaps its own users, as VMess does), name it inStreamProtocol::name, and map the table to it inbuild_handler. -
Serving. Add the core to the
established!list insupervisor/src/serve.rs(or implementEstablishedby hand with auser_hint, as VMess does, if the next stream of a gRPC connection should try the user it matched) and add aserve_connectionarm that callsdrive::<{ NewCore::<Principal>::BUF_SIZE }, _, _>with a closure building the core fromload_full()of the table,sniffandsource, then theconnector, thehandshakepermit and thereport.driverequiresTarget = Flow,Error = io::ErrorandTransportAddr = (), and the core’sis_establishedmust turn true only once the request is parsed and accepted; the existing cores reach that withTiming::enter(Phase::Relay, …). For the guard to count refusals, the core must fail withio::ErrorKind::PermissionDeniedwhen it refuses a credential, and with that kind for nothing else before it is established. -
Disruption. If some setting change cannot spare live connections, add it to
swap_disruptioninsupervisor/src/topology/spec_plan/plan.rs(Planning and applying a change). -
Front ends. Lower the protocol from each front end that should offer it: etemenanki-app in
app/src/lower.rs(etemenanki-app: from TOML to a spec) and katana insrc/lower/inbound.rs(Lowering inbounds and outbounds).
A protocol that cannot be a core, as SOCKS cannot with its second UDP socket, needs its own driver in serve_connection, with its own handshake timeout, and a WireCounted stream so its session still counts its bytes.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
| A refused apply leaves no listener behind, and serves nothing it bound. | Binding and pairing happen in prepare; dropping a Pending closes its socket, removes its staged Unix or handoff file, closes its endpoint or device. Only Listener::start, in commit, serves. |
a_refused_spec_changes_nothing in supervisor/tests/hot_swap.rs |
| A refused apply leaves a running listener’s socket file at its path. | A Unix or handoff socket is bound under a staging name; only Listener::start, in commit, moves it over its path. |
a_refused_apply_keeps_a_running_handoff_socket_at_its_path, a_regroup_whose_chown_is_refused_keeps_the_running_handoff_socket, a_refused_apply_leaves_a_running_socket_that_looks_staged_in_place in supervisor/tests/handoff.rs |
| Each Unix or handoff bind stages its own file, and is served at its own path by its own inbound. | staging_path draws a random name for every bind; bind_staged never binds over or removes an existing file. |
unix_binds_whose_staging_names_could_meet_are_each_served_at_their_path |
| An unchanged bind keeps its socket across an apply. | Listeners are found by BindSpec; a changed inbound gets prepare_swap and swap, never a new bind. |
a_protocol_change_on_the_same_port_keeps_the_socket_and_old_connections, a_hysteria2_obfuscation_change_needs_allow_disruptive (rebound is empty); a_reload_keeps_the_inbound_serving_on_its_udp_port in app/tests/integration/e2e_hysteria_inbound.rs |
| An apply that keeps an inbound and its users does not touch its connections. | Step::Reuse: no swap; a user table is stored for a reused inbound only when its admissions changed (same_admissions). |
an_established_connection_survives_an_apply_that_keeps_its_inbound |
| A new socket is served by the handler current at its accept. | handler.borrow().clone() per accept; swap only replaces the watch value. |
a_protocol_change_on_the_same_port_keeps_the_socket_and_old_connections |
| Stopping a stream listener stops accepting and nothing else. | Session tokens are children of the root, not of the listener. | Plan side: a_bind_change_binds_anew_and_stops_the_old_listener_without_closing_sessions in supervisor/tests/unit/plan.rs. No test moves a listener with a live connection. |
| No session opens on a stopped listener. | Sessions::open checks stop under the registry lock; the accept loop’s select! is biased toward stop. |
a_stopped_listener_opens_no_session in supervisor/tests/unit/session.rs |
| Removing an inbound closes its sessions. | Step::CloseSessions after StopAccepting. |
removing_an_inbound_closes_its_sessions |
| A Unix or handoff listener removes only the socket file it created. | SocketFile compares device and inode before removing. |
Removal: socks_over_a_unix_socket_relays_and_cleans_up in app/tests/integration/e2e_unix.rs; a_handed_over_connection_is_served_with_the_client_its_header_names in supervisor/tests/handoff.rs. The device and inode check has no dedicated test. |
A handoff socket has its mode and group before it listens, in a directory made 0750 when missing. |
bind_handoff sets them between bind and listen. |
a_handoff_socket_takes_over_a_stale_file_and_is_set_up_as_asked |
A handed-over connection is served as one its TCP listener accepted, its client the one the header names, or the socket’s own peer for a LOCAL header. |
serve_socket calls handoff::receive, set_source, then the shared serve_tcp. |
a_handed_over_connection_is_served_with_the_client_its_header_names, tls_grpc_and_vmess_run_over_a_handed_over_connection |
| A handover that breaks the wire contract is refused, and the relay keeps its connection. | adopt checks everything before it takes the socket; every descriptor received is an OwnedFd. |
a_malformed_handoff_is_refused_and_the_connection_stays_the_relays |
| A handed-over client is held to the bans as a direct one is. | serve_tcp checks is_banned and reports with the header’s client. |
a_handed_over_client_failing_to_authenticate_is_banned |
| Adding, moving, changing or removing a handoff socket keeps the TCP listener and every connection. | Each bind is planned on its own; every listener of an inbound serves its one handler. | a_reload_adds_moves_and_removes_a_handoff_socket_and_keeps_the_tcp_listener; plan side in supervisor/tests/unit/plan.rs |
| An inbound’s listeners count against one set of admission caps, and a listener added beside a kept one joins its pool. | caps_for in Actor::prepare; ListenerKind::Stream keeps the caps across swaps. |
an_inbounds_listeners_share_one_set_of_caps in supervisor/tests/unit/supervisor.rs |
| The accept loop never waits for a permit. | try_acquire_owned; a socket turned away is refused (AcceptedSocket::refuse) and dropped. |
No dedicated test |
| A persistent accept error does not spin the loop, and a per-client one does not slow it. | should_backoff_accept_error and ACCEPT_ERROR_BACKOFF |
accept_error_backoff_classification in supervisor/tests/unit/serve.rs |
| A client that never completes its request is disconnected. | drive’s per-step HANDSHAKE_TIMEOUT until established, and the core’s Timing deadline |
The core side: timing_arms_handshake_once_then_idle_per_byte_event in protocols/tests/unit/core/mod.rs, and per-core tests such as handshake_deadline_fails_the_connection in protocols/tests/unit/trojan/core.rs. drive’s own timeout has no test. |
| A session’s wire counts what its client’s side carried. | drive adds each step’s transport bytes; WireCounted and charged datagrams for SOCKS; Wire::quic for Hysteria 2 |
mux_sub_flows_and_their_session_count_exactly_what_moved, a_udp_association_counts_each_sub_link_and_charges_its_session, a_hysteria2_session_bills_its_quic_connections_bytes in supervisor/tests/tracking.rs |
| Routing sees the inbound tag and the client address captured at accept. | FlowContext built by connector_for and Shared::connector |
inbound_tag_selects_the_route, source_cidr_matches_the_client_address in app/tests/integration/e2e_route_context.rs |
| On an inbound that reads PROXY headers, a connection’s client is the one its header names, and a connection without one is its peer’s own. | serve_socket reads the header before the transport and records it with Session::set_source before any flow binds the session. |
a_proxy_header_names_the_client_and_a_bare_connection_is_its_own in supervisor/tests/guard.rs |
On a WebSocket inbound with real_ip, a trusted proxy’s header names the client, and anyone else’s header is ignored. |
real_ip_source takes the header only when RealIpSpec::trusts the connection’s client. |
a_trusted_proxys_forwarded_header_names_the_websocket_client, a_forwarded_header_from_anyone_untrusted_is_ignored in supervisor/tests/guard.rs; a_trusted_proxys_header_names_the_client_and_no_one_elses_does in supervisor/tests/unit/serve.rs |
| A client a trusted proxy names is held to the bans and the device limit as a direct one is. | The sink checks is_banned on the named client, records it with Session::set_source before the session binds, and hands it to the connector and the Report. |
the_device_limit_counts_the_forwarded_client, a_forwarded_client_failing_to_authenticate_is_banned_and_others_are_not in supervisor/tests/guard.rs |
| An IP that keeps failing to authenticate is turned away, and other IPs are not. | Guard counts per IP; serve_tcp checks is_banned before the transport handshake. |
an_ip_failing_to_authenticate_is_turned_away_and_others_are_not in supervisor/tests/guard.rs; the counting rules in supervisor/tests/unit/guard.rs |
| An IPv6 client is counted, cleared and banned by its /64, and an IPv4-mapped address as its IPv4 address. | BanKey::of keys every failure, success and ban check. |
an_ipv6_client_is_counted_and_banned_by_its_64, a_success_anywhere_in_the_64_clears_its_count, an_ipv4_mapped_address_counts_as_its_ipv4 in supervisor/tests/unit/guard.rs |
| A gRPC connection whose streams keep failing is closed. | Carrier::close cancels the carrier session’s token at carrier_max_failures failures in a row. |
a_grpc_connection_whose_streams_keep_failing_is_closed in supervisor/tests/guard.rs; a_carrier_is_closed_after_failed_streams_in_a_row |
| A gRPC connection hands the user its last authenticated stream matched to its next VMess stream; a failure, or a core that names no user, keeps the one stored, and a stream without a carrier gets none. | Carrier::succeeded, Report::carrier_hint |
a_carrier_hands_its_last_user_to_the_next_stream in supervisor/tests/unit/guard.rs |
| A VMess listener’s hot tier is refreshed once it is due, at most once a second, off the runtime, and the refresher ends with its listener. | refresh_hot_tiers polls every HOT_TIER_POLL and returns on stop; refresh_hot_tier prepares on the blocking pool. |
a_due_hot_tier_is_refreshed_by_the_listener in supervisor/tests/unit/serve.rs |
| A connection task holds its future once, and a future under a cancelled token never starts. | until_cancelled is a combinator; drive builds its core itself. |
a_connections_future_holds_one_runtime_and_little_besides, a_spawned_connection_is_no_bigger_than_its_future, until_cancelled_never_starts_a_future_under_a_cancelled_token in supervisor/tests/unit/serve.rs |
| An sss connection’s future holds one runtime, and other protocols’ connections do not grow with it. | serve_sss is two states of one future, and serve_connection boxes it. |
an_sss_connections_future_holds_one_runtime_and_little_besides in supervisor/tests/unit/serve.rs |
| A REALITY socket relayed to the cover site gives its handshake permit back, keeps its live permit until the relay ends, is never reported to the guard, and ends with its session. | serve_tcp drops the handshake permit before relay.run, inside the task under the carrier session’s token. |
a_camouflaged_connection_gives_its_handshake_permit_back in supervisor/tests/unit/serve.rs |
| An sss stream refused before authentication is never reported to the guard. | serve_sss runs the rejection without a Report call. |
a_probe_gets_silence_until_it_closes, a_probe_is_handed_to_the_fallback in supervisor/tests/sss.rs (the behaviour; no test sets a ban policy) |
| An AnyTLS connection is one session for all its streams, and a wrong password counts toward the IP ban. | drive over AnyTlsCore, which refuses with PermissionDenied |
streams_of_one_session_count_exactly_toward_its_user, a_wrong_password_counts_toward_the_ip_ban in supervisor/tests/anytls.rs |
| A Hysteria 2 listener never serves two endpoints on one port. | Changes are applied inside the running endpoint by its setters. | a_reload_keeps_the_inbound_serving_on_its_udp_port; switching_the_obfuscation_closes_the_old_clients_and_admits_new_ones in protocols/tests/pipeline/hysteria.rs |
| Shutdown is bounded by its grace, Hysteria 2 handshakes included. | The root cancel runs Hy2Inbound::shutdown under the draining run. |
shutdown_does_not_wait_out_a_stalled_hysteria2_handshake |
| A TUN runtime is cancelled, and its device handle and TCP flows given up to 3 s to be released, before the next one starts. | run_tun_inbound awaits run and then TunInbound::shutdown before it loops. |
No dedicated test |
Failure paths and cancellation
Section titled “Failure paths and cancellation”| What happens | Where | Result | Log |
|---|---|---|---|
| A TCP or UDP address is in use or not allowed | listener::bind |
ApplyError::Bind; the apply changes nothing |
The front end’s report, for example etemenanki-app’s failed to start: inbound <tag>: binding <bind> failed: <OS error> |
| A Unix path holds something other than a socket | listener::bind |
ApplyError::Bind |
… failed: <path> exists and is not a socket |
Every staging name drawn for a Unix or handoff bind is taken, STAGING_ATTEMPTS (16) times |
bind_staged |
ApplyError::Bind |
… failed: no free name to stage <path> under |
| A handoff socket’s directory cannot be created, or its mode or group cannot be set | bind_handoff |
ApplyError::Bind; the staged socket file, if it was bound, is removed, and a running socket at the path stays |
inbound <tag>: binding handoff:<path> failed: <error> |
| A TUN device cannot be created, addressed or routed | tun::open |
ApplyError::Bind |
The OS error, route <net>/<prefix>: <error> for a route, or on Windows creating a Wintun adapter (needs wintun.dll beside the executable, and an elevated process): <error> |
| A Unix bind off Unix | listener::bind |
ApplyError::Bind; validation refuses it first with unix sockets are not served on <os> |
unix socket <path>: not served on this platform |
| A handoff socket off Unix | listener::bind |
ApplyError::Bind; validation refuses it first with handoff sockets are not served on <os> |
unix socket <path>: not served on this platform |
| A certificate or key that does not parse | build_handler |
ApplyError::Build |
building inbound <tag> failed: <error>, for example hysteria2: the certificate file contains no certificates |
| A handler or table of the wrong kind | Pending::pair, prepare_swap, UserTarget::prepare |
ApplyError::Build (unreachable after validation) |
building inbound <tag> failed: the handler is not of the kind its listener serves |
A Salamander key shorter than MIN_PSK_LEN (4 bytes) |
check_obfs |
ApplyError::Build; validation refuses it first with salamander obfs key must be at least 4 bytes |
malformed: hysteria2 obfs psk is too short |
| The Hysteria 2 endpoint cannot be created on the socket | Hy2Inbound::open (from_socket, quinn’s endpoint) |
ApplyError::Build |
building inbound <tag> failed: <error> |
| A TUN device handle cannot be registered with the runtime, or the stack refuses its MTU | TunInbound::prepare, from Pending::pair or prepare_swap |
ApplyError::Build; the MTU case is unreachable after validation |
building inbound <tag> failed: <error> |
| The listener’s TUN device handle cannot be cloned for a swap | prepare_swap (try_clone) |
ApplyError::Build |
building inbound <tag> failed: <error> |
accept fails with ConnectionAborted or Interrupted |
run_stream_inbound |
Accepts again at once | debug accept error: <error> |
accept fails otherwise |
run_stream_inbound |
Sleeps 100 ms, or ends if stopped meanwhile | warn accept error, backing off 100ms: <error> |
| Live or handshake semaphore empty | run_stream_inbound |
Socket turned away (AcceptedSocket::refuse) and dropped |
debug dropping inbound connection; live connection limit reached or … handshake limit reached |
| The listener stops as a socket is accepted | Sessions::open returns None |
Loop ends; socket turned away and dropped | None |
| A PROXY header cannot be read, for example a malformed one | serve_socket |
Socket and session dropped | debug dropping a connection from <peer>: <error> |
| No PROXY header is complete within 10 s | serve_socket |
Socket and session dropped | None |
| A relay’s control connection closes without sending anything | handoff::receive |
Not answered; session dropped | None |
| No handover message within 5 s | handoff::receive |
Not answered; control connection and session dropped | debug handoff: no message within 5s |
| Reading the handover message fails | handoff::receive |
Not answered; control connection and session dropped | debug handoff: reading the message failed: <error> |
| A handover the supervisor cannot take: a descriptor count other than one, a malformed or trailing header, a socket that is not a connected TCP one | handoff::adopt |
0x01; the descriptors received are closed; control connection and session dropped |
debug handoff: refused: <reason> |
| The relay cannot be answered | handoff::answer |
The socket is served, or dropped, all the same | debug handoff: the relay was not answered: <error> |
| A TCP connection, accepted or handed over, comes from a banned IP | serve_tcp (Guard::is_banned) |
Socket and session dropped before the transport handshake | None |
The failed authentications of an IP, or of an IPv6 client’s /64, reach max_failures within window |
Report::failed → Guard |
The IP or the /64 is banned for duration |
info banned <key> for <s>s after <n> failed authentications, the key an IPv4 address or a /64 such as 2001:db8:1:2::/64 |
carrier_max_failures streams of one gRPC connection fail in a row |
Report::failed → Carrier::close |
The carrier session’s token is cancelled; the connection closes | debug closing a gRPC connection from <source> after <n> failed streams in a row |
| Transport handshake fails or takes over 10 s | serve_tcp |
Socket and session dropped | debug inbound transport failed: <error> |
| A REALITY socket is not a client of ours | serve_tcp, on Disposition::Camouflage |
Handshake permit dropped; relayed to the cover site until both sides close, 300 s pass idle, or the session is closed | debug <tag>: <source> goes to dest: <reason>, then on an error <tag>: relay to dest ended: <error> |
| A Vision inbound’s stream is not a REALITY stream | the sink in serve_tcp (into_vision_server) |
Stream dropped (unreachable after validation) | debug <tag>: vision setup failed: vless vision rides only over reality |
| An sss stream fails before authentication | serve_sss |
Drained, or relayed to the fallback; never reported to the guard | debug <tag>: sss stream from <source> refused: <reason> |
| A trusted proxy sends no real-IP header, or one that is not a list of addresses | real_ip_source |
The proxy is served as the client | debug trusted proxy <ip> sent no <header> header; serving it as the client, or … sent a <header> header that lists no addresses; serving it as the client |
| The client a trusted proxy names is banned | the sink in serve_tcp (Guard::is_banned) |
Stream, socket and session dropped before the protocol runs | None |
| No runtime step for 10 s before establishment | drive |
TimedOut |
debug <protocol> connection from <source> ended: inbound handshake timed out after 10s |
| A request not complete 10 s after its first byte | The core | Runtime error | debug … ended: proxy core: client did not complete its request in time |
| SOCKS handshake not complete in 10 s | SocksInbound::serve |
TimedOut |
debug socks connection from <source> ended: client did not complete its request in time |
| Any other runtime or driver error | drive, SocksInbound::serve |
Connection dropped | debug <protocol> connection from <source> ended: <error> |
| A session’s token is cancelled (see Tokens and tasks) | until_cancelled |
The task’s future is dropped | None |
| A Hysteria 2 QUIC handshake fails | Hy2Inbound::run |
Connection dropped | debug hysteria2: a handshake failed: <error> |
| A Hysteria 2 client arrives at the limit or while draining | Hy2Inbound::run |
QUIC refusal | debug hysteria2: refusing a connection; the listener is full or stopping |
| A Hysteria 2 connection’s transport parameters cannot be built | Hy2Inbound::run (endpoint::for_connection) |
QUIC refusal | warn hysteria2: refusing a connection: <error> |
| The Hysteria 2 port is still held 3 s after the endpoint closed | Hy2Inbound::shutdown |
Returns anyway | warn hysteria2: <address> did not come free within 3s |
| An IPv6 TCP connection on a TUN device that no egress could reach | the runtime’s IPv6 screen, asking Plane::ipv6_unreachable |
RST to the SYN | debug inbound <tag>: refusing <src> -> <dst>: no route to IPv6 from any egress it may take |
| A TUN runtime’s device handle or TCP flows outlive 3 s | TunInbound::shutdown |
The loop goes on | warn tun: device handle or <n> tcp flows still open after 3s |
| A TUN swap finds the runtime task ended | Listener::swap |
A new runtime task is spawned on the prepared duplicate | None |
| A staged Unix or handoff socket cannot be moved over its path | SocketFile::publish, in Listener::start |
The commit goes on; the listener’s file stays under its staging name | error could not move <staged> over <path>, so no one reaches the listener there: <error> |
| A Unix socket file cannot be removed | SocketFile::drop |
Ignored | debug could not remove <path>: <error> |
The serve.rs lines are logged under the target etemenanki_supervisor::serve, the listener lines under etemenanki_supervisor::system::listener, the handover lines under etemenanki_supervisor::system::handoff and the guard’s under etemenanki_supervisor::guard. Nothing in serve.rs or handoff.rs logs a single connection above debug.
For a stream connection, cancellation is by drop. When a session’s token fires, until_cancelled drops the connection’s future at whatever .await it is parked on: the client socket closes, the runtime and every outbound it opened are dropped, the connection’s permit handles are dropped, and the last Arc<Session> handle deregisters the session and folds its last bytes into its user’s account. No protocol-level goodbye is sent. Protocol and transport code must therefore keep its cleanup in Drop, never after an .await. A Hysteria 2 session is closed by the protocols crate instead, with DISCONNECT_CODE (see One session per QUIC connection).
Limits
Section titled “Limits”| Constant | Value | Defined in | Scope |
|---|---|---|---|
MAX_LIVE_CONNECTIONS_PER_INBOUND |
4,194,304 | supervisor/src/serve.rs |
Per stream inbound: one pool its TCP listener and handoff socket share, kept while either listener is kept; an apply that keeps neither starts a new one |
MAX_HANDSHAKES_PER_INBOUND |
204,800 | supervisor/src/serve.rs |
Per stream inbound, as above |
ACCEPT_ERROR_BACKOFF |
100 ms | supervisor/src/serve.rs |
Per accept error that backs off |
PROXY_HEADER_TIMEOUT |
10 s | supervisor/src/serve.rs |
Reading a PROXY protocol v2 header, on an inbound with proxy_protocol |
RECEIVE_TIMEOUT |
5 s | supervisor/src/system/handoff.rs |
How long a relay’s control connection may stay silent before its message |
MAX_V2_LEN |
4,096 bytes | protocols/src/transports/proxy_protocol.rs |
The longest PROXY protocol v2 header taken, TLVs included |
MAX_SOCKET_PATH |
107 bytes | supervisor/src/build/validate.rs |
The longest handoff socket path (sun_path holds 108 bytes with its NUL), and the longest staged path staging_path draws |
STAGING_ATTEMPTS |
16 | supervisor/src/system/listener.rs |
Staging names one Unix or handoff bind tries before it fails |
| Handoff socket backlog | SOMAXCONN |
supervisor/src/system/listener.rs → bind_handoff |
Control connections waiting to be accepted |
HOT_TIER_POLL |
1 s | supervisor/src/serve.rs |
How often a stream listener asks its VMess validator whether the hot tier is due a refresh |
MAX_REAL_IP_ADDRESSES |
32 | protocols/src/transports/ws/endpoint.rs |
The most addresses a real-IP header may list before it is Malformed |
SWEEP_INTERVAL |
30 s | supervisor/src/guard.rs |
How often the guard drops the records of IPs neither banned nor inside their window |
HANDSHAKE_TIMEOUT |
10 s | protocols/src/core/mod.rs |
drive‘s per-step watchdog, the cores’ Timing, the SOCKS handshake, TUN TCP flows |
RELAY_IDLE_TIMEOUT |
300 s | protocols/src/core/mod.rs |
A REALITY camouflage relay’s idle limit |
TRANSPORT_HANDSHAKE_TIMEOUT |
10 s | protocols/src/transports/accept.rs |
An inbound’s TLS handshake, WebSocket upgrade and HTTP/2 handshake (InboundTransport::accept), and REALITY’s decision |
SNIFF_TIMEOUT |
300 ms | protocols/src/sniff/mod.rs |
The sniffing window, inside the handshake phase |
Core BUF_SIZE |
16,384 to 67,584 bytes | each core | The cap of each of three buffers per stream connection |
DEFAULT_MAX_CONNECTIONS |
262,144 | protocols/src/hysteria/server/config.rs |
Front ends’ default for a Hysteria 2 inbound’s max_connections |
DEFAULT_MAX_CIRCUITS |
4,194,304 | protocols/src/hysteria/server/config.rs |
Front ends’ default for max_circuits |
CLOSE_CODE, DISCONNECT_CODE |
0x100, 0x107 |
protocols/src/hysteria/server/inbound.rs |
QUIC application codes: endpoint closed, one connection closed |
MIN_PSK_LEN |
4 bytes | protocols/src/hysteria/obfs.rs |
Shortest Salamander key check_obfs and Hy2Inbound::open accept |
RELEASE_TIMEOUT, RELEASE_POLL |
3 s, 20 ms | protocols/src/tun/inbound.rs |
Each TUN runtime’s shutdown |
DEFAULT_MTU, DEFAULT_UDP_IDLE_TIMEOUT |
1500, 60 s | protocols/src/tun/config.rs |
Front ends’ defaults for a TUN inbound’s mtu and udp_idle_timeout |
DEFAULT_MAX_FLOWS |
65,536 | protocols/src/tun/config.rs |
Front ends’ default for a TUN inbound’s max_flows, per runtime |
FLOW_QUEUE |
16 | protocols/src/tun/udp.rs |
New UDP flows queued toward one TUN association |
MIN_TUN_MTU |
1280 | supervisor/src/build/validate.rs |
Smallest TUN MTU a spec may name; the IP stack’s own floor |
SHUTDOWN_GRACE |
5 s | app/src/main.rs |
etemenanki-app’s grace for Supervisor::shutdown |
None of the serve.rs, handoff.rs or guard.rs constants is configurable. A Hysteria 2 inbound’s max_connections and max_circuits must be at least 1. An IpBanPolicy’s max_failures and carrier_max_failures are NonZeroU32. The limits across the whole workspace are collected on Limits, timeouts and memory.
| Test | File | What it pins |
|---|---|---|
accept_error_backoff_classification |
supervisor/tests/unit/serve.rs |
Interrupted and ConnectionAborted do not back off; OutOfMemory and Other do. |
a_connections_future_holds_one_runtime_and_little_besides |
supervisor/tests/unit/serve.rs |
serve_connection’s future is at most 1 KiB larger than the VMess runtime inside it, so the core is not held twice. |
an_sss_connections_future_holds_one_runtime_and_little_besides |
supervisor/tests/unit/serve.rs |
serve_sss’s future is at most 1 KiB larger than the sss UDP runtime: the gate, both runtimes and a refusal’s drain are states of one future. |
a_camouflaged_connection_gives_its_handshake_permit_back |
supervisor/tests/unit/serve.rs |
Two HTTP requests to a REALITY inbound are echoed by its cover site; every handshake permit is back and two live permits are held; an IP-ban policy of one failure bans neither client; cancelling the sessions ends both relays and frees the live permits. |
streams_of_one_session_count_exactly_toward_its_user, a_wrong_password_counts_toward_the_ip_ban, removing_the_user_ends_the_session_and_every_stream, a_padding_change_leaves_live_sessions_alone |
supervisor/tests/anytls.rs |
Three AnyTLS streams ride one session of the user, who is charged its bytes; three wrong passwords from one client named by a PROXY header ban it, another client is served; removing a user ends their session and every stream on it; a padding change leaves a live session on its scheme and pushes the new one to a new session. |
an_sss_outbound_carries_tcp_and_udp_to_an_sss_inbound, mismatched_chains_carry_nothing, a_probe_gets_silence_until_it_closes, a_probe_is_handed_to_the_fallback |
supervisor/tests/sss.rs |
sss end to end between two supervisors; chains that do not match carry nothing; a probe is drained in silence, or handed to the fallback. |
a_spawned_connection_is_no_bigger_than_its_future |
supervisor/tests/unit/serve.rs |
until_cancelled adds at most 256 bytes to the future it wraps. |
until_cancelled_ends_a_pending_future_and_drops_it, until_cancelled_lets_a_finishing_future_finish, until_cancelled_never_starts_a_future_under_a_cancelled_token |
supervisor/tests/unit/serve.rs |
A cancel ends and drops a pending future (None); a finished future returns Some(()); a future under a cancelled token never runs. |
a_due_hot_tier_is_refreshed_by_the_listener |
supervisor/tests/unit/serve.rs |
With 100 VMess users, matches of the last user make the hot tier due; refresh_hot_tiers clears it within five polls, and returns within one poll of stop. |
a_trusted_proxys_header_names_the_client_and_no_one_elses_does |
supervisor/tests/unit/serve.rs |
real_ip_source with X-Forwarded-For and trusted 127.0.0.0/8 and 10.0.0.0/8: a lone address, the rightmost untrusted one of a list, the leftmost when every one is trusted, the proxy for Missing and Malformed, an IPv4-mapped proxy address taken as IPv4, and the client unchanged for an untrusted source or none. |
a_proxy_header_names_the_client_and_a_bare_connection_is_its_own |
supervisor/tests/guard.rs |
On a VLESS inbound reading PROXY headers, a connection sent with a header has the header’s client as its session’s source, and a connection without one has its peer. |
a_trusted_proxys_forwarded_header_names_the_websocket_client |
supervisor/tests/guard.rs |
On a VLESS-over-WebSocket inbound trusting 127.0.0.0/8, the sessions’ sources are the forwarded IPv4 client, the untrusted entry of a list, a mapped address as IPv4, an IPv6 client, and the proxy for a missing or malformed header. |
a_forwarded_header_from_anyone_untrusted_is_ignored |
supervisor/tests/guard.rs |
Trusting 10.0.0.0/8, a header sent by a client outside it is ignored and that client is the session’s source; a trusted proxy’s header names the client. |
the_device_limit_counts_the_forwarded_client |
supervisor/tests/guard.rs |
With a device limit of 1, a second connection forwarded for the same IP is served, and one forwarded for another IP is refused. |
a_forwarded_client_failing_to_authenticate_is_banned_and_others_are_not |
supervisor/tests/guard.rs |
After three refused ids forwarded for one IP, that IP is not served even with the right id; another IP behind the same proxy is, and so is the proxy itself. |
an_ip_failing_to_authenticate_is_turned_away_and_others_are_not |
supervisor/tests/guard.rs |
After three refused ids from one IP, that IP is not served even with the right id; another IP is. |
a_grpc_connection_whose_streams_keep_failing_is_closed |
supervisor/tests/guard.rs |
With carrier_max_failures 3, three streams with an unknown id close the HTTP/2 connection. |
a_users_sessions_come_from_no_more_ips_than_their_device_limit |
supervisor/tests/guard.rs |
The device limit counts the client a PROXY header names (see Users, principals and sessions). |
an_ip_is_banned_at_the_limit_and_until_the_ban_ends, failures_outside_the_window_start_a_new_count, a_success_clears_the_count_but_not_a_ban, a_sweep_drops_what_no_longer_counts, without_a_ban_policy_nothing_is_counted, a_carrier_is_closed_after_failed_streams_in_a_row |
supervisor/tests/unit/guard.rs |
The guard’s counting on paused time: the ban at the limit and its end, the window, a success clearing the count but not a ban, the sweep, turning bans off, and the gRPC count reset by a success. |
an_ipv6_client_is_counted_and_banned_by_its_64, a_success_anywhere_in_the_64_clears_its_count, an_ipv4_mapped_address_counts_as_its_ipv4 |
supervisor/tests/unit/guard.rs |
Three failures from three addresses of 2001:db8:1:2::/64 ban a fourth address in it but not 2001:db8:1:3::1, and the key displays as 2001:db8:1:2::/64; in 2001:db8::/64, a success from a third address clears the count two failures built, and three failures after it, each from an address of its own, ban the /64; failures from ::ffff:203.0.113.7 ban 203.0.113.7 and not ::ffff:203.0.113.8. |
a_carrier_hands_its_last_user_to_the_next_stream |
supervisor/tests/unit/guard.rs |
A carrier hints nobody at first, then the user of the last success; a failure and a success naming no user keep it, the latest user wins, and a report without a carrier hints nobody. |
a_handed_over_connection_is_served_with_the_client_its_header_names |
supervisor/tests/handoff.rs |
On a VLESS inbound with a handoff socket, a handover whose header names 203.0.113.7 and one with a LOCAL header are each answered 0x00, closed and served, and the TCP listener serves a direct client beside them. The sessions’ sources are the named client, and the loopback peer for the LOCAL handover and the direct client; the socket file is gone after shutdown. |
a_malformed_handoff_is_refused_and_the_connection_stays_the_relays |
supervisor/tests/handoff.rs |
No descriptor, two, a UDP, a Unix or a listening socket, bytes after the header, one byte after a header of the full MAX_V2_LEN (filled out with a NOOP TLV), a wrong version and a header cut short are each answered 0x01 and closed; the relay’s connection still carries bytes both ways; a control connection closed without a message is not answered, and the next handover is taken. |
a_handed_over_client_failing_to_authenticate_is_banned |
supervisor/tests/handoff.rs |
After three handovers naming one client fail authentication, a fourth naming it is taken and then dropped even with the right id; one naming another client is served. |
tls_grpc_and_vmess_run_over_a_handed_over_connection |
supervisor/tests/handoff.rs |
A relay hands every connection over to a VMess-over-gRPC-and-TLS inbound; two flows, one of 100,000 bytes, echo, and every session’s source is the client the relay named. |
a_refused_apply_keeps_a_running_handoff_socket_at_its_path |
supervisor/tests/handoff.rs |
An apply that changes the socket’s mode and adds an inbound on a port already taken is refused with Bind; the running socket still accepts at its path with its old mode 0660, and the directory holds nothing else. |
a_regroup_whose_chown_is_refused_keeps_the_running_handoff_socket |
supervisor/tests/handoff.rs |
A change of gid to group 0, whose chown the process may not make, is refused with Bind; the running socket still accepts at its path, and the directory holds nothing else. Skipped as root or as a member of group 0. |
unix_binds_whose_staging_names_could_meet_are_each_served_at_their_path |
supervisor/tests/handoff.rs |
Two VLESS inbounds on Unix sockets in one directory, once at paths that differ only in their last byte and once with one path a dot-file beside the other: each socket is at its own path, nothing is left staged, and a client at each path opens a session of that path’s inbound. |
a_refused_apply_leaves_a_running_socket_that_looks_staged_in_place |
supervisor/tests/handoff.rs |
A running Unix socket whose name is a dot-file stays in place and reachable when an apply that would stop it and bind another socket beside it is refused by a later bind, and the directory holds nothing else. |
a_reload_adds_moves_and_removes_a_handoff_socket_and_keeps_the_tcp_listener |
supervisor/tests/handoff.rs |
Adding a handoff socket is swapped with no rebound; moving it is rebound and removes the old file; a mode change binds it afresh at the same path; removing it removes the file. A direct connection and every handed-over one keep relaying throughout. |
a_handoff_socket_takes_over_a_stale_file_and_is_set_up_as_asked |
supervisor/tests/handoff.rs |
The missing directory is 0750 and the socket 0660, both in the given group; a stale socket file at the path is replaced; a regular file there refuses the start with Bind and is left alone. |
an_inbounds_listeners_share_one_set_of_caps |
supervisor/tests/unit/supervisor.rs |
caps_for returns the kept listener’s caps whichever bind keeps it, and new caps, different each time, when none is kept. |
a_stopped_listener_opens_no_session |
supervisor/tests/unit/session.rs |
Sessions::open with a cancelled stop token returns None and registers nothing. |
cancelling_the_root_cancels_every_session |
supervisor/tests/unit/session.rs |
Every session token is a child of the root. |
an_established_connection_survives_an_apply_that_keeps_its_inbound |
supervisor/tests/hot_swap.rs |
An apply that adds an outbound and a rule reports the inbound as reused, swaps and rebinds nothing, and a live SOCKS relay keeps echoing. |
a_protocol_change_on_the_same_port_keeps_the_socket_and_old_connections |
supervisor/tests/hot_swap.rs |
SOCKS to HTTP on one port is a swap with no rebind; an old relay keeps working, a new client speaks HTTP, and a socket accepted before the apply is answered as SOCKS. |
a_refused_spec_changes_nothing |
supervisor/tests/hot_swap.rs |
A bind failure on one new inbound releases another bound in the same prepare; the plane, users and listeners are as before. |
removing_an_inbound_closes_its_sessions |
supervisor/tests/hot_swap.rs |
The removed inbound’s connection closes and its port refuses; the other inbound’s connection is untouched. |
a_hysteria2_obfuscation_change_needs_allow_disruptive |
supervisor/tests/hot_swap.rs |
Refused with ApplyError::Disruptive by default; with allow_disruptive the inbound is in restarted and not in rebound. |
shutdown_does_not_wait_out_a_stalled_hysteria2_handshake |
supervisor/tests/hot_swap.rs |
shutdown(Duration::ZERO) finishes within 5 s while a client’s QUIC handshake is stuck. |
shutdown_ends_pending_grace_timers |
supervisor/tests/hot_swap.rs |
shutdown(Duration::ZERO) does not wait out an hour-long removal grace, and the session it spared is closed. |
mux_sub_flows_and_their_session_count_exactly_what_moved |
supervisor/tests/tracking.rs |
drive feeds the session exactly the bytes the socket carried. |
a_udp_association_counts_each_sub_link_and_charges_its_session |
supervisor/tests/tracking.rs |
WireCounted counts the SOCKS greeting, authentication and request, and charged datagrams add their payload. |
a_hysteria2_session_bills_its_quic_connections_bytes |
supervisor/tests/tracking.rs |
A Hysteria 2 session counts more than its 20,000-byte payload each way: the QUIC connection’s UDP bytes. |
a_protocol_change_on_the_same_bind_swaps_the_handler_and_keeps_the_listener, a_bind_change_binds_anew_and_stops_the_old_listener_without_closing_sessions, a_removed_inbound_stops_accepting_and_closes_its_sessions, an_inbound_renamed_on_the_same_bind_swaps_and_closes_the_old_tags_sessions |
supervisor/tests/unit/plan.rs |
Which steps each kind of inbound change plans for its listener and sessions. |
an_inbound_with_a_handoff_socket_binds_both_listeners, adding_or_removing_a_handoff_socket_keeps_the_tcp_listener, a_changed_handoff_socket_is_bound_anew, a_removed_inbound_stops_its_handoff_socket_too, a_handoff_socket_passed_to_another_inbound_is_kept |
supervisor/tests/unit/plan.rs |
Each bind of an inbound planned on its own: both bound before the build, a socket added or removed beside a kept TCP listener, a moved or regrouped socket bound anew, both stopped with a removed inbound, and a socket another inbound takes over kept and swapped. |
a_tun_settings_change_on_the_same_device_swaps_and_disrupts, a_hysteria2_obfs_change_swaps_and_disrupts, a_hysteria2_masquerade_change_swaps_without_disrupting, a_vmess_clock_check_change_swaps_the_handler_without_disruption |
supervisor/tests/unit/plan.rs |
Which swaps are disruptions. |
two_inbounds_may_not_share_a_bind, the_same_port_over_udp_is_another_bind, each_protocol_is_served_only_on_its_kind_of_bind, a_unix_listener_carries_only_the_plain_tcp_shape |
supervisor/tests/unit/validate.rs |
The validation that makes BindSpec a key and pairs protocols with binds. |
a_handoff_socket_stands_beside_a_stream_inbounds_tcp_listener, a_handoff_bind_is_no_inbounds_own, two_binds_may_not_share_a_socket_path |
supervisor/tests/unit/validate.rs |
A handoff socket only beside a stream protocol’s TCP bind, never as an inbound’s own bind, and never at a path another bind has. The path and mode rules are on Validation. |
a_real_ip_header_needs_a_websocket_a_trusted_proxy_and_a_name |
supervisor/tests/unit/validate.rs |
A real-IP header is accepted on WebSocket over TCP, and refused on plain TCP or gRPC, with no trusted network, or under a name that is not a header name. |
a_connections_close_token_closes_that_connection_alone |
protocols/tests/pipeline/hysteria.rs |
Cancelling the token make_connector returned closes that connection and not its neighbour. |
cancelling_run_stops_admitting_and_waits_for_the_live_connections |
protocols/tests/pipeline/hysteria.rs |
A stopped Hysteria 2 listener refuses newcomers promptly, keeps relaying for the live connection, and run returns once it ends. |
a_new_connection_config_reaches_only_connections_that_arrive_after_it |
protocols/tests/pipeline/hysteria.rs |
A new connection config serves the connections that arrive after it (a new password, no UDP). |
switching_the_obfuscation_closes_the_old_clients_and_admits_new_ones, a_too_short_obfuscation_key_is_refused_and_changes_nothing |
protocols/tests/pipeline/hysteria.rs |
set_obfs on a running endpoint, and its refusal of a short key. |
socks_over_a_unix_socket_relays_and_cleans_up, http_connect_over_a_unix_socket_relays |
app/tests/integration/e2e_unix.rs |
A SOCKS round trip and an HTTP CONNECT over a Unix listener; the socket file is gone after SIGTERM. |
a_reload_keeps_the_inbound_serving_on_its_udp_port |
app/tests/integration/e2e_hysteria_inbound.rs |
A reload that changes a Hysteria 2 inbound’s settings with a client connected leaves it serving on the same port. Skipped without the reference hysteria build. |
a_routed_connect_is_answered_while_the_app_runs |
app/tests/integration/e2e_tun.rs |
The TUN inbound’s IP stack answers a routed TCP connect, and the interface and route are gone after the app exits. Linux only; skipped without CAP_NET_ADMIN. |
inbound_tag_selects_the_route, source_cidr_matches_the_client_address |
app/tests/integration/e2e_route_context.rs |
The tag and the peer IP captured at accept reach the router. |
Neither the admission semaphores’ limits nor drive’s silent-client timeout is exercised by a test at this revision; an_inbounds_listeners_share_one_set_of_caps pins only which caps a listener gets. A change to either should come with one; a paused Tokio clock (tokio::time::pause) makes the 10 s watchdog testable without waiting. Run the supervisor’s tests with cargo test -p etemenanki-supervisor and the app’s with cargo test -p etemenanki-app; see Testing.