Skip to content

Transports: TCP and TLS

Source files: 68 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/src/transports/mod.rs
  • Etemenanki/protocols/src/transports/accept.rs
  • Etemenanki/protocols/src/transports/camouflage.rs
  • Etemenanki/protocols/src/transports/coalesce.rs
  • Etemenanki/protocols/src/transports/connect.rs
  • Etemenanki/protocols/src/transports/stream.rs
  • Etemenanki/protocols/src/transports/keepalive.rs
  • Etemenanki/protocols/src/transports/proxy_protocol.rs
  • Etemenanki/protocols/src/transports/tls/mod.rs
  • Etemenanki/protocols/src/transports/tls/config.rs
  • Etemenanki/protocols/src/transports/tls/stream.rs
  • Etemenanki/protocols/src/transports/tls/platform_roots.rs
  • Etemenanki/protocols/src/transports/grpc/settings.rs
  • Etemenanki/protocols/src/transports/grpc/stream.rs
  • Etemenanki/protocols/src/transports/ws/endpoint.rs
  • Etemenanki/protocols/src/transports/ws/stream.rs
  • Etemenanki/protocols/src/helpers/address_family.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/dns/mod.rs
  • Etemenanki/protocols/src/hysteria/connection.rs
  • Etemenanki/environment/src/dial/mod.rs
  • Etemenanki/environment/src/dial/tcp.rs
  • Etemenanki/environment/src/dial/socket.rs
  • Etemenanki/concepts/src/link.rs
  • Etemenanki/concepts/src/client.rs
  • Etemenanki/app/src/transport.rs
  • Etemenanki/app/src/config.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/app/src/instance.rs
  • Etemenanki/app/src/main.rs
  • Etemenanki/supervisor/src/topology/spec_plan/transport.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/build/apply.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/supervisor/src/build/outbound.rs
  • Etemenanki/supervisor/src/build/dns.rs
  • Etemenanki/supervisor/src/entity/session.rs
  • Etemenanki/supervisor/src/entity/usage.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/proxy.rs
  • Etemenanki/supervisor/src/topology/spec_plan/outbound.rs
  • Etemenanki/supervisor/src/system/listener.rs
  • Etemenanki/supervisor/src/system/handoff.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/guard.rs
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/ffi/src/platform.rs
  • Etemenanki/protocols/tests/pipeline/transports.rs
  • Etemenanki/protocols/tests/support/mod.rs
  • Etemenanki/protocols/tests/unit/transports/accept.rs
  • Etemenanki/protocols/tests/unit/transports/tls_config.rs
  • Etemenanki/protocols/tests/unit/transports/tls_platform_roots.rs
  • Etemenanki/protocols/tests/unit/transports/proxy_protocol.rs
  • Etemenanki/app/tests/unit/transport.rs
  • Etemenanki/app/tests/unit/lower.rs
  • Etemenanki/app/tests/integration/e2e_xray.rs
  • Etemenanki/app/tests/integration/e2e_xray_wrapped.rs
  • Etemenanki/app/tests/support/mod.rs
  • Etemenanki/supervisor/tests/unit/validate.rs
  • Etemenanki/supervisor/tests/guard.rs
  • Etemenanki/supervisor/tests/handoff.rs
  • katana/src/lower/inbound.rs
  • katana/src/lower/outbound.rs
  • katana/src/api/newv2board.rs
  • katana/tests/unit/lower/inbound.rs
  • katana/tests/unit/api/newv2board.rs

The transports module of etemenanki-protocols (6.2.1 at this revision) sits between a TCP socket and a proxy protocol. InboundTransport turns one accepted socket into one or more byte streams and hands each to a sink. TransportConnector resolves an upstream proxy server, connects to it and wraps the socket in the same layers. Every stream an InboundTransport yields and every stream a TransportConnector dials is a TransportStream. The per-connection runtime, which is generic over its stream, drives that stream and feeds the protocol core its bytes, so no core or client codec learns whether TLS, WebSocket or HTTP/2 sits underneath.

This page covers the module’s frame (the two enums, the stream type, keepalive and the handshake timeout of accept), the PROXY protocol v2 decoder, the plain TCP and TLS layers in full, the dialer and socket policy under TransportConnector, and what the supervisor builds from a transport spec. The WebSocket and gRPC layers have their own page, Transports: WebSocket and gRPC, and so does REALITY, REALITY transport; they appear here only where they share code with TCP and TLS. How etemenanki-app reads a [stream] block is on etemenanki-app: from TOML to a spec; this page summarises it.

Concern Owner Deliberately left to
Keepalive on every TCP socket that passes through InboundTransport::accept or TransportConnector::dial protocols/src/transports/keepalive.rs → set_keepalive nothing; applied unconditionally on those two paths
Reading a PROXY protocol v2 header off an accepted socket, and decoding one already in hand protocols/src/transports/proxy_protocol.rs → read_v2, decode_v2 the supervisor, which reads one only for an inbound that asks, bounds the read with PROXY_HEADER_TIMEOUT, and decodes the header that comes with a handed-over socket
Bounding the transport handshake of an accepted socket (REALITY keeps a deadline of its own) protocols/src/transports/accept.rs → within, TRANSPORT_HANDSHAKE_TIMEOUT the protocol handshake: the core’s HANDSHAKE_TIMEOUT, and supervisor/src/serve.rs → drive for a client that never speaks
Turning one socket into one or many streams InboundTransport::accept the caller’s sink; in the supervisor each stream is served as a session, and on gRPC each HTTP/2 stream is a session of its own
Resolving and connecting to an upstream server TransportConnector::dial Resolver, AddressFamilyStrategy, TcpDialer and its socket policy
TLS protocol versions and cipher policy protocols/src/transports/tls/config.rs callers choose certificates, trust, ALPN and the server name only
Turning a stream block into a transport spec the front end: app/src/transport.rs and app/src/lower.rs in etemenanki-app, src/lower/inbound.rs in katana the supervisor, which validates and builds
Refusing a transport spec that contradicts itself supervisor/src/build/validate.rs nothing; every front end’s spec passes through it
Turning a validated spec into values supervisor/src/build/inbound.rs → build_transport, supervisor/src/build/outbound.rs → transport_connector the protocols crate, which parses the PEM bytes

Apart from the PROXY protocol header, the module never parses a proxy protocol, never routes and never counts bytes. The runtime that drives a TransportStream sees AsyncRead + AsyncWrite + Unpin and nothing else. The supervisor counts a session’s bytes above this layer: by supervisor/src/entity/usage.rs, a stream inbound’s usage is the bytes of the protocol stream after its transport, so TLS records, WebSocket frames and gRPC framing are not part of it (see Per-user usage accounting).

In the workspace, the supervisor is the module’s user. supervisor/src/build/inbound.rs builds one InboundTransport per stream inbound, supervisor/src/build/outbound.rs builds one TransportConnector per proxy outbound, and supervisor/src/serve.rs runs InboundTransport::accept on every TCP socket a stream listener accepts or a relay on the same host hands over. etemenanki-app, the mobile bindings and katana 6.1.0 reach the transports only through the supervisor; none of them names InboundTransport or TransportConnector. The app imports VerifyMode from the module, to fill a ClientTlsSpec, and the REALITY decoders of transports::reality; katana imports WsRoute and two of those decoders.

Two other users take the TLS types directly: the DNS resolver builds ClientConfig values for DNS over TLS and DNS over HTTPS, and the Hysteria 2 client reads VerifyMode (see Other users of the TLS types).

Every transport starts from a tokio TcpStream. TLS wraps it in tokio_openssl::SslStream. WebSocket (protocols/src/transports/ws/stream.rs → WsStream) and gRPC (protocols/src/transports/grpc/stream.rs → GrpcStream) run over MaybeTlsStream, which is either the plain socket or the TLS stream, so they share one I/O path with and without TLS. TransportStream is the enum at the top that the rest of the code sees. With the reality feature it has two more variants, Reality and Vision, which REALITY transport and XTLS Vision cover; the diagram leaves them out.

flowchart BT
  tcp["TcpStream"]
  ssl["SslStream of TcpStream"]
  mts["MaybeTlsStream"]
  ws["WsStream of MaybeTlsStream"]
  grpc["GrpcStream"]
  ts["TransportStream"]
  tcp -- "Tcp" --> ts
  tcp --> ssl
  ssl -- "Tls" --> ts
  tcp -- "Plain" --> mts
  ssl -- "Tls" --> mts
  mts --> ws
  mts --> grpc
  ws -- "Ws" --> ts
  grpc -- "Grpc" --> ts

The labels on the edges are the enum variants: TransportStream::Tcp, TransportStream::Tls and so on on the way into TransportStream, and MaybeTlsStream::Plain / MaybeTlsStream::Tls on the way into MaybeTlsStream.

The module’s public surface, from protocols/src/transports/mod.rs and, for tls, protocols/src/transports/tls/mod.rs, which keeps its config and stream submodules private and re-exports their items:

Path Items
transports (re-exports) Accepted, Camouflage, Disposition, InboundTransport, TransportConnector, TransportKind, TransportStream
transports::accept TRANSPORT_HANDSHAKE_TIMEOUT, Accepted, Disposition, InboundTransport
transports::camouflage Camouflage, the relay a REALITY inbound hands back for a socket that is not a client; present with or without the reality feature, so Disposition reads the same either way
transports::connect TransportKind, TransportConnector
transports::keepalive set_keepalive
transports::proxy_protocol MAX_V2_LEN, Header, decode_v2, read_v2, parse_v2
transports::stream TransportStream
transports::tls Alpn, ClientConfig, ServerConfig, VerifyMode, MaybeTlsStream, accept_optional_tcp, tcp_from_std, wrap_optional_tcp; the platform_roots submodule is pub(crate) and compiled only for Android, iOS, Windows, macOS and the crate’s own unit tests
transports::ws, transports::grpc the WebSocket and gRPC layers, on their own page
transports::reality (feature reality) REALITY’s server and client types and the decoders of Xray’s key, shortId and version formats, on their own page
protocols/src/transports/stream.rs
#[non_exhaustive]
pub enum TransportStream {
Tcp(TcpStream),
Tls(Box<SslStream<TcpStream>>),
Ws(Box<WsStream<MaybeTlsStream>>),
Grpc(Box<GrpcStream>),
#[cfg(feature = "reality")]
Reality(Box<super::reality::RealityStream>),
#[cfg(feature = "reality")]
Vision(Box<crate::vless::vision::VisionStream>),
}
impl TransportStream {
pub fn real_ip_header(&self) -> Option<&RealIpHeader>;
#[cfg(feature = "reality")]
pub fn into_vision_server(self) -> io::Result<Self>;
}

TransportStream implements AsyncRead and AsyncWrite by matching on the variant and forwarding poll_read, poll_write, poll_flush and poll_shutdown to the inner stream through Pin::new. Every inner type is Unpin, so no pin projection is needed. It does not override poll_write_vectored or is_write_vectored, so a vectored write falls back to tokio’s default, which writes the first non-empty buffer. It implements neither Debug nor Clone.

TransportStream is #[non_exhaustive], so a match outside the crate keeps a wildcard arm. into_vision_server turns a Reality stream into a Vision one, the server side of the XTLS Vision adapter, and refuses every other variant with vless vision rides only over reality (InvalidInput).

real_ip_header answers WsStream::real_ip_header for a Ws stream and None for every other variant. It is Some only for an accepted WebSocket upgrade whose route reads a client-address header, and it reports what that header said (RealIpHeader::Missing, Malformed or Addresses) without judging who sent it: as its doc comment says, anyone can send the header, so a caller takes it only from a proxy trusted to set it. The header, its parsing and the supervisor’s use of it are on Transports: WebSocket and gRPC.

