Skip to content

Protocol crate foundations

Source files: 127 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/Cargo.toml
  • Etemenanki/protocols/src/lib.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/error.rs
  • Etemenanki/protocols/src/macros.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/core/harness.rs
  • Etemenanki/protocols/src/helpers/address.rs
  • Etemenanki/protocols/src/helpers/parse.rs
  • Etemenanki/protocols/src/helpers/crypto.rs
  • Etemenanki/protocols/src/helpers/address_family.rs
  • Etemenanki/protocols/src/ss_aead.rs
  • Etemenanki/protocols/src/anytls/core.rs
  • Etemenanki/protocols/src/anytls/uot.rs
  • Etemenanki/protocols/src/anytls/users.rs
  • Etemenanki/protocols/src/sss/core.rs
  • Etemenanki/protocols/src/sss/protocol.rs
  • Etemenanki/protocols/src/sss/varint.rs
  • Etemenanki/protocols/src/sss/transform/mod.rs
  • Etemenanki/protocols/src/sss/transform/base.rs
  • Etemenanki/protocols/src/sss/transform/http_chunk.rs
  • Etemenanki/protocols/src/sss/transform/pad.rs
  • Etemenanki/protocols/src/sss/transform/record.rs
  • Etemenanki/protocols/src/sss/transform/stuff.rs
  • Etemenanki/protocols/src/sss/transform/zstd.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/protocols/src/sniff/collector.rs
  • Etemenanki/protocols/src/http/core.rs
  • Etemenanki/protocols/src/http/protocol.rs
  • Etemenanki/protocols/src/trojan/core.rs
  • Etemenanki/protocols/src/trojan/protocol.rs
  • Etemenanki/protocols/src/trojan/users.rs
  • Etemenanki/protocols/src/vless/core.rs
  • Etemenanki/protocols/src/vless/protocol.rs
  • Etemenanki/protocols/src/vless/addons.rs
  • Etemenanki/protocols/src/vless/codec.rs
  • Etemenanki/protocols/src/vmess/core.rs
  • Etemenanki/protocols/src/vmess/protocol.rs
  • Etemenanki/protocols/src/vmess/aead.rs
  • Etemenanki/protocols/src/vmess/framing.rs
  • Etemenanki/protocols/src/ss_legacy/core.rs
  • Etemenanki/protocols/src/ss_legacy/users.rs
  • Etemenanki/protocols/src/ss_legacy/aead.rs
  • Etemenanki/protocols/src/ss_legacy/codec.rs
  • Etemenanki/protocols/src/ss_legacy/protocol.rs
  • Etemenanki/protocols/src/ss_2022/core.rs
  • Etemenanki/protocols/src/ss_2022/codec.rs
  • Etemenanki/protocols/src/ss_2022/crypto.rs
  • Etemenanki/protocols/src/ss_2022/protocol.rs
  • Etemenanki/protocols/src/mux/demux.rs
  • Etemenanki/protocols/src/mux/frame.rs
  • Etemenanki/protocols/src/socks/protocol.rs
  • Etemenanki/protocols/src/socks/handshake.rs
  • Etemenanki/protocols/src/socks/server.rs
  • Etemenanki/protocols/src/hysteria/config.rs
  • Etemenanki/protocols/src/hysteria/connection.rs
  • Etemenanki/protocols/src/hysteria/connector.rs
  • Etemenanki/protocols/src/hysteria/protocol.rs
  • Etemenanki/protocols/src/hysteria/obfs.rs
  • Etemenanki/protocols/src/hysteria/server/inbound.rs
  • Etemenanki/protocols/src/hysteria/server/datagrams.rs
  • Etemenanki/protocols/src/hysteria/server/shim.rs
  • Etemenanki/protocols/src/hysteria/server/authenticator.rs
  • Etemenanki/protocols/src/wireguard/config.rs
  • Etemenanki/protocols/src/wireguard/device.rs
  • Etemenanki/protocols/src/wireguard/connector.rs
  • Etemenanki/protocols/src/dns/mod.rs
  • Etemenanki/protocols/src/dns/message.rs
  • Etemenanki/protocols/src/transports/accept.rs
  • Etemenanki/protocols/src/transports/connect.rs
  • Etemenanki/protocols/src/transports/stream.rs
  • Etemenanki/protocols/src/transports/ws/stream.rs
  • Etemenanki/protocols/src/transports/grpc/liveness.rs
  • Etemenanki/protocols/src/transports/grpc/framing.rs
  • Etemenanki/protocols/src/tun/udp.rs
  • Etemenanki/protocols/src/tun/inbound.rs
  • Etemenanki/protocols/tests/pipeline.rs
  • Etemenanki/protocols/tests/pipeline/core.rs
  • Etemenanki/protocols/tests/support/pipeline.rs
  • Etemenanki/protocols/tests/unit/core/mod.rs
  • Etemenanki/protocols/tests/unit/helpers/address.rs
  • Etemenanki/protocols/tests/unit/helpers/address_family.rs
  • Etemenanki/protocols/tests/unit/ss_aead.rs
  • Etemenanki/protocols/tests/unit/ss_legacy/core.rs
  • Etemenanki/protocols/tests/unit/ss_legacy/aead.rs
  • Etemenanki/protocols/tests/unit/ss_2022/core.rs
  • Etemenanki/protocols/tests/unit/trojan/core.rs
  • Etemenanki/protocols/tests/unit/vless/core.rs
  • Etemenanki/protocols/tests/unit/vless/protocol.rs
  • Etemenanki/protocols/tests/unit/mux/demux.rs
  • Etemenanki/concepts/src/core.rs
  • Etemenanki/concepts/src/net.rs
  • Etemenanki/environment/src/dial/socket.rs
  • Etemenanki/supervisor/Cargo.toml
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/guard.rs
  • Etemenanki/supervisor/src/entity/session.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/router.rs
  • Etemenanki/supervisor/src/topology/plane.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/topology/spec_plan/outbound.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/udp_fanout.rs
  • Etemenanki/supervisor/src/topology/outbound/freedom.rs
  • Etemenanki/supervisor/src/topology/balancer.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/supervisor/src/build/users.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/build/outbound.rs
  • Etemenanki/supervisor/src/build/dns.rs
  • Etemenanki/app/Cargo.toml
  • Etemenanki/app/src/config.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/ffi/Cargo.toml
  • Etemenanki/ffi/src/client.rs
  • Etemenanki/ffi/src/platform.rs
  • Etemenanki/ffi/src/proxy.rs
  • Etemenanki/webclient/Cargo.toml
  • Etemenanki/webclient/tests/tracking.rs
  • katana/Cargo.toml
  • katana/Cargo.lock
  • katana/src/lower/inbound.rs
  • katana/src/lower/outbound.rs
  • katana/src/api/newv2board.rs

etemenanki-protocols holds every proxy protocol and transport of Etemenanki; protocols/Cargo.toml gives it version 6.2.1. Every server core in it is assembled from the same small set of parts: a Flow<T> that says where a connection goes and who opened it, one error type for untrusted framing, a timer whose meaning depends on the phase, a buffer for sniffed bytes, a relay tail that tracks half-closes, and a handful of parsing, address and crypto helpers. The crate reads no Etemenanki configuration file and runs no stream accept loop. etemenanki-supervisor builds its handlers from a spec and drives them, and every front end (etemenanki-app, etemenanki-ffi and katana) serves connections through the supervisor.

This page is for contributors who change the shared files of the crate: flow.rs, error.rs, macros.rs, core/, helpers/ and ss_aead.rs. It covers the crate as a whole first (modules, features, consumers, lints), then each shared part, then how a protocol module is laid out and what adding a protocol involves. It assumes you know the sans-I/O contract of ProxyCoreDecode (events in, effects out), which is described on Server core. The task that drives a core is on Per-connection runtime.

The foundation modules own:

  • The flow a server core hands to its connector. It holds the destination, the user, the sniffed domain and the client address (protocols/src/flow.rs → Flow<T>).
  • Error classification for untrusted input (protocols/src/error.rs → ProtocolError). It is bridged to std::io::Error, because the concepts boundary is fixed to io::Error.
  • The pieces every server core composes (protocols/src/core/mod.rs): FlowKey and SubKey, Phase, Timing and Expired, SniffPrefix, Passthrough, and the smallest complete core, PassthroughCore.
  • A test driver that needs no sockets (protocols/src/core/harness.rs → CoreHarness).
  • Shared wire helpers (protocols/src/helpers/): the binary address codec and text authorities (address.rs), panic-free slicing (parse.rs), small crypto primitives (crypto.rs) and the address-family policy of outbounds (address_family.rs), plus the byte_newtype! macro (macros.rs).
  • The AEAD record stream both Shadowsocks flavours share (protocols/src/ss_aead.rs).

They own no protocol’s wire format and no socket, and they keep no clock of their own. Timing pushes Effect::SetDeadline, pushes Effect::Finish on an idle expiry, and tells the core which deadline passed when the core calls expired; the runtime owns the one timer. A core composes these parts; it does not inherit them. It keeps a Timing and calls it at the top of every byte event, collects a flow’s first bytes in a SniffPrefix, and keeps a Passthrough for the half-close bookkeeping of its one stream outbound.

protocols/src/lib.rs declares the modules below. Two of them are behind Cargo features, and a third feature, reality, gates parts of transports and vless.

Module Gate Contents
core none The shared core pieces on this page, and CoreHarness.
error, flow, helpers, macros none Shared types and helpers on this page. byte_newtype! is #[macro_export]ed at the crate root.
ss_aead none The AEAD record stream of both Shadowsocks flavours: Cipher, Aead, ChunkEncoder, ChunkDecoder, RecordStep and RECORD_OVERHEAD. See The shared AEAD record stream.
sniff none The TLS SNI and HTTP Host sniffers, Collector, SNIFF_LIMIT, SNIFF_TIMEOUT and worth_sniffing. See Sniffing.
dns none The resolver outbounds dial through (Resolver, Backend, ResolverOptions), dns::hosts::Hosts for hosts-file entries, and dns::serve::Service, which answers applications’ DNS queries. See DNS resolver.
transports none TCP, TLS, WebSocket and gRPC, accept and connect sides, and the PROXY protocol v2 header decoder (transports/proxy_protocol.rs → decode_v2, and read_v2, which reads one off a socket). REALITY (transports/reality.rs) is behind the reality feature; the Camouflage relay a REALITY inbound hands back (transports/camouflage.rs) exists with or without it. See TCP and TLS transports and REALITY transport.
mux none The mux.cool server demultiplexer that Trojan, VLESS and VMess share, and the frame encoders the VLESS client uses to send a Vision outbound’s UDP as XUDP. See mux.cool and XUDP.
socks none SOCKS4, 4a and 5: a dedicated inbound driver (SocksInbound) instead of a core, plus the SOCKS5 client codec and UDP link. A UDP ASSOCIATE relays only datagrams from the sender that its request and control connection identify (ExpectedSender). See SOCKS.
http none HttpCore and the HttpConnect client codec. See HTTP proxy.
trojan, vless, vmess none Server cores and client codecs. vless also holds the request addons that carry the XTLS flow (vless/addons.rs) and the Vision framing (vless/vision/), whose stream adapter VisionStream is behind the reality feature. See XTLS Vision.
anytls none AnyTLS: frames, settings, the padding scheme, a user table keyed by password digest, sing’s UDP-over-TCP, AnyTlsCore and the pooled AnyTlsConnector client. See AnyTLS.
sss none sss: its transform layer (sss::transform), the wire format, SssCore, the pre-authentication gate sss::accept, the client codecs and SssConnector. See sss and sss transforms.
ss_legacy, ss_2022 none Shadowsocks AEAD and Shadowsocks 2022 cores and codecs, both on top of ss_aead.
wireguard none Outbound only: WgConnector over boringtun and a smoltcp netstack.
hysteria feature = "hysteria" Hysteria 2 client and server. Pulls in quinn, h3, h3-quinn, shinku-quic, rustls, rustls-native-certs, rustls-pemfile, rustls-pki-types and blake2. quinn and h3-quinn are shinku-quic’s patched copies, the packages shinku-quinn and shinku-h3-quinn, under their usual library names (root Cargo.toml); see shinku-quic.
tun all(feature = "tun", any(unix, windows)) The TUN inbound over the ipstack userspace stack. Pulls in ipstack, tun-rs and etherparse, plus rtnetlink on Linux and route_manager on macOS and Windows.
Feature What it enables
hysteria The hysteria module and its optional dependencies.
tun The tun module (on Unix and Windows) and its optional dependencies.
reality transports::reality, the Reality variants of InboundTransport, TransportKind and TransportStream, TransportStream::Vision and vless::vision::VisionStream, over the etemenanki-reality crate.
vendored-openssl Forwards to openssl/vendored. It gates no module.