Variant Inner type Produced by
Tcp TcpStream InboundTransport::Tcp, TransportKind::Tcp
Tls SslStream<TcpStream> InboundTransport::Tls, TransportKind::Tls
Ws WsStream<MaybeTlsStream> InboundTransport::Ws, TransportKind::Ws
Grpc GrpcStream InboundTransport::Grpc, TransportKind::Grpc
Reality RealityStream InboundTransport::Reality for an authenticated client, TransportKind::Reality without Vision
Vision VisionStream TransportKind::Reality with Vision, and into_vision_server on an accepted Reality stream

protocols/src/transports/accept.rs names the accept-side alias, which is the same type:

pub type Accepted = TransportStream;
protocols/src/transports/accept.rs
/// How long the transport handshake may take.
pub const TRANSPORT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]
#[non_exhaustive]
pub enum InboundTransport {
Tcp,
Tls(ServerConfig),
Ws {
route: WsRoute,
tls: Option<ServerConfig>,
},
Grpc {
paths: Arc<GrpcPaths>,
tls: Option<ServerConfig>,
},
/// REALITY, over TCP.
#[cfg(feature = "reality")]
Reality(super::reality::RealityServer),
}
/// What became of an accepted socket once its transport was through.
#[derive(Debug)]
#[non_exhaustive]
pub enum Disposition {
Done,
Camouflage(Camouflage),
}
impl InboundTransport {
pub fn ws(path: impl AsRef<str>, host: Option<&str>, tls: Option<ServerConfig>) -> Self;
pub fn grpc(service: impl AsRef<str>, tls: Option<ServerConfig>) -> Self;
pub async fn accept<F>(&self, tcp: TcpStream, mut sink: F) -> io::Result<Disposition>
where
F: FnMut(Accepted);
}
fn timed_out(what: &str) -> io::Error;
async fn within<T>(what: &str, fut: impl Future<Output = io::Result<T>>) -> io::Result<T>;
async fn maybe_tls(tcp: TcpStream, tls: Option<&ServerConfig>) -> io::Result<MaybeTlsStream>;
  • InboundTransport::ws(path, host, tls) builds a WsRoute with protocols/src/transports/ws/endpoint.rs → WsRoute::new, which normalises the path (normalize_path strips an ?ed=N suffix and adds a missing leading /), and, when host is Some, requires the request’s Host to match it. Only the pipeline tests call it; the supervisor builds InboundTransport::Ws from a WsRoute of its own, which may also read a client-address header (see Building the values).
  • InboundTransport::grpc(service, tls) builds GrpcPaths for the service, which answers on both /<service>/Tun and /<service>/TunMulti.

InboundTransport is Clone: ServerConfig shares one Arc<SslAcceptor>, WsRoute holds Arc<str> values, and the gRPC paths sit behind an Arc. It is #[non_exhaustive], like Disposition.

accept does three things, in this order:

  1. It calls set_keepalive(&tcp) on the accepted socket.
  2. It runs the transport’s own handshake inside within, which wraps the future in tokio::time::timeout(TRANSPORT_HANDSHAKE_TIMEOUT, …). REALITY is the exception: its decision keeps its own deadline, because running out of time before the decision hands the socket to the cover site instead of closing it, so a probe sees the cover site’s timing.
  3. It hands each resulting stream to sink and returns Disposition::Done. A REALITY socket that is not a client of this server yields no stream; accept returns Disposition::Camouflage with the relay to the cover site, and the sink never sees the socket.
Variant Step bounded by TRANSPORT_HANDSHAKE_TIMEOUT within label Streams yielded
Tcp none, there is no handshake none exactly one, the socket itself
Tls ServerConfig::accept "tls" exactly one
Ws maybe_tls, then WsStream::accept (the HTTP upgrade) "websocket" exactly one
Grpc maybe_tls, wrapped by h2_io in Heard<Coalesced<_>>, then configured_server_builder().handshake(io) (the HTTP/2 preface and settings) "grpc" one per tunnel stream
Reality none; RealityServer::accept runs under its own deadline none one TransportStream::Reality for an authenticated client, none otherwise

For Tcp, Tls, Ws and an authenticated REALITY client, accept returns Ok(Disposition::Done) right after its one sink call. For Ws and Grpc the TLS handshake and the layer above it share one 10-second budget, because both run inside the same within future. On expiry timed_out builds an io::ErrorKind::TimedOut error with the text <label> handshake timed out: tls handshake timed out, websocket handshake timed out or grpc handshake timed out. An HTTP/2 handshake error becomes io::Error::other.

The limit covers only the transport step, as the module’s doc comment says. The protocol handshake that follows on the yielded stream (a Trojan password, a VLESS header) has its own deadlines, with the same value, etemenanki_protocols::core::HANDSHAKE_TIMEOUT (10 s, protocols/src/core/mod.rs):

  • the core’s Timing arms it once, at the client’s first byte event, and does not extend it while the core is still in its handshake;
  • supervisor/src/serve.rs → drive wraps each runtime.next() in the same timeout until the core is established, which catches a client that never speaks, and fails with inbound handshake timed out after 10s;
  • the SOCKS driver wraps its whole handshake in the same constant.

See Protocol crate foundations and Listeners and the serve loop.

For Grpc, accept reads the socket’s peer address and makes a ReadClock before the handshake, wraps the I/O with h2_io (Coalesced, which holds h2’s writes until h2 flushes so that a DATA frame goes out as one TLS record, under Heard, which stamps that clock on every read), and hands the handshaken h2::server::Connection to the private serve_h2(conn, heard, paths, peer, sink). It drives the HTTP/2 connection and calls sink once for every tunnel stream opened on /<service>/Tun or /<service>/TunMulti; a request on any other path is reset with REFUSED_STREAM and logged at debug. Each HTTP/2 stream is a session of its own. The request handling, the stream count, the connection’s liveness checks and the write batching are on Transports: WebSocket and gRPC.

protocols/src/transports/connect.rs
#[derive(Clone)]
#[non_exhaustive]
pub enum TransportKind {
Tcp,
Tls(ClientConfig),
Ws {
target: WsTarget,
tls: Option<ClientConfig>,
},
Grpc {
authority: Arc<str>,
service: Arc<str>,
mode: GrpcMode,
user_agent: Option<Arc<str>>,
tls: Option<ClientConfig>,
},
#[cfg(feature = "reality")]
Reality {
config: super::reality::ClientConfig,
vision: Option<[u8; 16]>,
},
}
impl TransportKind {
pub fn ws(host: impl AsRef<str>, path: impl AsRef<str>, tls: Option<ClientConfig>) -> Self;
pub fn grpc(
authority: impl AsRef<str>,
service: impl AsRef<str>,
tls: Option<ClientConfig>,
) -> Self;
#[must_use]
pub fn multi(mut self) -> Self;
#[must_use]
pub fn user_agent(mut self, agent: Option<&str>) -> Self;
#[cfg(feature = "reality")]
pub fn reality(config: super::reality::ClientConfig) -> Self;
#[cfg(feature = "reality")]
#[must_use]
pub fn vision(mut self, uuid: [u8; 16]) -> Self;
async fn wrap(&self, tcp: TcpStream) -> io::Result<TransportStream>;
}
#[derive(Clone)]
pub struct TransportConnector {
kind: Arc<TransportKind>,
dialer: Dialer,
resolver: Resolver,
strategy: AddressFamilyStrategy,
}
impl TransportConnector {
pub fn new(
kind: TransportKind,
dialer: Dialer,
resolver: Resolver,
strategy: AddressFamilyStrategy,
) -> Self;
pub fn tcp() -> Self;
pub async fn dial(&self, dest: &Destination) -> io::Result<TransportStream>;
}
  • TransportKind::ws(host, path, tls) builds a WsTarget with WsTarget::new, which reads an ?ed=N suffix on path with parse_early_data_path (it enables WebSocket early data) and then normalises the path with normalize_path. Both are in protocols/src/transports/ws/endpoint.rs.
  • TransportKind::grpc starts in GrpcMode::Gun with user_agent set to DEFAULT_USER_AGENT, a desktop Chrome string (Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.7977.42 Safari/537.36, in protocols/src/transports/grpc/settings.rs).
  • multi switches a gRPC kind to GrpcMode::Multi (TunMulti, MultiHunk framing), for an Xray peer configured with multiMode: true. user_agent(Some(..)) replaces the header and user_agent(None) drops it. Both do nothing on a non-gRPC kind.
  • reality(config) is VLESS over REALITY with an unframed body, and vision(uuid) makes a REALITY kind frame the body with XTLS Vision for that VLESS user id; it does nothing on any other kind. TransportKind is #[non_exhaustive].

The supervisor’s transport_connector calls neither multi nor user_agent, so every gRPC outbound opens /<service>/Tun with the default user agent. Only the pipeline test grpc_multi_mode_over_tls_round_trip calls multi.

TransportConnector::tcp() is plain TCP with Dialer::default() (no socket policy), Resolver::default() (the system resolver, cached) and AddressFamilyStrategy::default() (Auto). Nothing in the workspace calls it at this revision; the supervisor builds every connector with TransportConnector::new.

wrap layers the transport on a connected socket:

TransportKind What wrap does Yields
Tcp nothing TransportStream::Tcp
Tls(client) client.wrap(tcp), the client handshake TransportStream::Tls
Ws { target, tls } the private maybe_tls, then WsStream::connect(io, target, tls.is_some()) TransportStream::Ws
Grpc { .. } maybe_tls, then GrpcStream::connect(io, tls.is_some(), authority, service, mode, user_agent), which opens one HTTP/2 connection per dial and one tunnel stream on it TransportStream::Grpc
Reality { config, vision } config.connect(tcp), the REALITY client handshake; with vision set, VisionStream::client over the result TransportStream::Reality, or TransportStream::Vision with vision

The tls.is_some() flag picks the URI scheme of the request that follows: wss:// or ws:// for the WebSocket upgrade, https:// or http:// for the gRPC request. With early data configured, WsStream::connect returns before the upgrade and sends it with the first write. The upgrade itself, early data and the gRPC request are on Transports: WebSocket and gRPC.

TransportConnector implements the concepts crate’s Connector for a Destination:

concepts/src/link.rs
pub trait Connector<Target> {
type Stream: AsyncRead + AsyncWrite + Unpin;
type Datagram: DatagramLink;
type Future: Future<Output = io::Result<Outbound<Self::Stream, Self::Datagram>>>;
fn connect(&mut self, target: Target) -> Self::Future;
}
pub enum NoDatagram {
Never(Infallible),
}
// protocols/src/transports/connect.rs
type DialFuture =
Pin<Box<dyn Future<Output = io::Result<Outbound<TransportStream, NoDatagram>>> + Send>>;
impl Connector<Destination> for TransportConnector {
type Stream = TransportStream;
type Datagram = NoDatagram;
type Future = DialFuture;
fn connect(&mut self, dest: Destination) -> DialFuture;
}

connect clones the connector into a boxed 'static + Send future: an Arc bump for the kind, a clone of the Dialer (its SocketOptions, whose hook is an Arc) and a clone of the Resolver (an Arc). The clones share only immutable configuration and the resolver, whose cache is shared between them and synchronised internally. The result is mapped to Outbound::Stream. NoDatagram is uninhabited, so this connector cannot build an Outbound::Datagram at all. A proxy’s UDP travels inside its stream, and the client codec frames it, not the transport.

This connector is the Conn parameter of concepts/src/client.rs → ProxyClientConnector for every stream-based proxy client, directly or wrapped. supervisor/src/topology/outbound/proxy.rs → ProxyClient<BUF, S, D, C = TransportConnector> wraps a ProxyClientConnector<BUF, Make<S, D>, C, Destination> in a parking_lot::Mutex held only while the dial future is built. C is any Connector<Destination>: a TransportConnector for most protocols, or one that wraps it, as sss’s SssConnector<TransportConnector> wraps each dialed stream in sss’s transform chains. ProxyClientConnector::connect builds a ProxyClientRuntime, which hands the upstream Destination to TransportConnector::connect, and returns a ProxyClientConnecting future. That future polls the runtime’s poll_connected until the dial has completed, the codec’s handshake is done and everything the handshake staged is written and flushed, and only then hands the runtime over. If a dial answered with a datagram socket, the runtime would fail with proxy client runtime needs a stream to the upstream, got a datagram socket (Unsupported); a TransportConnector cannot produce one. A datagram flow travels inside the stream, and since concepts 2.1.2 the runtime flushes the stream after each datagram it writes, so a transport that holds small writes until a flush (a WebSocket sink, sss’s transform chains) does not keep a packet back until the next one. The HTTP, Trojan, VLESS, VMess, Shadowsocks and Shadowsocks 2022 outbounds are all ProxyClient values, and the sss outbound holds two, one sized for TCP and one for UDP (SssOutbound). The AnyTLS outbound is an AnyTlsConnector that dials its pooled sessions through a TransportConnector of its own (see AnyTLS). See Client runtime.

The SOCKS outbound (supervisor/src/topology/outbound/mod.rs → SocksOutbound) dials both of its paths through one TransportConnector. CONNECT goes through its own ProxyClient, built with a clone of it. SocksOutbound::connect_datagram calls TransportConnector::dial directly to open the UDP ASSOCIATE control stream, then SocksUdpLink::associate binds the relay socket through the outbound’s UdpDialer, in the family of the relay address the server answered (udp.bind(AddressFamily::of(relay))). The supervisor dials every proxy server as DialNetwork::Tcp (supervisor/src/build/outbound.rs → tcp). The outbound side is on Outbounds, UDP fan-out and balancers.

environment/src/dial/mod.rs
#[derive(Debug, Clone, Default)]
pub struct Dialer {
pub tcp: TcpDialer,
pub udp: UdpDialer,
}
impl Dialer {
pub fn new(options: SocketOptions) -> Self;
}
environment/src/dial/tcp.rs
/// How long one connect attempt may take before the next address is tried.
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug, Clone)]
pub struct TcpDialer {
options: SocketOptions,
connect_timeout: Duration,
}
impl TcpDialer {
pub fn new(options: SocketOptions) -> Self;
pub fn with_connect_timeout(mut self, timeout: Duration) -> Self;
pub fn options(&self) -> &SocketOptions;
pub fn connect_timeout(&self) -> Duration;
pub fn socket(&self, family: AddressFamily) -> io::Result<TcpSocket>;
pub async fn connect(&self, addr: SocketAddr) -> io::Result<TcpStream>;
pub async fn connect_any(&self, addrs: &[SocketAddr]) -> io::Result<TcpStream>;
}

Dialer::new gives the TCP and UDP dialers clones of one SocketOptions. TransportConnector uses only dialer.tcp. TcpDialer::new sets the connect timeout to DEFAULT_CONNECT_TIMEOUT; with_connect_timeout replaces it, and options() and connect_timeout() read the two fields back. Nothing in the supervisor calls with_connect_timeout, so every proxy upstream is dialed with the 10-second default per attempt.

TcpDialer::socket creates a socket of the family (TcpSocket::new_v4 or new_v6) and applies the policy before it connects:

Policy field Applied by Behaviour
interface SocketOptions::apply → bind_interface Linux and Android bind a name with SO_BINDTODEVICE; Linux, Apple platforms and Windows take an index, Windows through IP_UNICAST_IF / IPV6_UNICAST_IF. Apple refuses a name with binding by interface name needs an interface index on Apple platforms, and Windows with binding by interface name needs an interface index on Windows; Android refuses an index, and other platforms refuse both, with <what> is not supported on <os>
mark SocketOptions::apply → set_mark SO_MARK on Linux and Android; elsewhere a socket mark is not supported on <os>
hook SocketOptions::apply runs the SocketHook on the raw socket; its error refuses the socket
bind_address TcpDialer::socket, through bind_address_for binds only a socket of the address’s own family; a socket of the other family is left to the kernel

<os> is std::env::consts::OS, and those errors are Unsupported. The per-platform details are on Dialers.

The supervisor passes Dialer::new(socket.clone()), where socket is the policy given to SupervisorBuilder::socket_options (supervisor/src/supervisor.rs). Its doc comment says the policy holds for the supervisor’s lifetime, so an apply cannot change it, and that the system resolver (getaddrinfo) opens its sockets inside the C library, where no policy reaches them. etemenanki-app and katana do not call socket_options, so they run with SocketOptions::default(). The mobile bindings pass a protect hook (ffi/src/platform.rs → socket_options), which fails with the platform refused to protect the socket (PermissionDenied) when the platform declines.

TLS uses the system OpenSSL through the openssl (0.10.81 in Cargo.lock) and tokio-openssl (0.6.5) crates. The crate’s vendored-openssl feature builds OpenSSL from source instead (openssl/vendored). On Windows and macOS, rustls-native-certs (0.8.5) is a dependency whatever the features: it lists the platform’s CA store for platform_roots, as Client side describes. The module keeps the OpenSSL builders private: callers choose the certificate material, the trust policy, ALPN and the server name, and protocols/src/transports/tls/config.rs owns the profile and the protocol versions.

protocols/src/transports/tls/config.rs
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Alpn {
None,
Http1,
Http2,
Http2ThenHttp1,
}
impl Alpn {
fn wire_bytes(self) -> Option<&'static [u8]>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VerifyMode {
System,
CustomCa(Vec<u8>),
Insecure,
}
#[derive(Clone)]
pub struct ServerConfig {
acceptor: Arc<SslAcceptor>,
}
impl ServerConfig {
pub fn from_pem(cert_pem: &[u8], key_pem: &[u8], alpn: Alpn) -> io::Result<Self>;
pub async fn accept(&self, tcp: TcpStream) -> io::Result<SslStream<TcpStream>>;
}
#[derive(Clone)]
pub struct ClientConfig {
connector: Arc<SslConnector>,
sni: Arc<str>,
verify_hostname: bool,
}
impl ClientConfig {
pub fn new(sni: impl AsRef<str>, verify: bool, alpn: Alpn) -> io::Result<Self>;
pub fn with_verify_mode(
sni: impl AsRef<str>,
verify_mode: VerifyMode,
alpn: Alpn,
) -> io::Result<Self>;
pub async fn wrap<S>(&self, tcp: S) -> io::Result<SslStream<S>>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin;
}
fn ossl_err<E: std::error::Error + Send + Sync + 'static>(e: E) -> io::Error; // io::Error::other

ClientConfig::wrap is generic over any connected AsyncRead + AsyncWrite + Unpin stream: it performs the client handshake over a TCP socket or over a tunnel some proxy opened. The DNS resolver relies on that to run DNS over TLS and DNS over HTTPS through a stream its dialer opened, which may be a proxied one. ServerConfig::accept takes a TcpStream. The server, the client and the handshake are covered in TLS in detail.

protocols/src/transports/tls/stream.rs
pub enum MaybeTlsStream {
Plain(TcpStream),
Tls(Box<SslStream<TcpStream>>),
}
pub fn tcp_from_std(tcp: std::net::TcpStream) -> io::Result<TcpStream>;
pub async fn accept_optional_tcp(
tcp: std::net::TcpStream,
server: Option<ServerConfig>,
) -> io::Result<MaybeTlsStream>;
pub async fn wrap_optional_tcp(
tcp: TcpStream,
client: Option<ClientConfig>,
) -> io::Result<MaybeTlsStream>;

MaybeTlsStream forwards AsyncRead and AsyncWrite the same way TransportStream does. accept.rs and connect.rs each have a private maybe_tls that builds it from an Option of a borrowed server or client config. That is how the WebSocket and gRPC variants get optional TLS.

Function Input What it does
tcp_from_std a std::net::TcpStream sets it non-blocking, adopts it into tokio with TcpStream::from_std and applies set_keepalive
accept_optional_tcp a std socket and an owned Option<ServerConfig> goes through tcp_from_std, then runs the server handshake when a config is given
wrap_optional_tcp a tokio socket and an owned Option<ClientConfig> runs the client handshake when a config is given

The last two are the public, owned-config versions of maybe_tls. Nothing in the workspace or in katana calls any of the three at this revision; the supervisor accepts tokio sockets, and InboundTransport::accept sets keepalive itself.

protocols/src/transports/keepalive.rs
const TCP_KEEPALIVE_IDLE: Duration = Duration::from_secs(120);
const TCP_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
const TCP_KEEPALIVE_RETRIES: u32 = 3;
pub fn set_keepalive(stream: &TcpStream);

set_keepalive builds a socket2::TcpKeepalive with the three values above and applies it through SockRef::from(stream).set_tcp_keepalive, which also turns SO_KEEPALIVE on. The kernel sends the first probe after 120 s of silence and repeats it every 30 s; after 3 unanswered probes it drops the connection. A peer that vanished without a FIN is therefore noticed about 210 s after the last traffic. The comment on the constants gives the reason: Linux waits two hours before its first probe, and a proxy’s peers disappear without a FIN as a matter of routine (a mobile NAT rebind, a dropped route), so without the schedule the kernel keeps such a socket ESTABLISHED indefinitely and no layer above notices.

The call is best-effort by design: a platform that rejects the options is not a reason to drop the connection. It logs could not enable TCP keepalive: <error> at debug and the connection goes on. As its doc comment puts it, keepalive is a backstop for dead peers, not a substitute for the idle timeouts above it, such as the cores’ RELAY_IDLE_TIMEOUT (300 s, protocols/src/core/mod.rs), the SOCKS relay’s idle timer, the WebSocket carrier’s WS_IDLE_TIMEOUT (300 s, protocols/src/transports/ws/stream.rs) and H2_IDLE_TIMEOUT (30 s) for a gRPC connection with no streams. The last two are on Transports: WebSocket and gRPC.

set_keepalive has three callers:

Caller Sockets
InboundTransport::accept every TCP socket a stream inbound accepts or is handed over (SOCKS, HTTP, Shadowsocks, Shadowsocks 2022, Trojan, VLESS, VMess)
TransportConnector::dial every proxy upstream, including the SOCKS UDP ASSOCIATE control stream
tcp_from_std none at this revision; the function has no callers
protocols/src/transports/proxy_protocol.rs
const SIGNATURE: [u8; 12] = *b"\r\n\r\n\0\r\nQUIT\n";
/// The signature, the version and command, the family and the length.
const FIXED_LEN: usize = 16;
/// The longest header taken, TLVs included.
pub const MAX_V2_LEN: usize = 4096;
/// A LOCAL connection is the relay's own, such as its health check.
const LOCAL: u8 = 0x0;
/// A PROXY connection relays for the client its address block names.
const PROXY: u8 = 0x1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
/// The client a PROXY command names; `None` when it names no TCP client.
pub source: Option<SocketAddr>,
/// From the signature to the end of the address block, TLVs included.
pub len: usize,
}
pub fn decode_v2(bytes: &[u8]) -> io::Result<Header>;
pub async fn read_v2(tcp: &mut TcpStream) -> io::Result<Option<SocketAddr>>;
pub fn parse_v2(header: &[u8]) -> io::Result<Option<SocketAddr>>;

The PROXY protocol header is what a TCP relay sends ahead of its client’s bytes to name that client. Only version 2, the binary form, is read. The module has one decoder and two ways to reach it: read_v2 reads a header off an accepted socket when one was sent, and decode_v2 decodes one already in hand, such as the header a relay on the same host sends beside a connection it hands over. read_v2 and parse_v2 both end in decode_v2 and return its Header::source, so the three accept and refuse exactly the same headers.

decode_v2 decodes the header at the front of bytes. It checks, in this order:

  1. that there are at least FIXED_LEN bytes;
  2. the fixed part, in the private block_len: the 12-byte SIGNATURE, version 2 in the high nibble of byte 12, and an address-block length (bytes 14 and 15, big-endian) of at most MAX_V2_LEN − FIXED_LEN = 4080 bytes, so that the whole header fits in MAX_V2_LEN;
  3. that the whole address block follows the fixed part;
  4. the command, in the low nibble of byte 12: LOCAL or PROXY;
  5. for a PROXY command only, the family in byte 13, and an address block long enough for that family’s addresses.