No feature is on by default. The comments in protocols/Cargo.toml give the reason: Hysteria 2 brings a whole second TLS stack (quinn over rustls), TUN an interface-management stack and REALITY a TLS 1.3 of its own with ML-KEM, and a crate that wants only the classic protocols should not inherit any of them on a version bump without asking. No type of etemenanki-reality shows in this crate’s API, so a release of that crate reaches downstreams through a lockfile update alone. The features still work that way for a crate that depends on etemenanki-protocols alone. Every crate that goes through the supervisor gets all three, because supervisor/Cargo.toml turns on hysteria, tun and reality.

Consumer Manifest How Features it names
etemenanki-supervisor 1.1.0 supervisor/Cargo.toml Builds every inbound handler and outbound from a spec and drives the cores. hysteria, tun, reality
etemenanki-app 2.8.0 app/Cargo.toml Names protocol types only to lower its TOML into a spec (app/src/lower.rs), for example ResolverSpec, AddressFamilyStrategy, VerifyMode, parse_key, the TUN defaults, DeviceSpec, the Hysteria 2 tuning types Bandwidth, BandwidthConfig, Fallback, HopInterval, PortHopping and QuicOptions, the AnyTLS client’s DEFAULT_IDLE, the REALITY decoders decode_private_key, decode_public_key, decode_short_id and decode_client_version (transports::reality), and vless::addons::XTLS_RPRX_VISION. Its own vendored-openssl feature forwards to etemenanki-protocols/vendored-openssl. hysteria, tun, reality
etemenanki-ffi 0.4.1 (publish = false) ffi/Cargo.toml Reads the TUN defaults (DEFAULT_MAX_FLOWS, DEFAULT_MTU, DEFAULT_UDP_IDLE_TIMEOUT). Its own vendored-openssl feature forwards to etemenanki-protocols/vendored-openssl. hysteria, tun
etemenanki-webclient 2.0.0 webclient/Cargo.toml Dev-dependency only, for webclient/tests/tracking.rs. none
katana 6.1.0 katana Cargo.toml, which asks for protocols 7.1.1, and Cargo.lock, which locks 7.2.1 Names protocol types only to read a UniProxy panel’s node into the node config katana and helium share (src/api/newv2board.rs) and to lower a panel node into a spec (src/lower/inbound.rs, src/lower/outbound.rs), for example the Hysteria 2 server’s default limits, Masquerade, Bandwidth, BandwidthConfig, Fallback, QuicOptions, decode_psk, normalise_psk, Backend, ResolverSpec, AddressFamilyStrategy, Security, parse_key, the WireGuard DEFAULT_MTU, WsRoute, through which it checks a real-IP header name, the REALITY decoders decode_private_key and decode_short_id, and XTLS_RPRX_VISION. It serves connections only through the supervisor. vendored-openssl, hysteria, reality

The library crates are published to a private Cargo registry. Cargo unifies features across a build, so katana’s build compiles the tun module too: katana asks for vendored-openssl, hysteria and reality, and etemenanki-supervisor adds tun. katana never lowers a TUN inbound; src/lower/inbound.rs → credentials refuses any protocol other than the panel ones, with the note that a panel node is never TUN.

flowchart LR
  concepts["etemenanki-concepts"] --> protocols["etemenanki-protocols 6.2.1"]
  environment["etemenanki-environment"] --> protocols
  reality["etemenanki-reality"] -.->|"reality feature"| protocols
  protocols -->|"hysteria, tun, reality"| supervisor["etemenanki-supervisor 1.1.0"]
  protocols -->|"hysteria, tun, reality"| app["etemenanki-app"]
  protocols -->|"hysteria, tun"| ffi["etemenanki-ffi"]
  protocols -->|"vendored-openssl, hysteria, reality"| katana["katana 6.1.0"]
  protocols -.->|"dev only"| webclient["etemenanki-webclient"]
  supervisor --> app
  supervisor --> ffi
  supervisor --> katana
  supervisor --> webclient

etemenanki-protocols itself depends on etemenanki-concepts and etemenanki-environment as path dependencies with version requirements 2.0 and 3.0; inside the workspace they resolve to the path crates, concepts 2.1.2 and environment 3.2.1. The reality feature adds etemenanki-reality (requirement 0.1, the path crate 0.1.1). On macOS and Windows the crate also depends on rustls-native-certs, whatever the features: client TLS reads the platform’s CA store through it (transports/tls/platform_roots.rs). Among the dev-dependencies are tokio with test-util (for start_paused, because the idle and keepalive deadlines are minutes long) and criterion for the one bench, vmess_users. etherparse is no longer a dev-dependency: it is an optional dependency of the tun feature, which tun/ipv6.rs uses to refuse IPv6 handshakes, and the fake-device TUN test builds its IP packets with the same crate.

protocols 6.0.0 added AnyTLS, the REALITY transport, and the VLESS request addons with XTLS Vision. It changed these public items:

Item Change
transports::InboundTransport::accept Returns io::Result<Disposition> instead of io::Result<()>. Disposition::Done means every stream the socket yielded went to the sink, as before; Disposition::Camouflage(Camouflage) hands back a REALITY socket that is not a client, for the caller to relay. TCP, TLS, WebSocket and gRPC always return Done.
InboundTransport, TransportKind, TransportStream #[non_exhaustive], like the new Disposition, so a match outside the crate keeps a wildcard arm and a later transport is an addition.
vless::protocol::encode_request_header, vless::VlessStream::new Take a VlessFlow, and RequestHeader has a public flow field.

6.1.0 is a minor release. It adds the sss module, and the SOCKS driver now flushes the sniffed prefix it forwards (see SOCKS).

6.2.0 is a minor release. It adds vless::VlessDatagram::with_flow, through which a Vision outbound’s UDP rides XUDP, and changes VLESS behaviour without changing a signature: VlessCore refuses an unknown user id with PermissionDenied before it looks at the flow; both VLESS client codecs declare a STAGING_RESERVE of 296 bytes, room for the Vision addons; and the Vision writer ends its framing with its own COMMAND_DIRECT, so two Etemenanki peers leave the outer TLS (VLESS, XTLS Vision).

6.2.1 is a patch release. On Windows and macOS client TLS adds the platform’s CA store, read through rustls-native-certs, to OpenSSL’s, because an OpenSSL built from source looks for CAs under its build-time directory (TCP and TLS transports).

protocols/src/lib.rs opens with a crate-wide deny:

#![deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::arithmetic_side_effects
)]

The same four lints are allowed under cfg(test), because tests work on known-good inputs. etemenanki-environment opens with the same pair of attributes. The workspace gate runs cargo clippy --workspace --all-targets --all-features -- -D warnings, so production code in this crate does not index a slice, unwrap, or use unchecked +, - or *.

The only exceptions are functions that opt out of arithmetic_side_effects with a local #[allow(..., reason = "...")] that states why the arithmetic cannot overflow:

Function File Stated reason
after socks/server.rs, transports/ws/stream.rs an Instant only overflows past the end of the monotonic clock
deadline transports/grpc/liveness.rs the same
put_varint, read_varint transports/grpc/framing.rs shift by constant 7 on u64 cannot overflow; shift amount is bounded below 64 before each shift
read_varint, read_varint_slice hysteria/protocol.rs the prefix caps the fold at 6 + 7 × 8 = 62 bits
decode_varint hysteria/server/shim.rs the same
smoltcp_after wireguard/device.rs a smoltcp Instant is i64 microseconds, which the 60 s linger cannot overflow

The helpers in Parsing without panics exist because of this rule.

pub struct Flow<T> {
pub destination: Destination,
pub user: NetworkUser<T>,
pub sniffed: Option<SniffedBehavior>,
pub source: Option<IpAddr>,
}
impl<T> Flow<T> {
pub fn new(destination: Destination, user: NetworkUser<T>, source: Option<IpAddr>) -> Self;
pub fn toward(&self, destination: Destination) -> Self;
}

Flow<T> is the ProxyCoreDecode::Target of every server core in the crate. It is the value a core pushes in Effect::Open, and the value the connector routes and dials. The client codecs use Target = Destination instead: on the client side the target is the upstream proxy server the runtime dials, and the flow’s own destination is encoded inside the codec.

Field Set by Meaning
destination The core, from the request Destination { network, remote, port }, where remote is Remote::IpAddr or Remote::Domain. For a UDP flow it is the first packet’s destination; later packets carry their own address in Effect::SendTo.
user The core, from its user table NetworkUser<T>: an authorization (UserAuthorization::UsernamePassword or Uuid) plus user_data: Arc<T>.
sniffed The core, after sniffing Option<SniffedBehavior>, a protocol and a domain. Flow::new leaves it None.
source The core’s constructor The client’s address, when the inbound knows it. The supervisor’s serve loop passes the peer captured at accept, or the client a PROXY protocol v2 header names when the inbound reads one, or, for a socket a relay on the same host handed over, the client the header sent with it names (that socket’s own peer when the header names none), or, over WebSocket on an inbound with real_ip, the client a proxy in the trusted networks names in the upgrade’s header; the Hysteria 2 inbound passes the QUIC peer; the TUN inbound passes the client source address.

The payload is the supervisor’s Principal

Section titled “The payload is the supervisor’s Principal”

The supervisor instantiates every core with T = Principal (supervisor/src/topology/flow.rs → pub type Flow = etemenanki_protocols::flow::Flow<Principal>). Tests in this crate use T = (). Principal says who a flow belongs to:

pub struct Principal {
user: Option<UserKey>,
label: CompactString,
revoked: OnceLock<UserRemovalPolicy>,
}
impl Principal {
pub fn user(user: UserKey, label: CompactString) -> Arc<Self>;
pub fn anonymous() -> Arc<Self>;
pub fn user_key(&self) -> Option<UserKey>;
pub fn label(&self) -> &str;
pub fn revoked(&self) -> Option<UserRemovalPolicy>;
pub(crate) fn revoke(&self, policy: UserRemovalPolicy);
}

The supervisor builds each protocol’s user table from its admissions (supervisor/src/build/inbound.rs → user_table), and each entry carries that inbound-user’s Arc<Principal>. A successful handshake hands the Arc back as user_data, so a session learns its user from the first flow it opens. revoke marks the principal as no longer admitted by that inbound. The session side of this is on Users, principals and sessions.

The supervisor’s router adapts a flow to the route model in supervisor/src/topology/router.rs → route_target, called from CompiledRoutes::decide, which Plane::route and Plane::route_upstream (supervisor/src/topology/plane.rs) use. The inbound’s side of the context is supervisor/src/topology/flow.rs → FlowContext { inbound_tag, source }.

  • flow.sniffed becomes the target’s sniffed domain, so a domain or geosite rule can reach a flow addressed by IP.
  • flow.source.or(ctx.source) becomes the target’s source: the flow’s own source wins over the listener’s, because a QUIC inbound serves many peers from one socket and only the flow knows which peer it belongs to.
  • destination.network becomes the target network (Tcp or Udp), so RouteMatch::Network rules can fire.