It returns a Header whose len is FIXED_LEN plus the block length: where whatever follows the header starts. Those bytes are the caller’s, and decode_v2 does not read them.

Command and family Address block needed source
LOCAL (command 0x0), any family byte what the length says, no more None
PROXY (command 0x1), TCP over IPv4 (0x11) 12 bytes Some of the source address and source port
PROXY, UDP over IPv4 (0x12) 12 bytes None
PROXY, TCP over IPv6 (0x21) 36 bytes Some of the source address and source port
PROXY, UDP over IPv6 (0x22) 36 bytes None
PROXY, Unix stream or datagram (0x31, 0x32) 216 bytes, two 108-byte paths None
PROXY, unspecified (0x00) none None
PROXY, any other family byte refused

A None source names no TCP client: as the Header::source doc comment says, the connection’s own peer stands for the client. The family bytes that name none are still held to the length of their addresses, and a family byte the protocol does not define is refused, as the protocol says a receiver must. A LOCAL header’s family and addresses are not read at all. Bytes in the address block after the addresses and ports, the TLVs, are skipped.

A header that starts with the signature but is malformed fails with InvalidData and PROXY protocol v2: <what>:

<what> Cause
the header is cut short fewer than FIXED_LEN bytes
the signature is wrong the first 12 bytes are not SIGNATURE
not version 2 the high nibble of byte 12 is not 2
the header is too long the length is above 4080, so the header would be longer than MAX_V2_LEN
the address block is cut short fewer bytes follow the fixed part than the length says
unknown command the low nibble of byte 12 is neither 0 nor 1
unknown address family a PROXY command with a family byte the table above does not list
the IPv4 address block is cut short a TCP or UDP over IPv4 block under 12 bytes
the IPv6 address block is cut short a TCP or UDP over IPv6 block under 36 bytes
the Unix address block is cut short a Unix block under 216 bytes

MAX_V2_LEN’s doc comment gives the reason for the cap: an IPv6 address block is 36 bytes, and the rest of a block is TLVs that nothing here reads, so a longer header is refused rather than buffered.

read_v2 reads one header off the front of an accepted socket:

  1. It peeks at the front of the socket into a FIXED_LEN buffer, consuming nothing. If the peer has closed, or the bytes seen so far are not a prefix of the 12-byte SIGNATURE, it returns None and leaves every byte unread. A TLS record starts with 0x16 and the signature with 0x0D, so a direct TLS client is told apart at its first byte, without waiting for more.
  2. While the peeked bytes are still a prefix of the signature but fewer than FIXED_LEN, it sleeps 5 ms and peeks again: a header split across segments is waited for. read_v2 has no deadline of its own; its caller bounds it.
  3. It runs the peeked fixed part through block_len, so a wrong version or a length above 4080 is refused before anything is consumed. It then reads exactly FIXED_LEN plus that length off the socket and hands those bytes to decode_v2. The bytes after the header stay on the socket for the transport.

read_v2 returns None both for a connection that does not start with a header and for a header that names no TCP client. parse_v2 is decode_v2 reduced to the source.

Whether a TCP listener reads a header is the inbound’s choice. InboundSpec::proxy_protocol (supervisor/src/topology/spec_plan/inbound.rs) asks for it, and build_handler copies it into StreamInbound::proxy_protocol (supervisor/src/topology/inbound/mod.rs). Validation refuses it on any bind but TCP (see Validation). katana sets it on its TCP binds (src/lower/inbound.rs → lower_inbound), so katana’s TCP inbounds read a v2 header when one is sent. etemenanki-app and the mobile bindings always leave it false. What the supervisor does with the address is in Accepting a socket.

decode_v2 has one caller outside this module: supervisor/src/system/handoff.rs → receive. A relay on the same host hands a client’s TCP socket over on an inbound’s handoff socket, in one message that carries the socket and a PROXY v2 header naming its client. receive reads that message into a buffer of MAX_V2_LEN + 1 bytes, one more than the longest header, so a byte after a header of the full length is read too. It decodes the header with decode_v2 and refuses the handoff when Header::len is not the whole message, with the text bytes after the PROXY header. The handoff socket and its exchange are on Listeners and the serve loop.

supervisor/src/serve.rs → run_stream_inbound accepts a socket and spawns Connection::serve_socket for it (see Listeners and the serve loop). serve_socket branches on the AcceptedSocket (supervisor/src/system/listener.rs):

  • AcceptedSocket::Unix (compiled on Unix only): serve_connection runs inline on the tokio::net::UnixStream, with no transport, no local IP and no keepalive. The stream reaches the runtime as a UnixStream, not a TransportStream.
  • AcceptedSocket::Tcp: the connection’s source starts as the peer captured at accept. When StreamInbound::proxy_protocol is set, it runs read_v2 under PROXY_HEADER_TIMEOUT (10 s, supervisor/src/serve.rs). A header that names a client makes that address the source, in its canonical form (an IPv4-mapped IPv6 address becomes IPv4), and Session::set_source records it on the socket’s session. A connection without a header, or with one that names no TCP client, keeps its socket peer. A malformed header drops the connection, logged at debug as dropping a connection from <peer>: <error>; a timeout drops it with nothing logged.
  • AcceptedSocket::Handoff (compiled on Unix only): the accepted connection is a relay’s control connection on the inbound’s handoff socket. supervisor/src/system/handoff.rs → receive takes the TCP socket the relay hands over on it, and its client: the one the PROXY v2 header beside it names, or the socket’s own peer for a LOCAL header or an address that names no TCP client, in canonical form. Session::set_source records it on the session. Nothing is read off the TCP socket itself, so its first byte is the client’s. A handoff that is refused or never arrives serves nothing. The exchange is on Listeners and the serve loop.

Both TCP branches end in Connection::serve_tcp(tcp, source), which serves a TCP socket whose client is known, however it arrived:

  1. A source the supervisor’s guard has banned (supervisor/src/guard.rs → Guard::is_banned) is dropped.
  2. It reads local_ip from tcp.local_addr(); for a handed-over socket, that is the address the relay accepted it on.
  3. It runs the inbound’s InboundTransport::accept(tcp, sink). On a WebSocket inbound with StreamInbound::real_ip, the sink first lets a client that a proxy in the trusted networks names in the upgrade’s header stand in for the source; such a client is held to the same bans and recorded on the socket’s session with Session::set_source (see Transports: WebSocket and gRPC). The sink hands the source to each connector it builds, and to the session it opens for each gRPC stream. On a VLESS inbound that serves the Vision flow, the sink wraps the REALITY stream with into_vision_server before the core sees it; a failure is logged at debug as <tag>: vision setup failed: <error> and serves nothing.
  4. When accept returns Disposition::Camouflage, the socket belongs to the cover site. serve_tcp drops the connection’s handshake permit, keeps its live permit, logs <tag>: <source> goes to dest: <reason> at debug, where the reason is a category, and runs the relay with RELAY_IDLE_TIMEOUT as its idle limit; the relay’s end is logged as <tag>: relay to dest ended: <error>. Nothing in it is reported to the guard. See REALITY transport.

For a transport that yields one stream (TCP, TLS, WebSocket, REALITY), the sink serves it as the socket’s own session, through Shared::connector_for. For gRPC, each HTTP/2 stream is a session of its own (see Transports: WebSocket and gRPC).

sequenceDiagram
  participant L as run_stream_inbound
  participant C as serve_socket
  participant T as InboundTransport::accept
  participant H as serve_h2
  participant K as sink
  L->>C: spawn
  alt AcceptedSocket::Tcp
    opt proxy_protocol
      C->>C: read_v2 within PROXY_HEADER_TIMEOUT
    end
  else AcceptedSocket::Handoff
    C->>C: handoff::receive, decode_v2
  end
  C->>C: serve_tcp drops a banned source
  C->>T: accept(tcp, sink)
  T->>T: set_keepalive
  T->>T: within(label, TLS and upgrade or h2 handshake)
  alt Tcp, Tls, Ws or an authenticated REALITY client
    T->>K: sink(stream)
    opt Ws with real_ip
      K->>K: real_ip_source names the client
    end
    K->>K: serve as the socket's own session
  else Grpc
    T->>H: serve_h2(conn, heard, paths, peer, sink)
    loop each tunnel stream
      H->>K: sink(TransportStream::Grpc)
    end
  end
  opt REALITY socket that is not a client
    T-->>C: Ok(Disposition::Camouflage)
    C->>C: drop the handshake permit, relay to the cover site
  end
  opt accept fails
    T-->>C: Err(e)
    C->>C: debug, inbound transport failed
  end

Sessions, tokens and their lifetimes are on Users, principals and sessions; the accept loop and the drivers are on Listeners and the serve loop.

dial runs four steps:

flowchart LR
  d["dial(dest)"] --> u{"dest.network is Udp?"}
  u -- "yes" --> e["Err Unsupported"]
  u -- "no" --> r["destination_to_socketaddrs"]
  r --> c["TcpDialer::connect_any"]
  c --> k["set_keepalive"]
  k --> w["TransportKind::wrap"]
  w --> s["TransportStream"]
  1. Refuse UDP. A Destination whose network is DialNetwork::Udp fails at once with io::ErrorKind::Unsupported and the text a proxy transport carries no datagrams of its own. Every other DialNetwork value is dialed as TCP.
  2. Resolve. protocols/src/helpers/address_family.rs → destination_to_socketaddrs calls resolve_candidates("dial", dest, strategy, FamilySupport::both(), resolver). An IP destination skips the resolver. A domain goes to Resolver::resolve, which returns every address, de-duplicated, in the backend’s order. select_candidate_ips then filters and orders them by the outbound’s address_family strategy, and each address gets the destination’s port.
  3. Connect. environment/src/dial/tcp.rs → TcpDialer::connect_any tries the addresses in order, one at a time. TcpDialer::connect creates a socket of the address’s family through TcpDialer::socket, which applies the socket policy (see The dialer and the socket policy). Each attempt is bounded by the dialer’s connect timeout, DEFAULT_CONNECT_TIMEOUT (10 s). The first success wins. If all fail, the error lists every address with its failure.
  4. Keepalive and wrap. set_keepalive runs on the connected socket, then TransportKind::wrap layers TLS, WebSocket, gRPC or REALITY on top.

Resolver::resolve_with_ttl (protocols/src/dns/mod.rs), under resolve, answers in this order: a host string that parses as an IP address answers itself (with the resolver’s maximum TTL), then the resolver’s hosts entries, then an unexpired cache entry, then a lookup through the backends in order. A lookup that answers with no address is refused with dns: <host> did not resolve (NotFound) and is not cached. See DNS resolver.

destination_to_socketaddrs passes FamilySupport::both() because a TCP dialer lets the kernel pick the source address, so only the strategy removes addresses here. That is also why no_candidate_error, which adds (local address supports …) only when the support is not both(), never adds it on this path. The strategy values, their spellings and the WireGuard case, which does pass a narrower FamilySupport, are on Protocol crate foundations.

The attempts in connect_any are sequential, not raced (this is not Happy Eyeballs). The doc comment gives the reason: a dual-stack host routinely resolves a name to an address it cannot reach, such as a stale AAAA record or an IPv6 route that black-holes, so giving up after the first failure would strand the destination for as long as DNS keeps that order. Every failure is reported, so the cause is not lost.

Alpn maps to fixed wire bytes through the private Alpn::wire_bytes, which returns None for Alpn::None and the constant otherwise. The constants are length-prefixed protocol names, as ALPN encodes them.

Variant Constant Wire bytes
Alpn::None none ALPN is not configured
Alpn::Http1 ALPN_HTTP1 \x08http/1.1
Alpn::Http2 ALPN_H2 \x02h2
Alpn::Http2ThenHttp1 ALPN_H2_HTTP1 \x02h2\x08http/1.1

A server with ALPN installs a select callback that runs select_next_proto(server_protos, client_protos). When the client offers nothing in common, the callback returns AlpnError::NOACK: the handshake goes on without an ALPN extension instead of failing. A client with ALPN calls set_alpn_protos and offers the list. Alpn::Http2ThenHttp1 exists in the API, but no caller in the workspace or in katana uses it at this revision.

Which ALPN each transport uses is fixed by the supervisor’s build, the same on both sides:

Transport Server (build_transport) Client (transport_connector)
tls Alpn::None Alpn::None
ws with TLS Alpn::Http1 Alpn::Http1
grpc with TLS Alpn::Http2 Alpn::Http2

ServerConfig::from_pem builds the acceptor in this order. Every OpenSSL error becomes io::Error::other through ossl_err.

  1. Parse the certificate bundle with X509::stack_from_pem. The first certificate is the leaf. If the bundle holds no certificate, which is also what a file that is not PEM at all parses to, it fails with InvalidInput and no certificate in PEM bundle. A PEM block that does not decode fails with OpenSSL’s error text instead.
  2. Parse the private key with PKey::private_key_from_pem. An empty or non-PEM key fails with OpenSSL’s decoder error.
  3. Start from SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()), the openssl crate’s rendering of Mozilla’s intermediate server profile (version 5). It sets NO_TLSV1 | NO_TLSV1_1, loads the RFC 7919 ffdhe2048 DH group, and fixes the cipher lists shown below. It leaves the key-exchange groups to OpenSSL’s defaults.
  4. Set the minimum version to TLS 1.2 explicitly with set_min_proto_version(Some(SslVersion::TLS1_2)), so the floor does not depend on the option bits alone. TLS 1.3 stays enabled; the doc comment says the acceptor allows TLS 1.2 and TLS 1.3 only.
  5. Install the key (set_private_key) and the leaf (set_certificate), add every further certificate in the bundle with add_extra_chain_cert, and run check_private_key, so a key that does not belong to the leaf fails at build time. Because the key is installed before the certificate, OpenSSL drops a key that does not match when set_certificate runs, and check_private_key then reports no private key assigned rather than a mismatch.
  6. Turn read-ahead on (see Read-ahead).
  7. Install the ALPN select callback if alpn is not Alpn::None.

Neither side sets a cipher list of its own, so the cipher configuration comes from the openssl crate (0.10.81 at this revision), not from this repository:

Side TLS 1.2 cipher list TLS 1.3 suites
Server (mozilla_intermediate_v5) ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-RSA-AES256-GCM-SHA384, ECDHE-ECDSA-CHACHA20-POLY1305, ECDHE-RSA-CHACHA20-POLY1305, DHE-RSA-AES128-GCM-SHA256, DHE-RSA-AES256-GCM-SHA384 TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256
Client (SslConnector::builder) DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK OpenSSL’s defaults

Both builders also start from the crate’s common context options, which include NO_COMPRESSION, NO_SSLV2 and NO_SSLV3. After bumping the openssl crate, compare SslAcceptor::mozilla_intermediate_v5 and SslConnector::builder in the new version with this table.

accept creates each connection’s Ssl from the shared context (Ssl::new(self.acceptor.context())), wraps the socket in SslStream::new and drives the server handshake with SslStream::accept through Pin::new(&mut stream), mapping its error with ossl_err. There is no client-certificate request: the server authenticates itself only.

ClientConfig::with_verify_mode starts from SslConnector::builder(SslMethod::tls()), which already turns on peer verification (SslVerifyMode::PEER), loads the default trust paths and sets the client cipher list above. It then sets the minimum version to TLS 1.2, so TLS 1.3 is negotiated when the peer supports it. The verification policy decides the rest:

VerifyMode Chain verified against Hostname checked Builder calls
System the platform and OpenSSL default trust store, and on Android, iOS, Windows and macOS the platform roots yes trust_system
CustomCa(pem) the same system trust plus every certificate in pem yes trust_system, then X509::stack_from_pem and cert_store_mut().add_cert per certificate
Insecure nothing no set_verify(SslVerifyMode::NONE)

The private trust_system calls set_default_verify_paths() and, on Android, iOS, Windows and macOS, adds every certificate of platform_roots::ROOTS to the builder’s store, ignoring one the store refuses so the rest are kept. The module doc of protocols/src/transports/tls/platform_roots.rs gives the reason: OpenSSL built from source looks under its build-time OPENSSLDIR. That directory does not exist on a phone, and rustls-native-certs looks in the same Unix places on Android and iOS. On Windows it is a placeholder that is never a real path, and on macOS it is /usr/local/ssl, which the system does not have, so a client built with vendored-openssl there trusted no CA at all before protocols 6.2.1 and failed every TLS handshake that verifies. A system OpenSSL that finds CAs of its own loses nothing: a certificate added twice is refused, and the refusal ignored. ROOTS is a LazyLock<Vec<X509>>, built once per process, and each OS fills it differently:

  • Android. OpenSSL also ignores SSL_CERT_FILE there, because app processes run with AT_SECURE, and Android keeps one PEM file per CA, named by the old subject hash, which OpenSSL’s directory lookup does not use either. So the store is read file by file: the first of /apex/com.android.conscrypt/cacerts (the updatable Conscrypt module, Android 14 and newer) and /system/etc/security/cacerts that yields any certificate is the store, and a file that cannot be read or parsed is skipped. If neither yields one, it logs tls: no system CA certificate could be read from ["/apex/com.android.conscrypt/cacerts", "/system/etc/security/cacerts"] at warn and the list is empty.
  • iOS. An app has no store it can reach: there are no files, and the Security framework evaluates a chain but never lists its anchors. ROOTS is bundled(): Mozilla’s roots as the webpki-root-certs crate ships them (TLS_SERVER_ROOT_CERTS, DER), each converted with X509::from_der, and one OpenSSL refuses is skipped. The module doc names the cost: CAs that a user or an MDM profile installed are not trusted, and the set changes only when the app is rebuilt. A CustomCa still adds its certificates on top, as on every other OS.
  • Windows and macOS. ROOTS is native(): rustls_native_certs::load_native_certs() lists the platform’s own store, the Windows certificate store or the macOS keychains, and each DER certificate is converted with X509::from_der; one that cannot be converted is skipped. Every error the listing reports is logged at warn as tls: reading the system's CA certificates: <error>, and when no certificate is left, tls: no system CA certificate could be read follows at warn and the list is empty. CAs the user or the administrator added to that store are trusted, unlike on iOS.

On every other OS, Linux included, platform_roots is compiled only into the crate’s unit tests, and trust_system is set_default_verify_paths() alone.

CustomCa adds the given CAs to the system roots; it does not replace them. A bundle with no certificate in it, empty or not PEM at all, fails with InvalidInput and no certificate in CA PEM bundle. A PEM block that does not decode fails with OpenSSL’s error text. Both are raised by with_verify_mode, so --test reports them. If ALPN is requested, set_alpn_protos runs next, and read-ahead is turned on last (see Read-ahead). The config holds no client certificate.

ClientConfig::new(sni, verify, alpn) is shorthand: verify = true means VerifyMode::System, and false means VerifyMode::Insecure. Only the pipeline tests call it.

Hostname checking is set per session, not on the builder. OpenSSL’s ConnectConfiguration turns it on by default, so ClientConfig stores verify_hostname (true for System and CustomCa, false for Insecure), and wrap calls set_verify_hostname(false) when it is false. wrap then calls into_ssl(&self.sni), wraps the stream in SslStream::new and drives the client handshake with SslStream::connect through Pin::new(&mut stream), mapping errors with ossl_err. into_ssl sends the name as SNI and, when hostname checking is on, checks the certificate against it. Both behaviours come from the openssl crate:

  • a DNS name is sent as SNI and checked with OpenSSL’s host check, with partial wildcards refused (NO_PARTIAL_WILDCARDS); OpenSSL falls back to the subject CN when the certificate has no DNS name;
  • an IP literal is not sent as SNI (the extension carries only host names) and is checked against the certificate’s IP addresses.

Insecure still sends the name as SNI; it only skips the chain and the name check.

protocols/src/transports/tls/config.rs
fn read_ahead(builder: &mut SslContextBuilder); // builder.set_read_ahead(true)

Both ServerConfig::from_pem and ClientConfig::with_verify_mode call the private read_ahead on their builder, so every SslStream either one makes reads ahead. Without it, OpenSSL reads each record as its 5-byte header and then its body, two reads of the socket a record. With it, OpenSSL reads what the socket holds. The doc comment gives the reason both ends do it: either one’s reads are mostly records, on a server the small ones a carrier’s client sends, on a client the full ones of a download.

Reading ahead is safe here because of two facts the doc comment names. Records read ahead wait inside OpenSSL and come out of the next SSL_read, which SslStream always makes before it waits on the socket, so a record already pulled in is never stuck behind a socket that has nothing more to say. And nothing in the module takes the socket back from TLS to read it raw, which would miss bytes OpenSSL already holds. A change that unwraps an SslStream to reuse its socket has to deal with that buffer first.

The DNS resolver builds the ClientConfig of each DNS-over-TLS and DNS-over-HTTPS upstream with the same with_verify_mode (see Other users of the TLS types), so those connections read ahead too. The Hysteria 2 paths use rustls and are not affected.

ClientConfig and VerifyMode are not private to the transports:

User What it builds ALPN and trust See
protocols/src/dns/mod.rs → Upstream::new one ClientConfig per DNS-over-TLS or DNS-over-HTTPS upstream, built once so a query does not rebuild the connector; the resolver calls wrap on whatever stream its dialer opened, which may be a proxied one Alpn::None with the backend’s server_name for DNS over TLS, Alpn::Http1 with its host for DNS over HTTPS; VerifyMode::CustomCa when a CA is configured, System otherwise DNS resolver
protocols/src/hysteria/connection.rs → tls_config a rustls client configuration with the ring provider, because QUIC does not run over OpenSSL here; VerifyMode is its trust vocabulary its platform roots come from system_roots, which loads the native store and, on Android and iOS, adds platform_roots::ROOTS converted to DER; its CustomCa also adds to those roots, and it refuses a bundle with no certificate (hysteria2: the CA file contains no certificates) Hysteria 2: protocol and client
supervisor/src/build/inbound.rs → hy2_handler the Hysteria 2 server’s rustls configuration, from its own ServerTlsSpec PEM bytes (Hysteria2InboundSpec.tls) through hysteria::server::endpoint::server_config; it does not use ServerConfig not Alpn or VerifyMode Hysteria 2: server

The comment on the DNS-over-HTTPS case says why ALPN names http/1.1 explicitly: a server that will not speak it then fails the handshake loudly instead of answering something the client cannot read.

A change to VerifyMode’s meaning therefore reaches three places: the TCP transports, the DNS resolver and the Hysteria 2 client. etemenanki-app’s verify_mode helper in app/src/lower.rs fills it for both a [stream] block (key prefix tls.) and a Hysteria 2 outbound’s settings (no prefix).

Three owners stand between a stream block and a running transport. A front end lowers the block into the supervisor’s transport spec, the supervisor validates the spec, and the supervisor’s build turns the valid spec into the values above.

flowchart TB
  app["etemenanki-app: resolve_stream, inbound_transport, outbound_transport"] --> spec["InboundTransportSpec, OutboundTransportSpec"]
  kat["katana: stream, lower_outbound"] --> spec
  spec --> v["validate.rs"]
  v --> bi["build_transport"]
  v --> bo["transport_connector"]
  bi --> it["InboundTransport"]
  bo --> tc["TransportConnector::new"]