Plane::route first sends any flow addressed to port 53 to the DNS service when the plane has one. The rest of the path is on The plane: routing each flow.

toward(destination) builds a sub-flow. The sub-flow shares the carrier’s user (the Arc is cloned) and source, and resets sniffed to None, because a sniffed domain describes the carrier’s first bytes, not the new destination. The callers are:

  • mux/demux.rs → Demux: one sub-flow per mux.cool New frame. When the inbound sniffs and the sub-flow’s target is an IP, the demux sniffs the payload that New frame carried.
  • trojan/core.rs → TrojanCore: a UDP association opens its outbound toward the first packet’s destination.
  • supervisor/src/topology/outbound/udp_fanout.rs → FanOutLink::poll_send_to: each datagram of an association routes as the association’s flow toward that datagram’s target, on the plane current when it is sent. See Outbounds, UDP fan-out and balancers.

Clone is written by hand instead of derived, so cloning a Flow<T> does not require T: Clone; the payload only ever sits behind an Arc. NetworkUser<T> in concepts/src/net.rs does the same. Principal is not Clone, and it must not be: it stays one shared instance per inbound-user, so every holder of the Arc sees the one revocation mark. What a session does with that mark is on Users, principals and sessions.

#[derive(Debug, thiserror::Error)]
pub enum ProtocolError {
Truncated(&'static str),
Overflow(&'static str),
Malformed(&'static str),
Unauthenticated(&'static str),
Crypto(&'static str),
Unsupported(&'static str),
Io(#[from] io::Error),
Other(#[from] anyhow::Error),
}
impl From<ProtocolError> for io::Error { /* … */ }
pub type Result<T, E = ProtocolError> = std::result::Result<T, E>;

Every public service in the crate still returns io::Error, because that is the concepts boundary. ProtocolError classifies failures inside parsers, and the From impl lets any function that returns io::Result propagate it with ?. The &'static str payload names the field or region that failed; it never carries input bytes.

Variant Display io::ErrorKind after conversion
Truncated truncated input: … UnexpectedEof
Overflow integer overflow: … InvalidData
Malformed malformed: … InvalidData
Unsupported unsupported: … InvalidData
Unauthenticated authentication failed: … PermissionDenied
Crypto cryptographic operation failed: … Other
Other the wrapped error Other
Io the wrapped error the wrapped error, returned unchanged

At this revision, production code names only three variants:

Variant Constructed in
Truncated helpers/parse.rs, helpers/address.rs, ss_aead.rs, ss_legacy/aead.rs, ss_2022/protocol.rs, socks/protocol.rs, mux/frame.rs, vmess/protocol.rs, hysteria/protocol.rs, dns/message.rs, and sss’s transforms (sss/transform/mod.rs, base.rs, http_chunk.rs, pad.rs, record.rs, stuff.rs, zstd.rs)
Overflow helpers/parse.rs, helpers/address.rs, ss_2022/protocol.rs, socks/protocol.rs, mux/frame.rs, vmess/protocol.rs, vmess/aead.rs, hysteria/protocol.rs, dns/message.rs, sss/protocol.rs, sss/transform/zstd.rs
Malformed hysteria/protocol.rs, hysteria/obfs.rs, sss/protocol.rs, sss/varint.rs, and the same sss transform files as Truncated

Unauthenticated, Crypto and Unsupported are declared but not raised. The server cores build an authentication failure directly as an io::Error; see Failure paths and cancellation.

pub enum FlowKey {
Direct,
Sub(SubKey),
}
pub struct SubKey {
pub id: u16,
pub generation: u32,
}

Both derive Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord and Hash. That covers the bounds ProxyCoreDecode::Key asks for (Copy + Ord + Send + Sync + 'static, in concepts/src/core.rs). A core whose connection carries either one flow or a mux.cool carrier (TrojanCore, VlessCore, VMessCore) uses FlowKey as its key. FlowKey::Direct is the connection’s own flow, and FlowKey::Sub is one mux sub-flow. A core with exactly one outbound uses the concepts crate’s Single.

SubKey.generation exists because of a runtime rule: Effect::Open on a key that is still live fails the connection with RuntimeError::DuplicateKey (open reuses a live outbound key). A mux.cool peer may reuse a session id while the runtime still holds the old key as live. Demux therefore keeps a generation: u32 counter that starts at 0, increments it with wrapping_add(1) on every New frame it accepts, and mints SubKey { id, generation }, so the first sub-flow is generation 1 and a reused id becomes a different key. Demux::session_id accepts an outbound event only if the stored SubKey for that id matches the whole key, so downlink bytes that arrive for a retired generation produce no frames.

Core Module Driven by Key TransportAddr BUF_SIZE STAGING_RESERVE MAX_DATAGRAM Uses Timing
PassthroughCore core TUN inbound, per TCP stream Single () 8 KiB 0 4096 (trait default) yes
HttpCore http supervisor serve loop Single () MAX_HEAD, 64 KiB 256 4096 (trait default) yes
TrojanCore trojan supervisor serve loop FlowKey () 16 KiB 808 8192 (MAX_LENGTH) yes
VlessCore vless supervisor serve loop FlowKey () 16 KiB 808 8192 yes
VMessCore vmess supervisor serve loop FlowKey () 32 KiB 4096 8192 yes
ShadowsocksCore ss_legacy supervisor serve loop Single () 20 KiB 128 4096 (trait default) yes
Ss2022Core ss_2022 supervisor serve loop Single () MAX_RECORD_LEN, 65,569 bytes 256 4096 (trait default) yes
AnyTlsCore anytls supervisor serve loop StreamKey (a stream’s wire id) () 16 KiB 2065 8192 (MAX_UDP_PAYLOAD) yes
SssCore sss supervisor serve loop, after sss’s gate FlowKey () TCP_BUF_SIZE 16 KiB, UDP_BUF_SIZE 66 KiB 262 (PACKET_HEADER_MAX) 65,535 yes
Hy2StreamCore hysteria::server::inbound Hysteria 2 inbound, per proxy stream Single () 8 KiB 2048 4096 (trait default) yes
Hy2UdpCore hysteria::server::datagrams Hysteria 2 inbound, per connection’s datagrams u32 (session id) () 16 KiB 4096 MAX_UDP_SIZE, 4096 no; it runs its own sweep
TunUdpCore tun::udp TUN inbound, per client source Single SocketAddr 8 KiB 4096 4096 yes

BUF_SIZE is the const generic a runtime over the core is instantiated with, for example drive::<{ TrojanCore::<Principal>::BUF_SIZE }, _, _> in supervisor/src/serve.rs, sized for the largest frame the protocol admits. It is a cap, not an up-front allocation: the runtime’s read buffer starts at 2 KiB and doubles up to it, the staging buffer starts empty, and the scratch buffer is allocated at the first outbound read (concepts/src/buffer.rs). How the runtime uses it is on Per-connection runtime. The reserves of Trojan and VLESS are computed: one UDP packet header (PACKET_HEADER_MAX, 263 bytes, rounded up to a multiple of 16: 272) plus mux::demux::downlink_overhead(BUF_SIZE), which is two mux frame overheads of FRAME_OVERHEAD_MAX (268 bytes) each for a 16 KiB read; 272 + 536 = 808. ShadowsocksCore’s is 32 + 2 × RECORD_OVERHEAD + 28 and Ss2022Core’s is 32 + 1 + 8 + 32 + 2 + 2 × TAG_LEN + RECORD_OVERHEAD + 115. AnyTlsCore’s is its largest reply to one frame: two 7-byte frame headers, the longest padding scheme (MAX_SCHEME_LEN, 2048 bytes) and its 3-byte v=2 ServerSettings. SssCore’s is one datagram record header: a 259-byte address and a 3-byte length. SssCore has two buffer sizes, and the supervisor picks one by the command sss’s gate read. MAX_DATAGRAM matters only to a core that carries datagrams.

pub enum Phase { Handshake, Sniff, Relay, Closing }
pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
pub const RELAY_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
pub enum Expired { Handshake, Sniff, Idle }
pub struct Timing { phase: Phase, armed: bool }
impl Timing {
pub fn new() -> Self;
pub fn phase(&self) -> Phase;
pub fn is_established(&self) -> bool;
pub fn touch<C: ProxyCoreDecode>(&mut self, fx: &mut Effects<'_, C>);
pub fn enter<C: ProxyCoreDecode>(&mut self, phase: Phase, fx: &mut Effects<'_, C>);
pub fn expired<C: ProxyCoreDecode>(&mut self, fx: &mut Effects<'_, C>) -> Expired;
}
pub fn handshake_timed_out() -> io::Error;

The runtime has exactly one deadline timer, driven by Effect::SetDeadline(Option<Duration>), so Timing lets the phase decide what the deadline means. Every arm pushes Effect::SetDeadline(Some(after)) through the private arm, which also sets armed; arming again replaces the previous deadline. Timing is Debug, Clone, Copy and Default; Default is new(). Phase and Expired derive Debug, Clone, Copy, PartialEq and Eq.

Phase enter(phase) arms touch expired returns What the core does
Handshake HANDSHAKE_TIMEOUT (10 s) Arms HANDSHAKE_TIMEOUT only if nothing is armed Expired::Handshake Returns an error, normally Err(handshake_timed_out())
Sniff SNIFF_TIMEOUT (300 ms) Nothing Expired::Sniff Opens the flow with what it collected
Relay RELAY_IDLE_TIMEOUT (300 s) Re-arms RELAY_IDLE_TIMEOUT Expired::Idle, after pushing Effect::Finish and moving to Closing Returns Ok(0)
Closing Not entered by a core; reached only through an idle expiry

expired also clears armed. is_established() is true in Relay and Closing, and false during Sniff. A core enters Relay once the request is parsed and nothing more is needed from the client: for a single TCP flow that is just before it pushes Open, before the dial completes; a Trojan, VLESS or VMess UDP association or mux.cool carrier enters it before any Open, and TunUdpCore enters it right after its one Open. The doc comment of Timing::enter gives the reason for the order: a forward queued after the Open waits out the connect, and so would a deadline queued after that forward, so the previous phase’s deadline would stay armed through the connect, and the sniff window’s 300 ms could end the flow as idle. Every core that keeps a Timing forwards it as its own is_established(), except TunUdpCore, which reports whether it has opened its flow; Hy2UdpCore has no handshake and always returns true. supervisor/src/serve.rs → drive (through the Established trait) and protocols/src/tun/inbound.rs → serve_stream read it to apply HANDSHAKE_TIMEOUT until the core is established.

What arms and re-arms the deadline:

  • The handshake deadline is armed once, by the first touch. Timing::new starts in Handshake with nothing armed, and later touch calls in Handshake do nothing. The limit therefore counts from the client’s first bytes, and a slow trickle of bytes does not extend it. handshake_timed_out() is an io::Error of kind TimedOut with the text client did not complete its request in time.
  • The sniff window is fixed. enter(Phase::Sniff) arms SNIFF_TIMEOUT and touch leaves it alone, so bytes that arrive during sniffing do not extend it.
  • The idle deadline is re-armed on every byte event. Cores call touch at the top of Event::Transport and Event::Outbound, and of Event::Datagram when they carry UDP. TunUdpCore, whose transport is a datagram socket, calls it on Event::TransportDatagram and Event::Datagram. EOF, connect and error events do not call it. This is what makes RELAY_IDLE_TIMEOUT an idle limit and not a lifetime.
  • Cores enter only Sniff and Relay. Closing is reached only through an idle expiry.

A core arms deadlines with Effect::SetDeadline, and Event::Deadline arrives when the deadline it armed passes. VMessCore::new takes now: fn() -> i64 for the auth id’s timestamp, and Ss2022Core::new takes now: fn() -> u64 for the request timestamp. The supervisor passes vmess::aead::now_unix and calls Ss2022Core::with_system_clock, which passes ss_2022::crypto::now_unix; both return seconds since the Unix epoch. Hy2UdpCore keeps no Timing: it arms SWEEP_INTERVAL (1 s) and counts each Event::Deadline as one tick of its own clock to sweep idle UDP sessions.

A runtime delivers no event before the client speaks, so Timing alone cannot catch a client that connects and sends nothing. The stream serve loop, the TUN inbound and the SOCKS driver cover that case with the same constant:

Driver Watchdog Error on expiry
supervisor/src/serve.rs → drive While the core is not established, wraps each runtime.next() in tokio::time::timeout(HANDSHAKE_TIMEOUT, …) inbound handshake timed out after 10s (TimedOut)
protocols/src/tun/inbound.rs → serve_stream The same loop over a PassthroughCore runtime tun: the client never spoke (TimedOut)
protocols/src/socks/server.rs → SocksInbound::serve Wraps the whole SOCKS handshake in HANDSHAKE_TIMEOUT; the relay then runs its own RELAY_IDLE_TIMEOUT sleep handshake_timed_out(); a CONNECT relay ends with socks: relay idle (TimedOut), and an idle UDP association just ends

drive takes an Established bound (supervisor/src/serve.rs → pub trait Established { fn is_established(&self) -> bool; fn user_hint(&self) -> Option<UserHint> { None } }). The established! macro in the same file implements it for HttpCore<Principal>, TrojanCore<Principal>, VlessCore<Principal>, ShadowsocksCore<Principal>, Ss2022Core<Principal>, AnyTlsCore<Principal> and SssCore<Principal>, which keep the default user_hint; VMessCore<Principal> implements it by hand, so that user_hint hands on VMessCore::user_hint, the user its auth id matched. It builds the core itself, from a make_core: impl FnOnce() -> Core closure such as || HttpCore::new(config.load_full(), sniff, source); its doc comment gives the reason: an async fn keeps its arguments for as long as its future lives, so a core passed in would be held twice, once there and once in the runtime. It also takes a Report (supervisor/src/guard.rs), where the connection’s handshake ends: a PermissionDenied core error before the core is established counts as a refused credential (Report::failed), and reaching an established core calls Report::succeeded(runtime.core().user_hint()), which a gRPC connection keeps for its next VMess stream (see Transports: WebSocket and gRPC). The module docs of protocols/src/core/mod.rs set the rule the cores follow: a core that refuses a credential fails with PermissionDenied, and uses that kind for nothing else before it is established. When a connection ends with an error, serve_connection logs it at debug level as <protocol> connection from <source> ended: <error>, where the source is the Debug form of the connection’s source Option<IpAddr> (Some(192.0.2.1) or None) and the protocol is StreamProtocol::name (http, trojan, vless, vmess, shadowsocks, shadowsocks-2022, anytls, sss or socks). See Listeners and the serve loop.

stateDiagram-v2
  [*] --> Handshake: Timing new, unarmed
  Handshake --> Handshake: first touch arms HANDSHAKE_TIMEOUT
  Handshake --> Sniff: enter Sniff, IP destination and sniffing on
  Handshake --> Relay: enter Relay
  Sniff --> Relay: Found, Exhausted, EOF or Expired Sniff
  Relay --> Relay: touch re-arms RELAY_IDLE_TIMEOUT
  Relay --> Closing: Expired Idle pushes Finish
  Handshake --> [*]: Expired Handshake, core returns an error
#[derive(Debug, Default)]
pub struct SniffPrefix { collector: Collector }
impl SniffPrefix {
pub fn new() -> Self;
pub fn push(&mut self, plain: &[u8]) -> (usize, Verdict);
pub fn held(&self) -> &[u8];
pub fn found(&self) -> Option<&SniffedBehavior>;
pub fn result(&self) -> Option<SniffedBehavior>;
pub fn clear(&mut self);
pub fn is_empty(&self) -> bool;
}

SniffPrefix wraps sniff::collector::Collector, a bounded accumulator of a flow’s first plaintext bytes that carries no deadline of its own. The budget is SNIFF_LIMIT (4096 bytes) across however many events the bytes arrive in. push takes min(plain.len(), Collector::remaining()) bytes, all of them even when a match ends earlier, and returns how many it took and a Verdict:

Verdict Meaning What the core does
Found A sniffer recognised a TLS SNI or an HTTP Host in the bytes collected so far. Opens the flow now.
More Nothing recognised yet, and budget is left. push of an empty slice with budget left returns More without looking. Consumes the returned count and waits.
Exhausted The budget is spent without a match. Opens the flow without a sniffed domain.

The caller consumes exactly the returned count. Once the budget is spent, push takes 0 bytes and keeps returning Exhausted.

The bytes are copied into the collector, so they stay in the core’s held buffer (PassthroughCore’s ProxyCoreDecode::held returns prefix.held(), and so does TrojanCore’s outside a mux carrier) until the flow opens. Collector::new owns no memory, because every core builds one at accept and only a flow that reaches its sniff phase fills it; the first non-empty push reserves the whole SNIFF_LIMIT in one allocation, so filling the budget never reallocates (sniff/collector.rs → Collector::push). To open, the core enters Relay, which pushes SetDeadline(RELAY_IDLE_TIMEOUT), then pushes Effect::Open with flow.sniffed = prefix.result(), followed by Effect::ForwardHeld { range: 0..held.len() } when it holds any bytes, and calls clear() at the top of the next byte event. That is safe because of the runtime’s held-buffer rule: while a held forward is queued, the runtime delivers no byte event, so at the start of a byte event every earlier held range has been applied. result() clones the sniffed value and leaves the bytes in place for that forward; found() borrows it. clear() drops the collected bytes and the buffer they were in: sniffing is over by then.

worth_sniffing(&destination) in sniff/mod.rs is true only for an IP destination. A flow that already names a domain is routed by that name, so cores skip the sniff phase for it and do not spend up to SNIFF_TIMEOUT on it. The sniffers themselves are on Sniffing.

#[derive(Debug, Clone, Copy)]
pub struct Passthrough<K> { key: K, outbound_eof: bool, transport_eof: bool }
impl<K: Copy> Passthrough<K> {
pub fn new(key: K) -> Self;
pub fn key(&self) -> K;
pub fn is_done(&self) -> bool;
pub fn on_transport<C: ProxyCoreDecode<Key = K>>(&self, data: &[u8], fx: &mut Effects<'_, C>) -> usize;
pub fn on_outbound<C: ProxyCoreDecode<Key = K>>(&self, data: &[u8], fx: &mut Effects<'_, C>) -> io::Result<usize>;
pub fn on_outbound_eof<C: ProxyCoreDecode<Key = K>>(&mut self, fx: &mut Effects<'_, C>);
pub fn on_transport_eof<C: ProxyCoreDecode<Key = K>>(&mut self, fx: &mut Effects<'_, C>);
pub fn on_outbound_gone<C: ProxyCoreDecode<Key = K>>(&mut self, fx: &mut Effects<'_, C>);
}
pub fn staging_full() -> io::Error;

Passthrough is the relay tail of a protocol with one stream outbound. Most protocols frame or encrypt their transport side, so such a core decodes its own transport bytes and uses only the half-close bookkeeping; the Shadowsocks cores, for example, push their own Forward over each opened record. on_transport and on_outbound are the verbatim forms a plaintext relay uses: PassthroughCore, Trojan and VLESS after the header, the HTTP CONNECT tunnel, and a Hysteria 2 proxy stream.

Method State change Effects
on_transport(data) none Forward { key, range: 0..data.len() }; returns data.len()
on_outbound(data) none Stages data toward the transport; returns data.len(), or Err(staging_full())
on_outbound_eof outbound_eof = true ShutdownTransport, then Finish if the transport already ended
on_transport_eof transport_eof = true Shutdown { key }, then Finish if the outbound already ended
on_outbound_gone both flags set ShutdownTransport, Finish

is_done() is true once both flags are set. on_outbound_gone handles a failed connect or an outbound error: nothing more can move, so the core finishes, and bytes already staged toward the transport are still written. staging_full() is io::Error::other("staging room below the core's declared reserve"). Reaching it means the core staged more than its STAGING_RESERVE promised. That is a bug in the core, not a peer error, because the runtime delivers an outbound event only when staging has room for the reserve plus the payload.

Passthrough is Copy, and the byte methods take &self. Cores copy it out of their state enum (let relay = *relay;) before they call them. This keeps the borrow of self.state separate from the self.prefix.clear() call that follows.

pub struct PassthroughCore<T> {
pending: Option<Flow<T>>,
sniff: bool,
prefix: SniffPrefix,
relay: Passthrough<Single>,
timing: Timing,
}
impl<T> PassthroughCore<T> {
pub const BUF_SIZE: usize = 8 * 1024;
pub fn new(flow: Flow<T>) -> Self;
pub fn sniffing(flow: Flow<T>) -> Self;
pub fn is_established(&self) -> bool;
}
impl<T: Send + Sync + 'static> ProxyCoreDecode for PassthroughCore<T> {
type Key = Single;
type Target = Flow<T>;
type Error = io::Error;
type TransportAddr = ();
const STAGING_RESERVE: usize = 0;
fn handle(&mut self, event: Event<'_, Self>, fx: &mut Effects<'_, Self>) -> Result<usize, io::Error>;
fn held(&self) -> &[u8];
}

The smallest complete core. It serves a flow whose destination is known before the first byte and relays it verbatim in both directions. The TUN inbound uses it for each TCP connection, because the IP stack has already said where the connection goes (tun/inbound.rs: PassthroughCore::sniffing(flow) when the inbound sniffs, PassthroughCore::new(flow) otherwise). sniffing(flow) turns the sniff phase on only when worth_sniffing says the destination is an IP. PassthroughCore is also the reference for how the parts fit together:

Event Handling
Transport while pending and sniffing Enters Sniff on the first one, calls prefix.push, and opens when the verdict is not More. Returns the count taken.
Transport otherwise Opens if not open yet, then touch, prefix.clear(), relay.on_transport.
Outbound touch, prefix.clear(), relay.on_outbound.
TransportEof Opens if still pending, with whatever was sniffed, then relay.on_transport_eof.
OutboundEof relay.on_outbound_eof.
ConnectFailed, OutboundError Drops the pending flow, then relay.on_outbound_gone.
Deadline Expired::Handshake returns Err(handshake_timed_out()), Expired::Sniff opens, and Expired::Idle returns Ok(0).
Connected, datagram events Ignored (Ok(0)).

Opening sets flow.sniffed, enters Relay, then pushes Effect::Open { key: Single, target: flow } and Effect::ForwardHeld over the held prefix when it is not empty. A non-sniffing core opens on its first Transport event, so the effects of that event are, in order, SetDeadline(RELAY_IDLE_TIMEOUT) from enter, Open, SetDeadline(RELAY_IDLE_TIMEOUT) from touch, and Forward; passthrough_core_opens_on_the_first_bytes_and_relays_verbatim checks that the deadline comes before the Open. A sniffing core never calls touch while it is pending, so it never arms HANDSHAKE_TIMEOUT; its first event arms SNIFF_TIMEOUT, and RELAY_IDLE_TIMEOUT too when that event already ends the sniff.

pub const HARNESS_STAGING: usize = 64 * 1024;
pub struct CoreHarness<C: ProxyCoreDecode> {
pub core: C,
effects: EffectList<C>,
staging: WriteBuffer<HARNESS_STAGING>,
packets: Option<PacketList<C::TransportAddr>>,
}
impl<C: ProxyCoreDecode> CoreHarness<C> {
pub fn new(core: C) -> Self;
pub fn over_datagrams(core: C) -> Self;
pub fn event(&mut self, event: Event<'_, C>) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn transport(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn feed(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn outbound(&mut self, key: C::Key, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn staged(&mut self) -> Vec<u8>;
pub fn staged_packets(&mut self) -> Vec<(Vec<u8>, C::TransportAddr)>;
pub fn held(&self, range: std::ops::Range<usize>) -> Vec<u8>;
}

A stand-in for the runtime that a test drives by hand. The unit tests of the cores use it. It does no I/O and keeps no clock, so a test delivers Event::Deadline itself.

  • event builds an Effects sink over the harness’s effect list and staging (Effects::with_packets when it stands in for a datagram transport), delivers one event, and returns the consumed count and the effects pushed during that call.
  • transport delivers one Event::Transport. feed calls it again on the unconsumed tail while the core makes progress, the way the runtime does, and stops when the core consumes 0 bytes or the slice is used up; it returns the total consumed. It shifts the ranges of Forward and SendTo so they are absolute in the slice you passed. ForwardHeld and SendToHeld ranges index the held buffer and are left alone; resolve them with held(range).
  • outbound delivers Event::Outbound for one key.
  • staged takes everything staged toward the transport so far. Staged bytes accumulate in the harness’s HARNESS_STAGING (64 KiB) buffer until a test takes them.
  • over_datagrams builds a harness for a datagram transport, so Effects::stage_to and put_to work. staged_packets returns each staged packet with its peer, in order, and an empty list for a stream harness.

The harness does not enforce the runtime’s scheduling rules: the staging reserve check, the held-buffer pin, FrameTooLarge, DuplicateKey and the other RuntimeError checks. The pipeline tests cover those by running the cores under the real runtime; the stream cores go through protocols/tests/support/pipeline.rs → serve_runtime, which serves a runtime over each accepted TCP connection, or serve_runtime_over, which first runs each connection through an InboundTransport (a TLS handshake, for AnyTLS).

A typical single-stream core keeps Timing and SniffPrefix as fields and moves through a state enum that holds a Passthrough once it relays. VlessCore is a good one to read. For a CONNECT to an IP with sniffing on, the exchange looks like this:

sequenceDiagram
  participant R as Runtime
  participant C as Core
  participant P as SniffPrefix
  R->>C: Event Transport with the request header
  C->>R: SetDeadline HANDSHAKE_TIMEOUT from touch
  C->>C: parse header, look up user, Flow new
  C->>R: SetDeadline SNIFF_TIMEOUT from enter Sniff
  R->>C: Event Transport with the first payload
  C->>P: push payload
  P-->>C: taken count and Verdict Found
  C->>R: SetDeadline RELAY_IDLE_TIMEOUT from enter Relay
  C->>R: Open with the sniffed flow
  C->>R: ForwardHeld over the held prefix
  R->>R: dial, then apply the held forward
  R->>C: Event Outbound with reply bytes
  C->>R: SetDeadline RELAY_IDLE_TIMEOUT from touch
  C->>C: prefix clear
  C->>R: stage the reply toward the transport

When the header and the first payload arrive in one read, the core consumes the header and returns; the runtime calls it again on the tail, which is the second Event::Transport above. If the sniff deadline fires first, Event::Deadline yields Expired::Sniff and the core opens with sniffed = None and the bytes it holds. If the destination names a domain, or sniffing is off, the core opens right after the header. A UDP association and a mux.cool carrier skip Sniff and enter Relay directly.

#[derive(Debug, Clone, Copy)]
pub struct AddressCodec {
pub ipv4: u8,
pub domain: u8,
pub ipv6: u8,
pub port_first: bool,
}
impl AddressCodec {
pub const SOCKS: Self;
pub const VMESS: Self;
pub const MAX_LEN: usize = 1 + 1 + 255 + 2;
pub fn encoded_len(remote: &Remote) -> usize;
pub fn write_slice(&self, out: &mut [u8], remote: &Remote, port: u16) -> Option<usize>;
pub fn write_buf(&self, out: &mut BytesMut, remote: &Remote, port: u16);
pub fn read_slice(&self, data: &[u8]) -> io::Result<(Remote, u16, usize)>;
pub async fn read<R: AsyncRead + Unpin>(&self, r: &mut R) -> io::Result<(Remote, u16)>;
pub async fn read_destination<R: AsyncRead + Unpin>(&self, r: &mut R, network: DialNetwork) -> io::Result<Destination>;
}

A port of Xray’s AddressParser. An address is a type byte, the address bytes and a big-endian port. The protocols differ only in the three type values and in whether the port comes first, so a codec is those four fields.

AddressCodec::SOCKS, port last:

Field Size Meaning
type 1 0x01 IPv4, 0x03 domain, 0x04 IPv6
address 4, 16, or 1 + n IPv4 octets; IPv6 octets; or a length byte n followed by n domain bytes
port 2 Big-endian

AddressCodec::VMESS, port first:

Field Size Meaning
port 2 Big-endian
type 1 0x01 IPv4, 0x02 domain, 0x03 IPv6
address 4, 16, or 1 + n As above
Layout Used by
SOCKS SOCKS5 (socks/protocol.rs), Trojan (trojan/protocol.rs), Shadowsocks (ss_legacy/protocol.rs), Shadowsocks 2022 (ss_2022/protocol.rs), AnyTLS stream destinations and the UDP-over-TCP request (anytls/core.rs, anytls/client/session.rs)
VMESS VLESS (vless/protocol.rs), mux.cool frames (mux/frame.rs), VMess (vmess/protocol.rs)

Most modules declare their layout once as pub const ADDR: AddressCodec = …;. VMess names AddressCodec::VMESS at its two call sites, and AnyTLS names AddressCodec::SOCKS at its own. VLESS is port-first, as in Xray: its ADDR is AddressCodec::VMESS. AnyTLS’s UDP-over-TCP packets use a third layout, anytls/uot.rs → ADDR: type 0x00 IPv4, 0x01 IPv6, 0x02 domain, port last. sss parses its own addresses (sss/protocol.rs → parse_address, put_address) and does not use AddressCodec.

encoded_len counts the type byte and the port: 7 bytes for IPv4, 19 bytes for IPv6, and n + 4 bytes for a domain of n bytes. MAX_LEN is 259, the size with a 255-byte domain. Protocols use it to size fixed header buffers and reserves, for example trojan::protocol::PACKET_HEADER_MAX and REQUEST_HEADER_MAX, vless::protocol::REQUEST_HEADER_MAX, mux::frame::FRAME_OVERHEAD_MAX, the SOCKS5 request buffer, the Shadowsocks client’s STAGING_RESERVE (ss_legacy/codec.rs), and the address scratch buffers of ss_legacy/codec.rs and ss_2022/protocol.rs.

The slice and async forms share these decoding rules:

  • An unknown type byte is InvalidData with unknown address type: <n>.
  • A domain must be non-empty UTF-8 made only of ASCII letters, digits, -, . and _. Anything else is InvalidData (empty domain name, non-utf8 domain, invalid domain name: …).
  • A domain that starts with a digit or [ and parses as an IP (brackets stripped) becomes Remote::IpAddr, the way Xray’s maybeIPPrefix does.
  • In read_slice, a short input is a Truncated error (address type byte, address body, address after port, domain length byte, domain, fixed-size field), which reaches the caller as UnexpectedEof, so a caller can wrap it in need_more. The returned count is the number of bytes consumed, port included. Offsets are added with checked_add (Overflow("address length"), Overflow("domain length")). The async read returns the UnexpectedEof of the underlying read_exact instead.

write_slice writes into a fixed slice and returns None when the slice is too short or the domain is longer than 255 bytes. Cores and codecs use this form to seal into staging room (ss_legacy/codec.rs, ss_2022/protocol.rs, trojan/protocol.rs, mux/frame.rs). write_buf appends to a BytesMut and is used where the output grows: the SOCKS5 request, reply and UDP headers, the Trojan request and packet headers, the VLESS and VMess request headers, and the mux frame encoder.

The async forms that remain, read and read_destination, serve the SOCKS handshake (socks/handshake.rs), which reads its request off the stream. AddressCodec::write was removed in protocols 3.0.0; see What 3.0.0 removed.

pub fn format_authority(dest: &Destination) -> String;
pub fn parse_authority(raw: &str, default_port: u16) -> io::Result<Destination>;

These serve the protocols that carry the target as text: the HTTP proxy server, for a CONNECT target (default port 443) and for the host of a plain proxied request (http/core.rs); the HTTP client’s CONNECT line (http/protocol.rs → build_connect_request); and Hysteria 2’s TCP requests and UDP messages (hysteria/connector.rs, hysteria/server/inbound.rs, hysteria/server/datagrams.rs, which pass default port 0). The resolver keeps a private parse_authority of its own in dns/mod.rs.

  • format_authority brackets IPv6, as in [2001:db8::1]:443.
  • parse_authority trims the input and accepts host, host:port, [v6] and [v6]:port. It uses default_port when the port is absent, leaves domains unresolved, and returns a TCP Destination.
  • parse_authority rejects an empty host (empty authority host), an unbracketed IPv6 (ambiguous authority (bracket IPv6 literals)), an invalid port (invalid port), an unclosed bracket (malformed IPv6 authority) and trailing data after a bracketed literal (trailing data after IPv6 authority). All of these are InvalidData.

helpers/address_family.rs decides which of a destination’s resolved IPs an outbound may use. It answers two independent questions:

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum AddressFamilyStrategy { #[default] Auto, Ipv4Only, Ipv6Only, PreferIpv4, PreferIpv6 }
impl AddressFamilyStrategy {
pub fn allows(self, ip: IpAddr) -> bool;
pub fn as_str(self) -> &'static str;
}
pub struct FamilySupport { ipv4: bool, ipv6: bool }
impl FamilySupport {
pub fn both() -> Self;
pub fn from_addrs(addrs: &[IpAddr]) -> Self;
pub fn supports(self, ip: IpAddr) -> bool;
pub fn describe(self) -> &'static str;
}
pub async fn resolve_candidates(
context: &str,
dest: &Destination,
strategy: AddressFamilyStrategy,
support: FamilySupport,
resolver: &Resolver,
) -> io::Result<Vec<IpAddr>>;
pub fn select_candidate_ips(
resolved: Vec<IpAddr>,
strategy: AddressFamilyStrategy,
support: FamilySupport,
) -> Vec<IpAddr>;
pub fn no_candidate_error(
context: &str,
dest: &Destination,
strategy: AddressFamilyStrategy,
support: FamilySupport,
) -> io::Error;
pub async fn destination_to_socketaddrs(
dest: &Destination,
strategy: AddressFamilyStrategy,
resolver: &Resolver,
) -> io::Result<Vec<SocketAddr>>;
  • Policy (AddressFamilyStrategy, default Auto) is what the operator asked for. Auto, PreferIpv4 and PreferIpv6 allow both families; the *Only variants allow one. as_str gives auto, ipv4_only, ipv6_only, prefer_ipv4 and prefer_ipv6. Its FromStr is lenient: it trims, lowercases and maps - to _, and accepts the aliases below. Anything else is AddressFamilyStrategyParseError (unknown address family strategy).

    Variant Accepted spellings
    Auto the empty string, auto
    Ipv4Only ipv4, v4, 4, ipv4_only, ipv4only
    Ipv6Only ipv6, v6, 6, ipv6_only, ipv6only
    PreferIpv4 prefer_ipv4, prefer_v4, ipv4_prefer, v4_prefer
    PreferIpv6 prefer_ipv6, prefer_v6, ipv6_prefer, v6_prefer
  • Capability (FamilySupport, default both()) is which families the outbound can source traffic from. A dialer that leaves source selection to the kernel passes FamilySupport::both(), and the kernel fails fast with ENETUNREACH for an unusable family. WireGuard runs a userspace netstack with no routing table, so wireguard/connector.rs derives support from its tunnel addresses with FamilySupport::from_addrs(&config.local_addrs). describe gives IPv4 and IPv6, IPv4 only, IPv6 only or no address family.

resolve_candidates takes an IP destination as it is and resolves a domain through resolver. A domain that resolves to nothing is NotFound with <context>: destination did not resolve. select_candidate_ips then keeps every resolved address that passes both checks, in resolver order, and the Prefer* strategies apply a stable sort, so the other family stays as a fallback instead of being dropped. Keeping every candidate, not only the first, is what lets a dialer move on when the leading address is unreachable (TcpDialer::connect_any). When nothing survives, no_candidate_error returns AddrNotAvailable with <context>: no usable <strategy> destination address for <host>:<port>. It appends (local address supports <describe>) whenever the caller’s FamilySupport is not both families, so a kernel-routed dialer never gets the clause.

destination_to_socketaddrs is resolve_candidates with context dial and FamilySupport::both(), mapped to socket addresses. Its callers are transports/connect.rs (a proxy outbound’s upstream), hysteria/connection.rs (the Hysteria 2 client’s server address), wireguard/device.rs → resolve_endpoint (when WgConfig::endpoint_resolution is set), supervisor/src/topology/outbound/freedom.rs → FreedomConnector, and supervisor/src/topology/balancer.rs (the probe, always with Auto). wireguard/connector.rs calls resolve_candidates with context wireguard and its own FamilySupport. See Dialers.

pub fn take<'a, I>(data: &'a [u8], index: I, what: &'static str) -> Result<&'a [u8], ProtocolError>
where
I: SliceIndex<[u8], Output = [u8]>;
pub fn take_array<const N: usize>(data: &[u8], at: usize) -> Result<[u8; N], ProtocolError>;
pub fn need_more<T>(result: std::io::Result<T>) -> std::io::Result<Option<T>>;

These three #[inline] functions in helpers/parse.rs replace slice[a..b] and slice[a..b].try_into().unwrap(), which the crate-level lints reject:

  • take borrows a sub-slice for any range form (..b, a.., a..b, ..) and maps an out-of-range access to Truncated(what).
  • take_array::<N> copies N bytes from offset at. It computes the end offset with checked_add (overflow is Overflow("field offset")) and bounds-checks the range (short input is Truncated("fixed-size field")). Use it for reads such as u16::from_be_bytes(take_array::<2>(data, at)?).
  • need_more is for slice parsers that receive a growing buffer and are called again when more bytes arrive. It turns an UnexpectedEof error into Ok(None) and leaves every other error an error.

The resulting shape for a header parser is fn parse(buf: &[u8]) -> io::Result<Option<(Header, usize)>>:

Return Meaning for the core
Ok(None) Not enough bytes yet. Consume 0 and wait for the next Event::Transport.
Ok(Some((header, used))) A whole header. Consume used.
Err(e) The peer is not speaking this protocol. Fail the connection.

vless/protocol.rs → parse_request_header shows the idiom. It checks each fixed field the moment it arrives, so a wrong byte fails at once instead of waiting for the rest of a header that will never parse:

let Some(&version) = buf.first() else {
return Ok(None);
};
if version != VERSION {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("invalid vless request version: {version}"),
));
}
let Some(uuid) = need_more(take_array::<16>(buf, 1).map_err(io::Error::from))? else {
return Ok(None);
};

It goes on the same way. The addonsLen bytes after the UUID are the request addons, taken with need_more(take(buf, 18..addons_end, "vless addons").map_err(io::Error::from))? and decoded by vless/addons.rs → parse_addons as the protobuf Xray carries; an unknown flow, an unknown field or malformed bytes are InvalidData. A command after them other than 1, 2 or 3 is InvalidData (invalid vless command: <n>), and the address is read with need_more(ADDR.read_slice(take(buf, addr_at.., "vless address")?))?, where addr_at is the offset just past the command. The UUID is not authenticated here; the core matches it against its Validator.

Keep need_more to the results of slice parsing. An UnexpectedEof from a real read means the peer closed, and need_more would turn it into a wait. Compute lengths read from the wire with checked_add or saturating_add, and compare each fixed field against the values the protocol defines: a wrong version or reserved byte must be an error, not a wait.

byte_newtype! (protocols/src/macros.rs, exported at the crate root) declares a Clone + Copy newtype over [u8; N] with a pub const fn as_bytes(&self) -> &[u8; N]. vmess/aead.rs uses it for GcmKey (16 bytes), GcmNonce (12 bytes) and ConnNonce (8 bytes), so values with different roles do not mix at a call site. Role-named constructors such as GcmKey::request_len keep the pairs of the same size apart, which the newtype alone cannot.

pub fn evp_bytes_to_key(password: &[u8], key_len: usize) -> Vec<u8>;
pub fn hkdf_sha1_ss_subkey(master_key: &[u8], salt: &[u8], out: &mut [u8]);
pub fn increment_le(nonce: &mut [u8]);
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool;
Function What it computes Callers
evp_bytes_to_key OpenSSL EVP_BytesToKey with MD5 and no salt: D_i = MD5(D_(i-1) ‖ password), concatenated and truncated to key_len. This is how Shadowsocks derives the master key from a password. ss_legacy/users.rs (the inbound’s user keys); supervisor/src/build/outbound.rs → build_outbound (the Shadowsocks outbound, for every front end)
hkdf_sha1_ss_subkey HKDF-SHA1 with the salt, the master key as input key material and the info string ss-subkey, filling out. This is the per-session Shadowsocks AEAD subkey. ss_legacy/aead.rs
increment_le Adds one to a little-endian counter in place, carrying across bytes and wrapping at the top. ss_aead.rs → Aead, the one nonce counter both Shadowsocks flavours share
ct_eq Constant-time equality through subtle::ConstantTimeEq. Slices of different length compare unequal. For example trojan/users.rs → Validator::get

hkdf_sha1_ss_subkey cannot fail for Shadowsocks subkey sizes of 16 or 32 bytes: HKDF-SHA1 fails only above 255 × 20 bytes of output. On that unreachable path it zero-fills out instead of panicking, because of the crate lints.

protocols/src/ss_aead.rs is the AEAD chunk stream that Shadowsocks AEAD (SIP004, ss_legacy) and Shadowsocks 2022 (SIP022, ss_2022) share. Each direction of a connection is keyed once, with a subkey each flavour derives its own way from its key and a fresh salt, and then seals under a little-endian nonce counter that starts at zero and advances once per AEAD operation. Data travels in records: a sealed two-byte big-endian length, then the sealed payload, each followed by its tag. SIP022 also seals its headers as bare chunks on the same counter. The flavours differ only in the ciphers they offer and in the longest payload a record may carry: ss_legacy/aead.rs → MAX_PAYLOAD (0x3FFF) and ss_2022/crypto.rs → MAX_PACKET_SIZE (0xFFFF).

pub const TAG_LEN: usize = 16;
pub const RECORD_HEADER_LEN: usize = 2 + TAG_LEN;
pub const RECORD_OVERHEAD: usize = RECORD_HEADER_LEN + TAG_LEN;
pub enum Cipher { Aes128Gcm, Aes256Gcm, ChaCha20Poly1305, XChaCha20Poly1305 }
impl Cipher {
pub const fn key_len(self) -> usize;
pub const fn nonce_len(self) -> usize;
}
pub struct Aead(/* the keyed cipher and its nonce counter */);
impl Aead {
pub fn new(cipher: Cipher, key: &[u8]) -> io::Result<Self>;
pub fn opens_length(&self, header: &[u8]) -> bool;
}
pub struct ChunkEncoder { /* aead, max_payload */ }
impl ChunkEncoder {
pub fn new(aead: Aead, max_payload: usize) -> Self;
pub fn seal_chunk(&mut self, plain: &[u8], out: &mut Staging<'_>) -> io::Result<()>;
pub fn seal_record(&mut self, plain: &[u8], out: &mut Staging<'_>) -> io::Result<()>;
}
pub enum RecordStep {
NeedMore,
Data { consumed: usize, plain: Range<usize> },
}
pub struct ChunkDecoder { /* aead, max_payload, pending_len */ }
impl ChunkDecoder {
pub fn new(aead: Aead, max_payload: usize) -> Self;
pub fn open_chunk(&mut self, chunk: &mut [u8]) -> io::Result<usize>;
pub fn open_record(&mut self, wire: &mut [u8]) -> io::Result<RecordStep>;
}
Cipher key_len nonce_len
Aes128Gcm 16 12
Aes256Gcm 32 12
ChaCha20Poly1305 32 12
XChaCha20Poly1305 32 24
  • Aead::new refuses a key of any other length with InvalidInput (shadowsocks: AEAD key of the wrong length). Each cipher is boxed, and a private each_cipher! macro runs the same code for all four.
  • seal_chunk stages plain followed by its tag. seal_record first checks that the payload fits a u16 and the encoder’s max_payload (InvalidInput, shadowsocks: record payload over the limit), then reserves RECORD_OVERHEAD + plain.len() bytes of staging (shadowsocks: staging room below the frame when there is no room), and only then seals the length and the payload. A refused record therefore stages nothing and leaves the nonce where it was. A failed seal is shadowsocks: AEAD seal failed.
  • open_record opens the sealed length from a copy and remembers it in pending_len, so a buffer presented again after more bytes arrived is never decrypted twice. A declared length above max_payload is InvalidData (shadowsocks: record length 0x4000 exceeds 0x3fff for a legacy record). The payload is opened in place once the whole record is there, and RecordStep::Data says how many wire bytes are done and where the plaintext sits inside them. A zero-length record is an ordinary record that carries nothing and ends nothing. A tag that does not verify is InvalidData (shadowsocks: invalid AEAD tag).
  • open_chunk opens a bare chunk in place and returns its plaintext length; a chunk shorter than its tag is Truncated("AEAD chunk shorter than its tag").
  • opens_length tries a key on a record’s first RECORD_HEADER_LEN bytes without changing the bytes or advancing the nonce. A legacy multi-user server tries each user’s key on the first record this way.

How each flavour derives its keys and uses these pieces is on Shadowsocks AEAD and Shadowsocks 2022.

protocols 4.0.0 added a public socket: SocketOptions field to three configuration types, so the sockets they open from the host can carry the host’s socket policy. A new public field breaks struct literals of these types, which makes it a breaking change of that release.

Config Field The socket it applies to
wireguard/config.rs → WgConfig socket The tunnel’s UDP socket: wireguard/device.rs binds it with UdpDialer::new(config.socket.clone()). WgConfig::new sets SocketOptions::default().
hysteria/config.rs → Hy2Config socket The UDP socket QUIC runs on: hysteria/connection.rs → bind_socket(config, addr) binds it with UdpDialer::new(options.clone()) and returns the socket and the address to connect to. With port hopping it builds a shinku_quic::hop::HoppingSocket that binds each hop’s socket the same way (see Port hopping). Salamander wraps the outermost socket when obfs is set.
dns/mod.rs → ResolverOptions socket Every socket a resolver without a dialer opens to its servers: Resolver::build keeps local: Dialer::new(socket), which opens the plain-DNS UDP socket (and its TCP retry after a truncated answer) and the TCP connections under DNS over TLS and DNS over HTTPS. ResolverOptions::default() leaves it at the default.

SocketOptions lives in environment/src/dial/socket.rs. Every field is optional, and the default sets none of them:

Field Type Meaning
bind_address Option<IpAddr> The source address to bind, applied only to sockets of its own family.
interface Option<Interface> The interface to tie the socket to.
mark Option<u32> A packet mark (SO_MARK), for policy routing on Linux and Android.
tcp_keepalive Option<Duration> TCP keepalive idle time; None leaves the platform default.
hook Option<SocketHook> Arc<dyn Fn(&Socket) -> io::Result<()> + Send + Sync>, called on each socket, so it can do anything the platform allows.

The supervisor fills all three fields from one value. supervisor/src/supervisor.rs → SupervisorBuilder::socket_options takes the policy, which holds for the supervisor’s lifetime; an apply cannot change it. supervisor/src/build/outbound.rs → build_outbound passes it into Hy2Config and WgConfig, and supervisor/src/build/dns.rs → build_dns passes it into the ResolverOptions of every resolver it builds from servers. supervisor/src/build/inbound.rs → build_handler passes it to a REALITY inbound, which dials its cover site with Dialer::new(socket) and the system resolver, outside the routing plane (see REALITY transport). The system resolver (Resolver::system(), which calls getaddrinfo) opens its sockets inside the C library, where no policy reaches them.

At this revision, etemenanki-ffi is the front end that sets a policy. ffi/src/proxy.rs starts the supervisor with Supervisor::builder().socket_options(platform::socket_options(platform)), and ffi/src/platform.rs → socket_options installs a hook that calls the app’s Platform::protect(fd) (Android’s VpnService.protect) and fails the socket with PermissionDenied (the platform refused to protect the socket) when the app refuses. etemenanki-app and katana run with the default policy.

WgConfig also has endpoint_resolution: Option<(Resolver, AddressFamilyStrategy)>, added in protocols 3.0.0. With Some, wireguard/device.rs → resolve_endpoint resolves the endpoint through destination_to_socketaddrs with the configured strategy, and a failed lookup is one of that function’s dial: errors: dial: destination did not resolve (NotFound) for an empty answer, or dial: no usable <strategy> destination address for <host>:<port> (AddrNotAvailable) when the strategy rules every address out. With None, it takes an IP endpoint as it is and asks the host resolver (tokio::net::lookup_host) for a domain, and an empty answer fails with NotFound (wireguard: endpoint domain did not resolve). The supervisor always passes Some((servers, endpoint_address_family)). See WireGuard.

Release 2.0.0 deleted the task-and-channel pipeline, but some of its AsyncRead and AsyncWrite helpers stayed in the wire modules, called only by unit tests and by each other. protocols 3.0.0 removed them. The cores and the client codecs had already parsed and staged through the slice functions, and the tests now do the same.

Module Removed What the code and tests use
trojan/protocol.rs read_request_header, read_packet, write_request_header, write_packet parse_request_header, parse_packet, encode_request_header, packet_header
vless/protocol.rs read_request_header, read_response_header, read_length_packet, write_request_header, write_response_header parse_request_header, parse_response_header, parse_length_packet, encode_request_header
mux/frame.rs read_meta, read_data parse_frame
helpers/address.rs AddressCodec::write write_slice, write_buf; it had no callers
vmess/aead.rs open_vmess_aead_header open_vmess_aead_header_slice
vmess/protocol.rs decode_response_header decode_response_header_slice
vmess/framing.rs ChunkStream::read_chunk ChunkDecoder
http/protocol.rs read_head nothing; it had no callers
hysteria/protocol.rs read_tcp_request, read_tcp_request_body parse_tcp_request_body
ss_legacy, ss_2022 EncryptWriter, DecryptReader, seal_to_vec, the read_request* and read_response functions, RequestHead, ResponseHead, and the Vec-based chunk readers and writers the sans-I/O codecs over ss_aead

What stays async is what still reads off a real stream: AddressCodec::read, read_destination and socks/protocol.rs → read_username_password and read_until_null for the SOCKS handshake, and Hysteria 2’s read_varint and read_tcp_response, because the client reads its TCPResponse off the QUIC stream.

Invariant Mechanism Pinned by
Production code in the crate does not panic on input Crate-level deny of unwrap_used, expect_used, indexing_slicing and arithmetic_side_effects; take, take_array and checked arithmetic cargo clippy --workspace --all-targets --all-features -- -D warnings
A short slice waits, a malformed one fails Truncated maps to UnexpectedEof, and need_more maps only that kind to None request_header_is_parsed_from_a_slice_once_whole in protocols/tests/unit/vless/protocol.rs; rejects_bad_version, rejects_unknown_command
The handshake deadline is armed once and counts from the first bytes Timing.armed; touch in Handshake timing_arms_handshake_once_then_idle_per_byte_event in protocols/tests/unit/core/mod.rs
The relay deadline is an idle limit touch re-arms RELAY_IDLE_TIMEOUT on every byte event Same test
An idle expiry pushes Effect::Finish Timing::expired pushes Effect::Finish and moves to Closing Same test; passthrough_core_finishes_when_the_outbound_fails_or_idles
Handshake and sniff expiry are left to the core expired pushes nothing for them timing_reports_handshake_and_sniff_expiry_to_the_core
Sniffing never holds more than SNIFF_LIMIT bytes SniffPrefix::push takes at most Collector::remaining() sniff_prefix_takes_no_more_than_its_budget
Sniffed bytes are forwarded, not lost, and the relay deadline is armed before Open SetDeadline(RELAY_IDLE_TIMEOUT), Open, then ForwardHeld over the held prefix; clear only at the next byte event sniff_prefix_finds_a_host_across_pushes_and_keeps_the_bytes, a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host, a_sniffing_passthrough_core_opens_on_the_sniff_deadline
A flow addressed by domain is never held for sniffing worth_sniffing a_sniffing_passthrough_core_with_a_domain_target_opens_at_once
A relay finishes only when both halves have closed The two Passthrough flags passthrough_half_closes_each_side_and_finishes_on_the_second
A reused mux session id never reuses a live outbound key SubKey.generation, incremented on every accepted New stream_sessions_open_forward_and_end_with_fresh_generations in protocols/tests/unit/mux/demux.rs
Encoded addresses round-trip and encoded_len is exact AddressCodec write_slice_matches_write_buf_and_bounds_itself in protocols/tests/unit/helpers/address.rs
Prefer* keeps the other family as a fallback Stable sort in select_candidate_ips prefer_ipv4_keeps_ipv6_as_fallback in protocols/tests/unit/helpers/address_family.rs
A netstack outbound never gets an address it cannot source FamilySupport::from_addrs auto_skips_families_without_a_local_address
The capability clause appears only for a caller whose FamilySupport is not both families, never for a kernel-routed dialer no_candidate_error compares support with both() the_capability_clause_is_omitted_for_a_kernel_routed_dialer
A Shadowsocks client that fails authentication sees nothing back and no close until it leaves or the handshake deadline passes, whatever number of bytes it sends State::Rejected in ShadowsocksCore and Ss2022Core an_unknown_password_is_drained_then_refused_when_the_client_leaves, a_rejected_client_is_cut_off_at_the_handshake_deadline, no_byte_count_makes_the_server_close_first in protocols/tests/unit/ss_legacy/core.rs; a_wrong_key_is_drained_until_the_handshake_deadline, no_byte_count_makes_the_server_close_first in protocols/tests/unit/ss_2022/core.rs
An AEAD record is decrypted once, however often its bytes are presented ChunkDecoder.pending_len a_record_presented_again_is_never_decrypted_twice in protocols/tests/unit/ss_aead.rs
A refused seal stages nothing and keeps the nonce seal_record checks and reserves before it seals a_refused_seal_stages_nothing_and_keeps_the_counter
Bare chunks and records advance one counter One Aead per direction bare_chunks_and_records_share_one_counter
  • Handshake timeout. On Expired::Handshake a core returns Err(handshake_timed_out()) (TimedOut), and the runtime ends the connection. A rejected Shadowsocks client ends with its stored rejection instead (below). A client that sends nothing at all is ended by the driver’s watchdog (see The silent client).
  • Unknown user, failing at once. TrojanCore (trojan: invalid user), AnyTlsCore (anytls: invalid user), VlessCore (invalid vless request user id) and VMessCore (vmess: unknown user or invalid auth id, or one of its clock-check and replay texts; see VMess) return an io::Error of kind PermissionDenied, and the connection ends without a reply. drive reports these errors to the supervisor’s guard as refused credentials.
  • Unknown user, drained. ShadowsocksCore and Ss2022Core do not fail at once. They enter State::Rejected(io::Error), consume every byte the client sends, open nothing and stage nothing, and return the stored error only on Event::TransportEof or Expired::Handshake. ShadowsocksCore stores shadowsocks: no matching user (PermissionDenied); Ss2022Core stores shadowsocks-2022: unknown identity, also PermissionDenied (ss_2022/core.rs → denied), and rejects this way, with InvalidData, a fixed chunk the key does not open, a wrong header type, a stale timestamp (shadowsocks-2022: bad timestamp) and a replayed salt (shadowsocks-2022: replayed request salt). The test comment gives the reason: a prober sending n random bytes sees the same for every n. A stored PermissionDenied reaches the guard the same way as the immediate refusals above when it ends the connection.
  • sss, refused before a core exists. sss reads its request header through its pre-authentication gate (sss::accept) before the supervisor builds a runtime. A stream the gate refuses is drained or handed to the configured fallback; sss writes nothing to it, and the refusal is not reported to the guard. See sss.
  • HTTP proxy authentication. HttpCore stages a 407 Proxy Authentication Required response with Proxy-Authenticate: Basic realm="proxy" and Connection: close, then pushes ShutdownTransport and Finish.
  • Malformed framing. Parsers return InvalidData, directly or as a converted ProtocolError, and the error ends the connection. VlessCore returns Unsupported (vless flow (xtls vision) is not served by this core) for a known user’s request that carries the Vision flow, after the user lookup: the Vision adapter strips the flow before the core sees it, so such a request means the inbound does not serve Vision. Nothing in sniff can fail a connection: bytes it does not recognise yield no sniffed domain.
  • Outbound failure. ConnectFailed or OutboundError leads to Passthrough::on_outbound_gone, which pushes ShutdownTransport and Finish. Staged bytes are still written.
  • Staging overrun. staging_full() fails the connection. It signals a wrong STAGING_RESERVE in the core, not a hostile peer.
  • Runtime errors. drive turns a RuntimeError into io::Error::other with the error’s text, for example open reuses a live outbound key.
  • Cancellation. The cores keep no socket and spawn no task, so dropping a core is always safe. Cancellation happens above them. Each accepted connection is a session with its own CancellationToken (on a gRPC carrier, each HTTP/2 stream is a session of its own), a child of the session registry’s root (supervisor/src/entity/session.rs → Sessions::open), not of its listener. supervisor/src/serve.rs → Shared::spawn_until runs the connection on the supervisor’s TaskTracker under until_cancelled(token, fut), which is fut.with_cancellation_token_owned(token), so cancelling the session drops the runtime, and dropping the runtime drops the core. Its doc comment says why it is a combinator and not a select! in an async block: the block would keep the future and the copy moved into the select!, making the task twice the size of the connection’s future. Cancelling a listener’s own stop token ends its accept loop, and the connections it accepted run on; when an apply removes an inbound tag, a separate CloseSessions step closes that inbound’s sessions (see Planning and applying a change). The serve loop itself is on Listeners and the serve loop.
Constant Value Defined in
HANDSHAKE_TIMEOUT 10 s protocols/src/core/mod.rs
RELAY_IDLE_TIMEOUT 300 s protocols/src/core/mod.rs
SNIFF_TIMEOUT 300 ms protocols/src/sniff/mod.rs
SNIFF_LIMIT 4096 bytes protocols/src/sniff/mod.rs
PassthroughCore::BUF_SIZE 8 KiB (8,192 bytes) protocols/src/core/mod.rs
PassthroughCore::STAGING_RESERVE 0 protocols/src/core/mod.rs
ProxyCoreDecode::MAX_DATAGRAM default 4096 bytes concepts/src/core.rs
HARNESS_STAGING 64 KiB (65,536 bytes) protocols/src/core/harness.rs
AddressCodec::MAX_LEN 259 bytes protocols/src/helpers/address.rs
Longest domain AddressCodec::write_slice encodes 255 bytes (one length byte) protocols/src/helpers/address.rs
ss_aead::TAG_LEN 16 bytes protocols/src/ss_aead.rs
ss_aead::RECORD_HEADER_LEN 18 bytes protocols/src/ss_aead.rs
ss_aead::RECORD_OVERHEAD 34 bytes protocols/src/ss_aead.rs
Longest record payload 0x3FFF (Shadowsocks AEAD), 0xFFFF (Shadowsocks 2022) protocols/src/ss_legacy/aead.rs, protocols/src/ss_2022/crypto.rs

The limits of the whole process are collected on Limits, timeouts and memory.

Most modules follow the same split. Not every module has every file, and a module adds files for what is specific to it: VMess adds aead.rs, keys.rs, framing.rs, session.rs and accounts.rs; Shadowsocks AEAD adds aead.rs, and Shadowsocks 2022 adds crypto.rs and replay.rs, both on top of crate::ss_aead.

File Holds Examples
mod.rs Module docs and the public re-exports trojan/mod.rs: pub use core::TrojanCore;
protocol.rs Wire primitives: constants, the module’s ADDR codec, slice parsers returning io::Result<Option<(T, usize)>>, and encoders. Only socks/protocol.rs and hysteria/protocol.rs keep async reads, for data they read off a live stream. vless/protocol.rs → parse_request_header, encode_request_header
core.rs The server core: a state enum, Timing, SniffPrefix, a Passthrough once relaying, BUF_SIZE, STAGING_RESERVE, is_established TrojanCore, VlessCore, VMessCore, ShadowsocksCore, Ss2022Core, HttpCore
codec.rs Client codecs implementing ProxyCoreEncodeHandshake plus ProxyCoreEncode (streams) or ProxyCoreEncodeDatagram (UDP) TrojanStream, TrojanDatagram, VlessStream, SsStream, HttpConnect
config.rs Server configuration types VlessServerConfig, HttpServerConfig, SocksServerConfig
users.rs, validator.rs, accounts.rs User tables, generic over the payload T and handing out Arc<T>. The core holds them behind an Arc. Some modules keep their server config here too (TrojanServerConfig, ShadowsocksServerConfig, Ss2022ServerConfig). trojan::Validator, vless::Validator, vmess::AccountValidator

The exceptions are structural:

  • SOCKS is served by its own driver (socks/server.rs → SocksInbound), not by a core.
  • Hysteria 2 owns its QUIC endpoint and runs one runtime per proxy stream (Hy2StreamCore) and one per connection’s datagrams (Hy2UdpCore).
  • TUN owns its device and runs one runtime per TCP connection (PassthroughCore) and one per client source’s UDP (TunUdpCore).
  • WireGuard has only an outbound connector.
  • AnyTLS multiplexes streams over one TLS connection, keyed by each stream’s wire id (StreamKey), and its client is a pooled Connector (anytls/client/), not a codec.
  • sss reads its request header through a gate (sss/server.rs → accept) before its core runs, and both ends wrap the transport in sss’s transform chains.
  • VLESS’s Vision flow is a stream adapter (vless/vision/) wrapped around a REALITY stream, not part of VlessCore.

Unit tests live outside src/, under protocols/tests/unit/<module>/<file>.rs. They are compiled into the module they test, so they can reach private items:

#[cfg(test)]
#[path = "../../tests/unit/trojan/core.rs"]
mod tests;

Pipeline tests run a server core and a client codec against each other under the real runtime. They are modules of protocols/tests/pipeline.rs, one file per protocol under protocols/tests/pipeline/, plus core.rs, dns_secure.rs, hysteria_options.rs, reality.rs and transports.rs. The hysteria and hysteria_options modules are gated by cfg(feature = "hysteria") and the reality module by cfg(feature = "reality"), like the code they test. The tun module is gated by cfg(all(feature = "tun", unix)): it fakes the device with a socket pair’s descriptor, which has no counterpart on Windows, where a device is a Wintun session.

  1. Write the wire primitives in protocols/src/<name>/protocol.rs. Parse from slices with take, take_array and checked arithmetic, return Ok(None) through need_more while bytes are missing, and compare every fixed field (version, reserved bytes, lengths, command) against the values the protocol defines. Reuse AddressCodec::SOCKS or AddressCodec::VMESS if the address layout matches; otherwise declare a new AddressCodec value. Put the result in pub const ADDR.

  2. Write the server core in core.rs. Implement ProxyCoreDecode with Target = Flow<T>, Error = io::Error, Key = Single (or FlowKey if it can carry mux.cool) and TransportAddr = () for a stream transport. Call timing.touch(fx) at the top of every byte event, enter(Phase::Sniff) or enter(Phase::Relay) once the request is parsed, and handle all three Expired values. Declare BUF_SIZE for the largest frame the protocol admits, a STAGING_RESERVE that covers everything one call stages beyond its payload, and MAX_DATAGRAM if it carries datagrams larger than 4096 bytes. Expose is_established().

  3. Write the client codecs in codec.rs against ProxyCoreEncodeHandshake plus ProxyCoreEncode and, if the protocol carries UDP, ProxyCoreEncodeDatagram. See Client codecs and the client runtime.

  4. Add users and configuration in users.rs or validator.rs and config.rs, generic over T. Compare secrets in constant time: trojan/users.rs compares each entry with ct_eq, and anytls/users.rs keys a map by the password’s digest with a key type whose PartialEq is ct_eq. Never log credentials or keys.

  5. Register the module in protocols/src/lib.rs. Put it behind a new Cargo feature if it brings a heavy dependency tree, as hysteria and tun do, gate its pipeline test module the same way, and turn the feature on in supervisor/Cargo.toml, because the supervisor is what serves it.

  6. Test it. Write unit tests in protocols/tests/unit/<name>/ that drive the core through CoreHarness, including negative tests for malformed input, truncated input and unknown users. Add a pipeline test in protocols/tests/pipeline/<name>.rs and register it in protocols/tests/pipeline.rs.

  7. Wire it into the supervisor.

    • Add a variant to supervisor/src/topology/spec_plan/inbound.rs → InboundProtocolSpec and/or supervisor/src/topology/spec_plan/outbound.rs → OutboundProtocolSpec. See The spec: desired state.
    • Add its rules to supervisor/src/build/validate.rs → validate (through validate_inbound or validate_outbound), the one owner of every rule about what a spec means. See Validation and apply errors.
    • If it runs over a stream transport, give the variant a transport: InboundTransportSpec and list it in InboundProtocolSpec::transport, the one list of protocols that take a transport. Building the handler, the real-IP rule and validation read that list, so the protocol meets the transport rules (TLS material only with a TLS shape, plain TCP on a Unix listener, REALITY under VLESS only) without calling them. InboundProtocolSpec and OutboundProtocolSpec are #[non_exhaustive], so a front end that matches them keeps a wildcard arm.
    • Map the inbound to the kind of credential it admits in supervisor/src/build/users.rs → credential_kind.
    • Build its user table and handler in supervisor/src/build/inbound.rs → user_table and build_handler, with a StreamProtocol variant (and a name) in supervisor/src/topology/inbound/mod.rs.
    • Add a drive::<{ Core::<Principal>::BUF_SIZE }, _, _> arm to supervisor/src/serve.rs → serve_connection, and add the core to the established! list, or implement Established by hand, as VMessCore does, if it names the user it matched.
    • For an outbound, add an Outbound variant in supervisor/src/topology/outbound/mod.rs and build it in supervisor/src/build/outbound.rs → build_outbound, passing the socket policy into any socket it opens itself.
  8. Wire it into the front ends. Add the settings to app/src/config.rs and lower them in app/src/lower.rs (see etemenanki-app: from TOML to a spec). If panels can describe it, it needs a variant in helium-node-api’s node config, the contract katana reads every panel’s node as, and, where a UniProxy panel can describe it, a conversion in katana’s src/api/newv2board.rs → parse_node_config; then lower it in katana’s src/lower/inbound.rs → lower_stream_protocol and credentials, or src/lower/outbound.rs (see Lowering inbounds and outbounds).

  9. Run the gates: cargo fmt --all -- --check, cargo test --workspace and cargo clippy --workspace --all-targets --all-features -- -D warnings.

Test File Covers
timing_arms_handshake_once_then_idle_per_byte_event protocols/tests/unit/core/mod.rs One handshake arm, an idle re-arm per event, and an idle expiry that pushes Finish and moves to Closing
timing_reports_handshake_and_sniff_expiry_to_the_core same Expired::Handshake and Expired::Sniff push nothing
sniff_prefix_finds_a_host_across_pushes_and_keeps_the_bytes same A Host header split across two pushes (18 then 19 bytes taken); held bytes kept until clear
sniff_prefix_takes_no_more_than_its_budget same The SNIFF_LIMIT cap, Exhausted, and 0 bytes taken after it
passthrough_half_closes_each_side_and_finishes_on_the_second same Half-close order and Finish
passthrough_core_opens_on_the_first_bytes_and_relays_verbatim same The order of deadline, open and forward
passthrough_core_finishes_when_the_outbound_fails_or_idles same ConnectFailed and an idle Deadline
a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host same Sniff, the relay deadline, then Open with the domain and ForwardHeld over all 41 held bytes, then clear
a_sniffing_passthrough_core_opens_on_the_sniff_deadline same Opening on Expired::Sniff without a domain, the relay deadline first
a_sniffing_passthrough_core_with_a_domain_target_opens_at_once same No sniff phase for a domain destination
passthrough_runtime_relays_a_tcp_flow_and_half_closes protocols/tests/pipeline/core.rs PassthroughCore relaying 100,000 bytes to a TCP echo server under the real runtime
write_slice_matches_write_buf_and_bounds_itself protocols/tests/unit/helpers/address.rs Both layouts round-trip; encoded_len; a short output and a 256-byte domain are rejected
authority_ipv4_with_port, authority_domain_default_port, authority_ipv6_bracketed same parse_authority
parses_address_family_strategy_aliases, auto_skips_families_without_a_local_address, auto_keeps_resolver_order_when_both_families_are_supported, ipv4_only_filters_to_ipv4, prefer_ipv4_keeps_ipv6_as_fallback, a_kernel_routed_dialer_is_limited_by_policy_alone, the_capability_clause_is_omitted_for_a_kernel_routed_dialer protocols/tests/unit/helpers/address_family.rs Aliases, filtering, fallback order and error text
request_header_is_parsed_from_a_slice_once_whole, rejects_bad_version, rejects_unknown_command, parses_a_vision_flow_header_with_shifted_offsets, rejects_an_unknown_or_malformed_flow_header protocols/tests/unit/vless/protocol.rs need_more returns None at each tested cut of a header (inside the UUID, at the addons byte, at the command, inside the address) and while the addons are incomplete; each fixed field fails as soon as it is wrong; the Vision addons shift the command and address; an unknown flow is InvalidData
stream_sessions_open_forward_and_end_with_fresh_generations protocols/tests/unit/mux/demux.rs A new SubKey generation per New, starting at 1
evp_key_known_answer protocols/tests/unit/ss_legacy/aead.rs evp_bytes_to_key against MD5 of the password
records_round_trip_under_every_cipher, bare_chunks_and_records_share_one_counter, a_record_presented_again_is_never_decrypted_twice, a_declared_length_over_the_limit_is_refused, a_refused_seal_stages_nothing_and_keeps_the_counter, a_trial_key_neither_changes_the_bytes_nor_advances, a_key_of_the_wrong_length_is_refused protocols/tests/unit/ss_aead.rs The shared AEAD record stream
unknown_user_is_refused protocols/tests/unit/trojan/core.rs PermissionDenied at once
unknown_uuid_is_refused, an_unknown_uuid_asking_for_vision_is_refused_as_unknown protocols/tests/unit/vless/core.rs PermissionDenied at once, with or without the Vision flow
an_unknown_password_is_drained_then_refused_when_the_client_leaves, a_rejected_client_is_cut_off_at_the_handshake_deadline, no_byte_count_makes_the_server_close_first protocols/tests/unit/ss_legacy/core.rs The drained rejection of Shadowsocks AEAD
eih_selects_the_user_and_a_stale_timestamp_is_refused, a_wrong_key_is_drained_until_the_handshake_deadline, no_byte_count_makes_the_server_close_first, a_replayed_request_is_refused protocols/tests/unit/ss_2022/core.rs The drained rejection of Shadowsocks 2022

How the unit, pipeline and interoperability tests are organised across the workspace is on Testing.