supervisor/src/topology/spec_plan/transport.rs
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum StreamShape {
/// Plain TCP.
Tcp,
/// TLS over TCP — this project's own `network = "tls"`.
Tls,
Ws {
path: String,
host: Option<String>,
tls: bool,
},
Grpc {
service: String,
authority: Option<String>,
tls: bool,
},
/// REALITY over TCP: a TLS 1.3 of its own, under VLESS only.
Reality,
}
impl StreamShape {
pub fn uses_tls(&self) -> bool;
}
pub struct ServerTlsSpec {
pub cert_pem: Vec<u8>,
pub key_pem: Secret<Vec<u8>>,
}
pub struct ClientTlsSpec {
/// The SNI sent, and the name the certificate is checked against.
pub server_name: String,
/// Which roots the certificate is verified against, if it is at all.
pub verify: VerifyMode,
}
pub struct InboundTransportSpec {
pub shape: StreamShape,
pub tls: Option<ServerTlsSpec>,
pub reality: Option<RealityServerSpec>,
}
pub struct OutboundTransportSpec {
pub shape: StreamShape,
pub tls: Option<ClientTlsSpec>,
/// Present exactly when the shape is Reality.
pub reality: Option<RealityClientSpec>,
/// Which family of the upstream's addresses is dialed.
pub address_family: AddressFamilyStrategy,
}

StreamShape lives in the supervisor so that inbounds and outbounds of every front end share one shape. Its doc comment gives the reason: with one shape, a rule about which fields a network requires cannot end up on one side only, and a rule on one side only was the root cause of a group of bugs in which a config that asked for TLS got plaintext. uses_tls() is false for Tcp and Reality, true for Tls, and the tls flag for Ws and Grpc: whether this project’s TLS is layered, and so whether TLS material must sit beside the shape. REALITY brings a TLS 1.3 of its own and no ServerTlsSpec; its settings are the spec’s reality field, a RealityServerSpec or RealityClientSpec with the values already decoded (see REALITY transport). StreamShape is #[non_exhaustive], so a front end that matches it keeps a wildcard arm.

The two transport specs differ in what they allow:

  • InboundTransportSpec.tls must be Some exactly when uses_tls() holds, and reality exactly when the shape is Reality. A WebSocket host of None accepts any Host, since an inbound has nothing to borrow a name from.
  • OutboundTransportSpec must carry no gaps: a WebSocket host and a gRPC authority must be Some, filled by the front end from the TLS name or the server address, tls must be Some exactly when uses_tls() holds, and reality exactly when the shape is Reality.

The private keys (the TLS key and REALITY’s X25519 key) are wrapped in Secret. All seven types derive Debug, Clone, PartialEq and Eq.

etemenanki-app reads the block into app/src/config.rs → StreamConfig (network, security, tls, ws, grpc, reality; every block #[serde(deny_unknown_fields)]). app/src/transport.rs → resolve_stream defaults an absent network to "tcp". It takes security = "reality" first, as its own shape, StreamShape::Reality, which it allows only over network = "tcp" (<ctx>: security = "reality" needs network = "tcp"); for anything else it calls tls_layer, which validates security against the network and fails closed: only an absent, empty or "none" value and "tls" are accepted, and Xray’s network = "tcp" with security = "tls" is refused with a message that points to network = "tls". It then builds the StreamShape, with ws.path defaulting to "/" and grpc.service_name required. In app/src/lower.rs, inbound_transport, which every inbound protocol that takes a transport goes through (SOCKS and Shadowsocks included), reads the tls.cert_file and tls.key_file bytes into a ServerTlsSpec when the shape layers TLS, decodes [inbound.stream.reality] into a RealityServerSpec when the shape is Reality, and gives a Unix listener the plain Tcp shape after reject_stream_settings. outbound_transport parses address_family, fills the WebSocket host and gRPC authority (ws.host or grpc.authority, then tls.server_name, then server) and the TLS server name (tls.server_name, then server), refusing the config rather than guessing a name, and maps tls.allow_insecure and tls.ca_file to a VerifyMode with verify_mode; for a Reality shape it decodes [outbound.stream.reality] into a RealityClientSpec instead. The protocols that take no transport (Hysteria 2, TUN, and the outbounds that dial no proxy server) refuse a non-plain stream block through reject_stream_settings. Lowering does not parse the PEM bytes; the supervisor does when it builds the values. Every rule and error text is on etemenanki-app: from TOML to a spec.

A katana node arrives as helium-node-api’s node config, the contract katana and helium share, so its transport is the contract’s Transport (Tcp, Ws { path, host } or Grpc { service_name }) with the protocol’s security beside it. Lowering never sees a transport the kernel cannot serve. src/lower/inbound.rs → stream turns the two into the transport spec:

Node StreamShape
TCP without TLS Tcp
TCP with TLS Tls
WebSocket Ws, with the node’s path and host, and tls from its security
gRPC Grpc, with the node’s service name, authority: None and tls from its security
VLESS with security reality Reality, with a RealityServerSpec from the node’s REALITY settings (reality_spec)

What stream judges is this host’s part. On every node but REALITY it refuses cert.reject_unknown_sni and the ACME certificate modes (dns, http, tls) with node requests kernel-unsupported feature: <feature> (Unsupported). A TLS node needs cert.mode = "file" (TLS node requires cert.mode = "file") and both cert.cert_file and cert.key_file (TLS node requires cert.cert_file and cert.key_file), whose bytes become the ServerTlsSpec; a REALITY node carries no certificate, so these certificate rules do not apply to it. lower_stream_protocol puts the transport under the node’s protocol: a Shadowsocks node rides the transport the panel names for it, as Xray serves one, and relays TCP alone; Trojan, SOCKS and HTTP nodes always run over TLS; an AnyTLS node gets the Tls shape. How a REALITY node’s settings become the spec is on Lowering inbounds and outbounds.

What the contract cannot hold is refused before lowering, by the panel client that reads the answer. A helium answer is the contract already: its transports have no TCP header, and REALITY runs over transport tcp only (security reality runs over transport tcp only). A UniProxy (newV2board) answer is converted in src/api/newv2board.rs → transport, from the node’s network and its transport settings:

  • tcp, raw or no network is Tcp. ws or websocket is Ws, with the settings’ path (/ when it is missing or empty) and the Host in their headers (none when it is empty). grpc or gun is Grpc, with the settings’ serviceName.
  • httpupgrade is refused as the feature httpupgrade transport, splithttp and xhttp as splithttp transport, and any other network as transport "<name>", each with node requests kernel-unsupported feature: <feature>.
  • A Tcp node’s settings may carry a TCP header, which plain_tcp_header checks, REALITY nodes included, since REALITY rides TCP. No header, a null header, an object with no type or a null type, and the type "none" in any letter case are bare TCP. Any other type, the empty string included, is refused as the feature tcp header type "<type>", for example node requests kernel-unsupported feature: tcp header type "http". A header that is not an object fails with tcp header is not an object, and a type that is not a string with tcp header type is not a string. The comment on plain_tcp_header gives the reason: served as bare TCP, the clients of a node with V2Ray’s header obfuscation would open with an HTTP head, fail to authenticate and count toward their IP’s ban.
  • A Trojan node is TLS over TCP, whatever transport the panel names. A SOCKS or HTTP node without TLS is refused as socks without TLS or http without TLS.
  • The node is then held to the contract’s own rules (validate), so a UniProxy node meets the rules a helium one does: a WebSocket path with no query but ?ed=N, a WebSocket host without a port, a non-empty gRPC service name (Transports: WebSocket and gRPC).

A refusal is the panel client’s error, so a node logs it as its node_info failing, for example node <id>: node_info failed: parse UniProxy config response: node requests kernel-unsupported feature: tcp header type "http"; retrying in <n>s when it starts.

Beside the transport, lower_inbound sets InboundSpec::real_ip from [node.controller]’s real_ip_header and real_ip_from when the node’s transport is WebSocket, and leaves it None on every other transport and on Hysteria 2. Half a setting, or a typo in either key, is refused on every node; see Transports: WebSocket and gRPC and Lowering inbounds and outbounds. When [node.controller] sets handoff_dir, lower_inbound also gives every node on a TCP bind an InboundSpec::handoff at <handoff_dir>/<port>.sock, or <handoff_dir>/<listen_ip>-<port>.sock when the node listens on one address rather than all (handoff_file), mode 0o660, in the group handoff_group names (katana’s own when it is unset); a Hysteria 2 node gets none. etemenanki-app and the mobile bindings always leave handoff at None.

katana’s outbounds (src/lower/outbound.rs → lower_outbound) always carry OutboundTransportSpec { shape: StreamShape::Tcp, tls: None, reality: None, address_family }, so katana builds no TLS, WebSocket or gRPC dial transport. The supervisor validates and builds katana’s specs exactly as it does the app’s. katana’s lowering is on Lowering inbounds and outbounds.

supervisor/src/build/validate.rs checks every transport spec on apply, from any front end, because the fields are public and a spec can be built by hand. inbound_transport runs once for every protocol InboundProtocolSpec::transport names (SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS and sss), so a protocol added to that list meets the same rules: the plain Tcp shape on a Unix bind, TLS material exactly when the shape layers TLS, REALITY settings exactly with the Reality shape, and that shape only under VLESS (reality is for vless only). A SOCKS inbound over anything but plain TCP must turn udp off (socks serves udp associate over plain tcp only; turn udp off to wrap it in a transport), because its relay’s datagrams go to a UDP socket beside the listener, in the clear; an AnyTLS inbound needs the Tls shape. On any inbound, proxy_protocol on a bind other than TCP is refused with only a tcp listener reads a PROXY protocol header, and so is a handoff socket, with only a stream inbound on a tcp listener takes a handoff socket (its path and mode are checked too); a real_ip setting on anything but a WebSocket transport on a TCP bind, with no trusted network, or with a header name that is not one is refused too (the texts are on Transports: WebSocket and gRPC); and on a platform without Unix sockets a Unix bind is refused with unix sockets are not served on <os>, and a handoff socket with handoff sockets are not served on <os>. For every outbound with a proxy upstream (SOCKS, HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, sss and AnyTLS) it requires the same TLS pairing, a WebSocket host and a gRPC authority, REALITY settings exactly with the Reality shape, and that shape only under VLESS. Both sides share tls_mismatch, which words the TLS error by which half is missing. A failure is ApplyError::Invalid and refuses the whole spec. The rules, their texts and their tests are on Validation and apply errors.

supervisor/src/build/inbound.rs
fn build_transport(
spec: &InboundTransportSpec,
real_ip: Option<&RealIpSpec>,
socket: &SocketOptions,
) -> io::Result<InboundTransport>;

build_handler calls build_transport for every protocol InboundProtocolSpec::transport names, on a TCP bind, with the inbound’s real_ip and the supervisor’s socket policy. A Unix bind gets InboundTransport::Tcp; Hysteria 2 and TUN take no transport. A closure tls(alpn) turns spec.tls into Some(ServerConfig::from_pem(&cert_pem, key_pem.expose(), alpn)), or None.

StreamShape InboundTransport Server ALPN
Tcp InboundTransport::Tcp none
Tls InboundTransport::Tls(tls(Alpn::None)); missing tls if absent Alpn::None
Ws { path, host, .. } InboundTransport::Ws { route, tls: tls(Alpn::Http1) }, where route is WsRoute::new(path), with .host(host) when host is Some and .real_ip_header(&real_ip.header)? when real_ip is Some Alpn::Http1 when TLS
Grpc { service, .. } InboundTransport::grpc(service, tls(Alpn::Http2)); the constructor takes only the service Alpn::Http2 when TLS
Reality InboundTransport::Reality(build_reality(reality, socket)), a RealityServer that dials its cover site with Dialer::new(socket.clone()) and the system resolver, outside the routing plane; missing reality settings if absent none
supervisor/src/build/outbound.rs
fn transport_connector(
spec: &OutboundTransportSpec,
dns: &Dns,
socket: &SocketOptions,
vision: Option<[u8; 16]>,
) -> io::Result<TransportConnector>;

build_outbound calls transport_connector for each proxy outbound, with vision set to the user id only for a VLESS outbound with the Vision flow. A closure tls(alpn) turns spec.tls into Some(ClientConfig::with_verify_mode(&server_name, verify.clone(), alpn)), or None.

StreamShape TransportKind Client ALPN Error when a field is missing
Tcp TransportKind::Tcp none none
Tls TransportKind::Tls(tls(Alpn::None)) Alpn::None missing tls
Ws { path, host, .. } TransportKind::ws(host, path, tls(Alpn::Http1)) Alpn::Http1 when TLS missing ws host
Grpc { service, authority, .. } TransportKind::grpc(authority, service, tls(Alpn::Http2)) Alpn::Http2 when TLS missing grpc authority
Reality TransportKind::reality(client), and .vision(uuid) when vision is set, where client is RealityClientConfig::from_bytes(server_name, public_key, short_id) with the client version when the spec sets one none missing reality

The result is TransportConnector::new(kind, Dialer::new(socket.clone()), dns.servers.clone(), spec.address_family). socket is the supervisor’s socket policy. supervisor/src/build/dns.rs → Dns holds three things: servers, the resolver that looks up the proxy servers the outbounds dial; destinations, the resolver for the destinations the process connects to itself (through freedom, and inside a WireGuard tunnel); and service, the DNS service when the spec asks for one. Only servers goes into a TransportConnector. See Supervisor DNS.

Both builders ignore the shape’s own tls flag and layer TLS exactly when the spec carries TLS material; validation keeps the two equal. The missing … errors are InvalidInput and cannot occur for a validated spec. build_handler, and with it build_transport, runs while an apply stages its users (supervisor/src/supervisor.rs → Actor::stage, then stage_users, which is handed the supervisor’s socket policy for a REALITY inbound’s dial), off the runtime; transport_connector runs in Actor::prepare. Both steps come before anything visible changes, and prepare, the step of an apply that does everything that can fail with no visible effect, wraps the errors of both in ApplyError::Build. So a certificate, key or CA that does not parse refuses the whole apply. etemenanki_supervisor::check builds a fresh Actor with SocketOptions::default(), runs stage, and runs the same prepare with binding off (prepare(&plan, &spec, users, false)). etemenanki-app’s --test goes through app/src/instance.rs → check, which reads the file and calls check_bytes, which lowers it and calls etemenanki_supervisor::check; so --test reports these errors too (see Build time). The rest of build_outbound is on Outbounds, UDP fan-out and balancers.

Invariant Enforced by Pinned by
Every stream an InboundTransport yields and every stream a TransportConnector dials has the same type, whatever the transport TransportStream is the only Accepted type and the only Connector::Stream of TransportConnector tcp_round_trip, tls_round_trip, ws_round_trip, grpc_round_trip in protocols/tests/pipeline/transports.rs
A TCP socket accepted by InboundTransport or dialed by TransportConnector gets the keepalive schedule (best-effort) set_keepalive at the top of InboundTransport::accept and after connect_any in TransportConnector::dial no test pins it
InboundTransport::accept gives its transport handshake at most 10 s, REALITY excepted within wraps the TLS, upgrade and HTTP/2 handshakes in tokio::time::timeout(TRANSPORT_HANDSHAKE_TIMEOUT, …); the REALITY decision keeps its own deadline no test pins it
One gRPC connection yields one stream per HTTP/2 tunnel stream serve_h2 calls sink for each accepted request on a known path one_grpc_connection_carries_many_streams in protocols/tests/pipeline/transports.rs
Records read ahead reach the reader without more bytes from the socket, on both ends read_ahead on both builders; SslStream makes an SSL_read before it waits on the socket, and nothing reads the socket raw after TLS records_read_ahead_come_out_without_more_from_the_socket in protocols/tests/unit/transports/tls_config.rs
A TLS server never negotiates below TLS 1.2 mozilla_intermediate_v5 plus set_min_proto_version(Some(SslVersion::TLS1_2)) server_rejects_tls10, server_rejects_tls11, server_accepts_tls12, server_accepts_tls13 in protocols/tests/unit/transports/tls_config.rs
A pinned CA verifies the server with hostname checking on VerifyMode::CustomCa adds the certificates to the store; verify_hostname stays true tls_with_a_pinned_ca_round_trip in protocols/tests/pipeline/transports.rs
A custom CA extends the default trust store rather than replacing it, and never turns verification off CustomCa calls trust_system before adding certificates, and leaves SslVerifyMode::PEER in place no test pins it
A proxy transport never yields datagrams dial refuses DialNetwork::Udp; Datagram = NoDatagram is uninhabited transport_connector_refuses_udp in protocols/tests/pipeline/transports.rs
An unrecognised security never means plaintext tls_layer returns an error for every value other than absent, "", "none" and "tls" an_unknown_security_is_rejected_on_every_network, security_is_trimmed_before_matching in app/tests/unit/transport.rs
Xray’s tcp + tls spelling is refused with the fix in the message tls_layer’s "tcp" if requested arm tcp_with_tls_is_rejected_and_names_the_fix in app/tests/unit/transport.rs; syntax_errors_are_refused in app/tests/unit/lower.rs
Inbound and outbound apply the same stream rules both lowerings go through resolve_stream, and both specs carry the supervisor’s one StreamShape structural; the tls_layer tests cover both
A protocol that cannot carry a transport refuses a stream block reject_stream_settings a_default_or_plain_tcp_stream_is_accepted, a_transport_the_protocol_cannot_honour_is_rejected, security_on_a_protocol_without_a_transport_is_rejected in app/tests/unit/transport.rs; the hysteria2 cases of syntax_errors_are_refused
A stream protocol on a Unix listener lowers to the plain shape, and the supervisor accepts nothing else on a Unix bind inbound_transport’s Unix branch; validate.rs refuses a non-Tcp shape on a Unix bind a_unix_listen_lowers_to_a_plain_stream in app/tests/unit/lower.rs (the plain shape); a_unix_listener_carries_only_the_plain_tcp_shape in supervisor/tests/unit/validate.rs (the supervisor rule); the app’s refusal of a stream block on a Unix listener is not pinned
A TLS stream needs its certificate and key inbound_transport refuses a missing tls.cert_file or tls.key_file the tls.cert_file case of syntax_errors_are_refused
TLS material sits beside a shape exactly when the shape layers TLS validate.rs → tls_mismatch an_inbound_carries_tls_material_exactly_when_its_shape_layers_tls, an_outbound_carries_tls_settings_exactly_when_its_shape_layers_tls in supervisor/tests/unit/validate.rs
Every inbound protocol that takes a transport meets the same transport rules validate.rs → inbound_transport, run for each protocol InboundProtocolSpec::transport names every_protocol_meets_the_same_transport_rules in supervisor/tests/unit/validate.rs
REALITY rides only under VLESS, on both sides inbound_transport and validate_outbound refuse the Reality shape under any other protocol reality_is_vless_only, a_reality_outbound_is_vless_only in supervisor/tests/unit/validate.rs
A SOCKS inbound serves UDP ASSOCIATE only over plain TCP validate_inbound’s SOCKS arm socks_relays_udp_over_plain_tcp_only in supervisor/tests/unit/validate.rs
An outbound transport reaches the builder with no gaps outbound_transport fills host and authority; validate.rs refuses a gap a_server_config_lowers_to_its_spec (host and SNI from tls.server_name); an_outbound_needs_a_ws_host_and_a_grpc_authority, an_inbound_needs_no_ws_host_or_grpc_authority in supervisor/tests/unit/validate.rs
An outbound never verifies a certificate against a guessed name outbound_transport refuses when neither tls.server_name nor server is set no test pins the refusal
allow_insecure and ca_file cannot be combined verify_mode the allow_insecure and tls.ca_file case of syntax_errors_are_refused (and allow_insecure and ca_file cannot for Hysteria 2)
Failure Error Where it surfaces
Transport handshake exceeds 10 s TimedOut, tls handshake timed out / websocket handshake timed out / grpc handshake timed out returned from accept; the socket is dropped
TLS handshake fails (no shared version, a malformed ClientHello) OpenSSL’s error as io::Error::other returned from accept
WebSocket upgrade refused (wrong path or Host) see Transports: WebSocket and gRPC returned from accept
HTTP/2 handshake fails io::Error::other returned from accept
Failures inside an HTTP/2 connection after its handshake see Transports: WebSocket and gRPC
REALITY: the cover site cannot be dialed the dial’s error, or dialing dest timed out (TimedOut) after TRANSPORT_HANDSHAKE_TIMEOUT returned from accept; logged at warn at most once a minute
REALITY: the socket is not a client of this server none: Ok(Disposition::Camouflage) serve_tcp relays the socket to the cover site; see REALITY transport

Connection::serve_tcp logs any error from accept at debug as inbound transport failed: <error> and serves nothing further on that socket. Streams already handed to the sink run in their own tasks, each under its session’s token.

Failure Error kind Text
UDP destination Unsupported a proxy transport carries no datagrams of its own
The resolver fails or answers with no address as returned by Resolver::resolve an empty answer is dns: <host> did not resolve (NotFound); see DNS resolver
resolve_candidates gets an empty list (a backstop; the resolver refuses an empty answer itself) NotFound dial: destination did not resolve
Nothing left after the family filter AddrNotAvailable dial: no usable <strategy> destination address for <remote>:<port>, with <strategy> as as_str spells it (ipv4_only, ipv6_only, …)
The policy refuses the socket (interface, mark or hook) as returned by SocketOptions::apply inside the connect_any list below; the mobile bindings’ hook gives the platform refused to protect the socket
Every address failed, for any reason ConnectionRefused failed to connect to any address (<addr>: <error>; …)
connect_any got no address (a backstop; resolution never returns an empty list) ConnectionRefused failed to connect to any address (none given)
TLS handshake or verification fails io::Error::other OpenSSL’s error stack
WebSocket upgrade or gRPC request fails see Transports: WebSocket and gRPC

connect_any never returns a single attempt’s error. An attempt that exceeds the connect timeout shows up only inside that list, as <addr>: connect to <addr> timed out, and the error kind is ConnectionRefused even when every attempt timed out. The proxy client runtime turns any of these into a failed connect for the flow (see Client runtime).

Lowering errors carry the object they belong to, and errors raised while the supervisor builds the values, inside ServerConfig::from_pem or ClientConfig::with_verify_mode, are wrapped in ApplyError::Build. app/src/main.rs → main logs a failed --test as configuration invalid: <error> at ERROR. Captured with the pinned binary (OpenSSL 3.0):

Input --test prints
network = "tls" with no tls.cert_file configuration invalid: inbound vin: tls stream needs tls.cert_file
a certificate file that does not exist configuration invalid: inbound vin: cannot read tls.cert_file "<path>": No such file or directory (os error 2)
an empty or non-PEM certificate file configuration invalid: building inbound vin failed: no certificate in PEM bundle
a certificate file with a PEM block that does not decode configuration invalid: building inbound vin failed: error:04800064:PEM routines:PEM_read_bio_ex:bad base64 decode:…
an empty or non-PEM key file configuration invalid: building inbound vin failed: error:1E08010C:DECODER routines:OSSL_DECODER_from_bio:unsupported:…:No supported data to decode. Input type: PEM
a key that does not belong to the certificate configuration invalid: building inbound vin failed: error:0A0000BE:SSL routines:SSL_CTX_check_private_key:no private key assigned:…
an empty or non-PEM tls.ca_file configuration invalid: building outbound tout@v1 failed: no certificate in CA PEM bundle
tls.allow_insecure = true with tls.ca_file configuration invalid: outbound tout: tls.allow_insecure and tls.ca_file cannot both be set

The OpenSSL texts depend on the linked OpenSSL; the … stands for the OpenSSL source location it appends. When you add a failure to from_pem or with_verify_mode, give it a message that makes sense after building inbound <tag> failed: .

accept is a plain future, so dropping it cancels everything it owns. Before the sink runs, that is only the socket and the half-finished handshake. For gRPC, serve_h2 is the only thing that drives the HTTP/2 connection, so once it is dropped, the streams it yielded can no longer send or receive.

In the supervisor, serve_socket, and with it accept, runs under Shared::spawn_until with the socket’s own session token: when that token is cancelled, spawn_until drops the future. The PROXY header read and the receipt of a handed-over socket run inside serve_socket, so they are cancelled the same way. Each stream’s serve_connection runs under its session’s token. Session tokens are children of the supervisor’s root token (supervisor/src/entity/session.rs → Sessions::open), so closing a session, removing its inbound and shutting the supervisor down all reach them. All these tasks run on the supervisor’s TaskTracker, which shutdown waits for.

On the dial side, the future returned by connect owns everything it touches: dropping it at any await closes the socket and abandons the handshake.

Constant Value Defined in Applies to
TRANSPORT_HANDSHAKE_TIMEOUT 10 s protocols/src/transports/accept.rs the TLS handshake, WebSocket upgrade and HTTP/2 handshake in InboundTransport::accept, per socket
HANDSHAKE_TIMEOUT 10 s protocols/src/core/mod.rs the protocol handshake: armed by the core at the client’s first byte, and applied by the supervisor’s drive to each runtime step until the core is established
TCP_KEEPALIVE_IDLE 120 s protocols/src/transports/keepalive.rs silence before the first keepalive probe
TCP_KEEPALIVE_INTERVAL 30 s protocols/src/transports/keepalive.rs interval between probes
TCP_KEEPALIVE_RETRIES 3 protocols/src/transports/keepalive.rs unanswered probes before the kernel drops the connection
DEFAULT_CONNECT_TIMEOUT 10 s environment/src/dial/tcp.rs each TCP connect attempt in connect_any
PROXY_HEADER_TIMEOUT 10 s supervisor/src/serve.rs reading a PROXY protocol v2 header, on an inbound that reads one
FIXED_LEN 16 bytes protocols/src/transports/proxy_protocol.rs the fixed part of a PROXY v2 header, waited for in 5 ms steps
MAX_V2_LEN 4096 bytes protocols/src/transports/proxy_protocol.rs the longest PROXY v2 header taken, TLVs included, by decode_v2 and so by read_v2 and the handoff receiver
RECEIVE_TIMEOUT 5 s supervisor/src/system/handoff.rs a relay’s message on a handoff control connection, once that connection is accepted
Minimum TLS version TLS 1.2 protocols/src/transports/tls/config.rs both ServerConfig and ClientConfig

The WebSocket and HTTP/2 timers and sizes are on Transports: WebSocket and gRPC, and the process-wide view is on Limits, timeouts and memory.

File Tests What they pin
protocols/tests/pipeline/transports.rs tcp_round_trip, tls_round_trip, tls_with_a_pinned_ca_round_trip, ws_round_trip, ws_over_tls_with_early_data_round_trip, ws_early_data_is_the_first_bytes_the_server_reads, ws_rejects_a_wrong_path_at_the_upgrade, grpc_round_trip, grpc_multi_mode_over_tls_round_trip, one_grpc_connection_carries_many_streams, transport_connector_refuses_udp Every InboundTransport accepts what the matching TransportKind dials. assert_echo sends hello and a 200 000-byte payload, shuts down the write side, and expects a clean end of stream with nothing after the echo.
protocols/tests/unit/transports/tls_config.rs server_accepts_tls12, server_accepts_tls13, server_rejects_tls10, server_rejects_tls11, records_read_ahead_come_out_without_more_from_the_socket The server’s version floor, using a raw SslConnector pinned to one version with set_min_proto_version and set_max_proto_version. Read-ahead between a ServerConfig and a ClientConfig over loopback, in both directions: 64 records of 100 bytes sent in one burst, then silence, must come out of 37-byte reads, each given 5 s, without waiting on the socket.
protocols/tests/unit/transports/tls_platform_roots.rs every_bundled_root_parses bundled() on the host: the list is not empty and holds one OpenSSL certificate for every root in webpki_root_certs::TLS_SERVER_ROOT_CERTS, so on iOS no bundled root goes missing without a word. platform_roots.rs includes the file with #[path], and the module is compiled under cfg(test) for it; the Android store reader is compiled only for Android, and no host test reaches it.
protocols/tests/unit/transports/tls_platform_roots.rs every_native_root_converts native() on the host lists as many OpenSSL certificates as load_native_certs found, so every certificate of the platform store reaches OpenSSL. native() is compiled for tests on every OS, so this runs on Linux against the host’s store; rustls-native-certs is a dev-dependency for it.
protocols/tests/unit/transports/proxy_protocol.rs a_tcp4_header_names_its_source, a_tcp6_header_names_its_source, trailing_tlvs_are_skipped, a_local_header_and_a_udp_address_name_no_client, a_unix_or_unspecified_address_names_no_client, a_local_header_ignores_its_family, decoding_says_where_the_header_ends, the_longest_header_is_taken, a_malformed_header_is_refused, a_header_is_read_and_what_follows_is_left, a_direct_client_is_left_untouched, a_header_split_across_writes_is_waited_for, a_client_that_hangs_up_sends_no_header parse_v2 and decode_v2 on built headers: both TCP families, TLVs, LOCAL, UDP over both families, Unix and unspecified addresses naming no client, a LOCAL header with an undefined family byte, a Header::len that stops before the bytes after the header, a header of exactly MAX_V2_LEN taken, and every malformed case refused as InvalidData: a wrong version or signature, one byte over MAX_V2_LEN, an unknown command, family (0x41) or transport (0x13), short IPv4, IPv6 (34 bytes), UDP and Unix (215 bytes) blocks, and a header or address block cut short. read_v2 over a loopback pair: the bytes after a header stay on the socket, a TLS ClientHello is left unread, a header written in two parts 30 ms apart is waited for, and a closed peer yields None.
supervisor/tests/guard.rs a_proxy_header_names_the_client_and_a_bare_connection_is_its_own End to end through a VLESS inbound with proxy_protocol set: a connection with a header is tracked with the address it names, and one without with its socket peer.
supervisor/tests/handoff.rs (Unix only) a_handed_over_connection_is_served_with_the_client_its_header_names, tls_grpc_and_vmess_run_over_a_handed_over_connection A VLESS inbound on a TCP listener with a handoff socket beside it: a socket handed over with a header is tracked with the client the header names, one with a LOCAL header with its own peer, and a direct connection with its socket peer. TLS, HTTP/2, gRPC and VMess run over a handed-over socket, every stream a session of the client the header names. The file’s other tests cover the handoff socket itself (Listeners and the serve loop).
app/tests/unit/transport.rs tcp_without_security_is_plaintext, tcp_with_tls_is_rejected_and_names_the_fix, tls_network_carries_tls_with_or_without_a_redundant_security, ws_and_grpc_layer_tls_only_when_asked, an_unknown_security_is_rejected_on_every_network, security_is_trimmed_before_matching, an_unknown_network_is_left_to_the_caller, reality_security_over_tcp_is_its_own_shape, reality_is_refused_on_any_network_but_tcp, a_default_or_plain_tcp_stream_is_accepted, a_transport_the_protocol_cannot_honour_is_rejected, security_on_a_protocol_without_a_transport_is_rejected The (network, security) matrix row by row, security = "reality", and reject_stream_settings.
app/tests/unit/lower.rs a_server_config_lowers_to_its_spec, syntax_errors_are_refused, a_unix_listen_lowers_to_a_plain_stream, socks_and_shadowsocks_lower_their_stream, socks_and_shadowsocks_on_a_unix_socket_refuse_a_stream The transport specs lowering builds: a ws + tls inbound with its file bytes, a plain grpc inbound, a ws + tls outbound whose host and SNI fall back to tls.server_name; the refusals for tcp + tls, an unknown network, a missing tls.cert_file and allow_insecure with ca_file; the plain shape of a Unix listener with no stream block; and SOCKS and Shadowsocks inbounds that read their [inbound.stream], and refuse one on a Unix socket.
supervisor/tests/unit/validate.rs an_inbound_carries_tls_material_exactly_when_its_shape_layers_tls, an_inbound_needs_no_ws_host_or_grpc_authority, an_outbound_carries_tls_settings_exactly_when_its_shape_layers_tls, an_outbound_needs_a_ws_host_and_a_grpc_authority, a_unix_listener_carries_only_the_plain_tcp_shape, every_protocol_meets_the_same_transport_rules, shadowsocks_runs_over_a_transport, socks_relays_udp_over_plain_tcp_only, reality_is_vless_only, a_reality_outbound_is_vless_only The supervisor’s transport rules, on hand-built specs, for every protocol that takes a transport. The REALITY settings rules are on REALITY transport.
app/tests/integration/e2e_xray.rs app_client_tls_xray_server_tls, app_server_tls_xray_client_tls (and the ws and grpc pairs, plain and TLS) network = "tls" interoperates with Xray’s "network":"tcp","security":"tls" in both directions, with VLESS as the tunnel protocol. The Xray client pins the app server’s certificate; the app client uses allow_insecure.
app/tests/integration/e2e_xray_wrapped.rs app_server_shadowsocks_over_grpc, app_server_shadowsocks_over_ws_tls, app_server_shadowsocks_2022_over_grpc_tls, app_server_socks_over_tls, app_server_http_over_tls, and the app_client_ twin of each Shadowsocks, Shadowsocks 2022, SOCKS5 and HTTP inside a transport interoperate with the pinned Xray in both directions: the app as the server behind Xray’s client, and as the client in front of Xray’s server.
katana tests/unit/api/newv2board.rs a_tcp_header_other_than_none_is_refused, a_transport_katana_cannot_serve_is_refused A UniProxy VMess, VLESS or Shadowsocks body on tcp with no header, a null header, an object with no type or a null type, or the type "none" or "None" is read as Tcp. The types "http" and "" are refused as tcp header type "…", a type that is not a string with tcp header type is not a string and a header that is not an object with tcp header is not an object, and a REALITY body with an http header is refused too. The networks httpupgrade, splithttp, xhttp and quic are refused by name, each as node requests kernel-unsupported feature: ….
katana tests/unit/lower/inbound.rs acme_cert_mode_rejected, tls_without_cert_file_errors, reject_unknown_sni_is_refused_rather_than_ignored A node under an ACME cert mode does not lower, a TLS node without cert.mode = "file" does not either, and cert.reject_unknown_sni = true is refused as Unsupported with an error that names the key.

The pipeline tests share self_signed_pem (an RSA-2048 certificate with subject CN localhost and a localhost DNS name, and its PKCS#8 key), tcp_dest and udp_dest from protocols/tests/support/mod.rs. tls_pair builds a server and an Insecure client (ClientConfig::new("localhost", false, alpn)); the pinned-CA test instead passes the server’s own certificate as VerifyMode::CustomCa, so the chain and the localhost name are both checked. tls_config.rs has its own self_signed_pem, with the CN localhost and no DNS name, which is enough because its raw client sets SslVerifyMode::NONE and set_verify_hostname(false). The Xray tests build Xray-core with go build through XRAY_BIN in app/tests/support/mod.rs, and skip themselves when Go is not installed or the build fails.

Terminal window
cargo test -p etemenanki-protocols --test pipeline transports
cargo test -p etemenanki-protocols --lib transports
cargo test -p etemenanki-app --lib transport
cargo test -p etemenanki-app --lib lower
cargo test -p etemenanki-supervisor --lib validate
cargo test -p etemenanki-supervisor --test guard
cargo test -p etemenanki-supervisor --test handoff
cargo test -p etemenanki-app --test integration e2e_xray::
cargo test -p etemenanki-app --test integration e2e_xray_wrapped::

The app’s unit tests run under --lib, because app/src/lib.rs mounts the modules whose #[path] attributes include app/tests/unit/transport.rs and app/tests/unit/lower.rs.