Skip to content

Client runtime

Source files: 72 · checked against Etemenanki 46c12e4 · katana v6.0.0
  • Etemenanki/concepts/src/client.rs
  • Etemenanki/concepts/src/relay.rs
  • Etemenanki/concepts/src/core.rs
  • Etemenanki/concepts/src/buffer.rs
  • Etemenanki/concepts/src/link.rs
  • Etemenanki/concepts/src/runtime.rs
  • Etemenanki/concepts/tests/client.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/transports/connect.rs
  • Etemenanki/protocols/src/transports/grpc/stream.rs
  • Etemenanki/protocols/src/transports/coalesce.rs
  • Etemenanki/protocols/src/helpers/address.rs
  • Etemenanki/protocols/src/http/codec.rs
  • Etemenanki/protocols/src/http/protocol.rs
  • Etemenanki/protocols/src/socks/codec.rs
  • Etemenanki/protocols/src/socks/udp_link.rs
  • Etemenanki/protocols/src/socks/protocol.rs
  • Etemenanki/protocols/src/socks/server.rs
  • Etemenanki/protocols/src/trojan/codec.rs
  • Etemenanki/protocols/src/trojan/protocol.rs
  • Etemenanki/protocols/src/vless/codec.rs
  • Etemenanki/protocols/src/vless/protocol.rs
  • Etemenanki/protocols/src/vless/addons.rs
  • Etemenanki/protocols/src/vmess/codec.rs
  • Etemenanki/protocols/src/vmess/framing.rs
  • Etemenanki/protocols/src/vmess/protocol.rs
  • Etemenanki/protocols/src/vmess/session.rs
  • Etemenanki/protocols/src/vmess/aead.rs
  • Etemenanki/protocols/src/ss_aead.rs
  • Etemenanki/protocols/src/ss_legacy/codec.rs
  • Etemenanki/protocols/src/ss_legacy/aead.rs
  • Etemenanki/protocols/src/ss_2022/codec.rs
  • Etemenanki/protocols/src/ss_2022/crypto.rs
  • Etemenanki/protocols/src/ss_2022/protocol.rs
  • Etemenanki/protocols/src/sss/codec.rs
  • Etemenanki/protocols/src/sss/client.rs
  • Etemenanki/protocols/src/sss/protocol.rs
  • Etemenanki/protocols/src/sss/core.rs
  • Etemenanki/protocols/src/sss/server.rs
  • Etemenanki/protocols/tests/support/pipeline.rs
  • Etemenanki/protocols/tests/pipeline/http.rs
  • Etemenanki/protocols/tests/pipeline/socks.rs
  • Etemenanki/protocols/tests/pipeline/trojan.rs
  • Etemenanki/protocols/tests/pipeline/vless.rs
  • Etemenanki/protocols/tests/pipeline/vmess.rs
  • Etemenanki/protocols/tests/pipeline/shadowsocks.rs
  • Etemenanki/protocols/tests/unit/http/codec.rs
  • Etemenanki/protocols/tests/unit/socks/codec.rs
  • Etemenanki/protocols/tests/unit/socks/protocol.rs
  • Etemenanki/protocols/tests/unit/trojan/codec.rs
  • Etemenanki/protocols/tests/unit/vless/codec.rs
  • Etemenanki/protocols/tests/unit/vmess/codec.rs
  • Etemenanki/protocols/tests/unit/ss_legacy/codec.rs
  • Etemenanki/protocols/tests/unit/ss_2022/codec.rs
  • Etemenanki/protocols/tests/unit/ss_aead.rs
  • Etemenanki/protocols/tests/unit/vmess/framing.rs
  • Etemenanki/protocols/tests/unit/sss/codec.rs
  • Etemenanki/environment/src/dial/tcp.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/proxy.rs
  • Etemenanki/supervisor/src/topology/outbound/udp_fanout.rs
  • Etemenanki/supervisor/src/topology/outbound/dns.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/plane.rs
  • Etemenanki/supervisor/src/build/outbound.rs
  • Etemenanki/supervisor/src/build/dns.rs
  • Etemenanki/supervisor/src/connector.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/track/mod.rs
  • Etemenanki/supervisor/tests/sss.rs
  • katana/src/lower/outbound.rs
  • katana/tests/unit/e2e.rs

A server core parses what a client sends and decides where each flow goes. When a flow goes to another proxy server instead of straight to its destination, something has to speak that proxy’s protocol on the way out: write the request header, wait for a reply if the protocol has one, seal every payload byte into wire frames, and open the frames that come back. In Etemenanki that is the client side of the model, and it lives in etemenanki-concepts (concepts/src/client.rs and the encode half of concepts/src/core.rs), with one codec per protocol in etemenanki-protocols.

The client side has three layers: a codec, a sans-I/O state machine for one flow; ProxyClientRuntime, which drives one codec over one dialed upstream and looks like a plain byte stream (or a datagram link) from outside; and ProxyClientConnector, a Connector that builds a codec and a runtime for every flow, so a server runtime can dial through an upstream proxy. The same crate also has two plain byte-copy futures (concepts/src/relay.rs) for paths with no protocol in between. This page is for contributors who change any of these or add a client protocol. It assumes the server side from The server core and The server runtime, and the link types from Links and types.

Layer Owns Does not own
Codec (ProxyCoreEncodeHandshake plus ProxyCoreEncode or ProxyCoreEncodeDatagram, concepts/src/core.rs) The protocol: request header, handshake replies, framing, encryption, the close. Sockets, buffers, wakers, timers. The runtime hands it byte slices and a Staging area.
ProxyClientRuntime (concepts/src/client.rs) The upstream stream, a staging buffer toward it, a read buffer from it, the handshake loop, AsyncRead/AsyncWrite or DatagramLink on the plaintext side, and checks that the codec keeps its contract. Dialing (it calls an inner Connector), choosing the codec, deciding what “connected” means to a server core.
ProxyClientConnector / ProxyClientConnecting (concepts/src/client.rs) Picking a stream or datagram codec per flow, and resolving the dial only once the upstream is dialed, the handshake is done and the handshake bytes are flushed. Anything after the dial resolves: from then on the server runtime polls the ProxyClientRuntime directly.
UnidirectionalConnection / BidirectionalConnection (concepts/src/relay.rs) Copying bytes between streams with one fixed buffer per direction and counting what moved. BidirectionalConnection half-closes each writer when its reader ends; UnidirectionalConnection only flushes. Framing, deadlines. A caller that wants an idle limit wraps the future.

Nothing on the client side spawns a task or uses a channel. A ProxyClientRuntime is polled by whoever holds it, so the codec, both buffers and the upstream stream are all polled inside the holder’s task. The holders at this revision:

  • In the supervisor, the server runtime stores a TCP flow’s client runtime as that key’s outbound, so it runs in the connection’s task.
  • In the supervisor, a UDP flow’s client runtime is a sub-link of a FanOutLink, which the server runtime holds as the key’s datagram outbound.
  • A query of the supervisor’s resolver to a through_proxy server polls the client runtime from inside the query future, outside any server runtime (see The supervisor’s resolver).
  • The pipeline tests, some concept tests and katana’s end-to-end tests poll it directly.

The relay futures are single hand-written futures too.

One task exists below the client runtime: the driver of a gRPC upstream’s HTTP/2 connection. protocols/src/transports/grpc/stream.rs → GrpcStream::connect runs the HTTP/2 client handshake over Coalesced (configured_client_builder().handshake(Coalesced::new(io)), protocols/src/transports/coalesce.rs), which holds h2’s writes until h2 flushes and sends them as one write of at most one TLS record’s plaintext, spawns the connection driver inside an AbortOnDropHandle, waits for send_req.ready(), and opens the tunnel request with send_request(request, false). The stream keeps the handle in its _driver field, so dropping the stream aborts the driver. The driver logs grpc connection ended: <error> at debug level when the connection fails. The transport is described in WebSocket and gRPC transports.

The codecs, the runtime and the relay futures hold no lock, and every codec value belongs to one flow. The supervisor adds one lock around them: each ProxyClient keeps its ProxyClientConnector in a parking_lot::Mutex, held only while a dial future is built (see The supervisor’s proxy clients).

User What it uses Where
The supervisor’s proxy outbounds (HTTP, SOCKS CONNECT, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, sss) ProxyClientConnector over a TransportConnector (for sss, over an SssConnector around one), wrapped in ProxyClient supervisor/src/topology/outbound/proxy.rs, supervisor/src/topology/outbound/mod.rs
The supervisor’s resolver (Split mode, through_proxy servers) a ProxyClient reached through Target::connect_stream from RoutedDialer::dial, when the route for the server’s address names a proxy outbound supervisor/src/topology/outbound/dns.rs, supervisor/src/build/dns.rs
The supervisor’s SOCKS UDP SocksUdpLink, not the client runtime supervisor/src/topology/outbound/mod.rs → SocksOutbound
The SOCKS inbound’s CONNECT relay BidirectionalConnection protocols/src/socks/server.rs → relay_with_idle_guard
An sss inbound relaying a refused stream to its fallback BidirectionalConnection protocols/src/sss/server.rs → relay
Pipeline tests ProxyClientRuntime over plain TCP, via the client helper protocols/tests/support/pipeline.rs
Concept tests all three layers, with toy codecs concepts/tests/client.rs
katana’s end-to-end tests ProxyClientRuntime as the test client katana tests/unit/e2e.rs

UnidirectionalConnection and ProxyClientRuntime::codec have no caller in the workspace or in katana at these revisions. The WireGuard, Hysteria 2 and AnyTLS outbounds do not use the client runtime: each is a Connector of its own that owns its connections (see WireGuard, Hysteria 2 client and AnyTLS). AnyTLS’s AnyTlsConnector keeps a pool of TLS sessions, each carrying one flow at a time. katana has no client code of its own; its [[outbound]] entries become the same supervisor outbounds (see katana).

Every client codec implements the handshake trait. The payload shape is a second trait on top of it, so a codec implements exactly the operations its flow has.

concepts/src/core.rs
pub trait ProxyCoreEncodeHandshake {
type Target;
type Error;
const STAGING_RESERVE: usize;
fn start(&mut self, out: &mut Staging<'_>) -> Result<Handshake, Self::Error>;
fn reply(&mut self, wire: &mut [u8], out: &mut Staging<'_>) -> Result<Reply, Self::Error>;
fn finish(&mut self, out: &mut Staging<'_>) -> Result<(), Self::Error>;
}
Item Meaning
Target What the runtime’s inner Connector dials: the upstream proxy server, not the flow’s destination. The destination lives inside the codec and start encodes it. Every codec in etemenanki-protocols uses Destination.
Error The codec’s error. The runtime requires Error + Send + Sync + 'static and wraps it into an io::Error of kind InvalidData. Every codec in etemenanki-protocols uses io::Error.
STAGING_RESERVE The most that one start, reply, finish or seal call stages beyond the plaintext it takes: header, length prefix, tag, padding. The runtime offers a stream seal at least STAGING_RESERVE + 1 bytes of room and a packet seal STAGING_RESERVE + plain.len(), and makes STAGING_RESERVE free before finish, so a codec that keeps to its bound never runs out of room.
start Called once, right after the dial succeeds, with an empty staging buffer (room for all BUF_SIZE bytes). It stages the request header and says whether a reply must be parsed before plaintext may flow.
reply Called only while the handshake is AwaitReply, after everything staged so far has been written, with the unparsed upstream bytes (mutable, so the codec can decrypt in place). It may stage the next round. Bytes left after the final reply are the first wire frames.
finish The plaintext side half-closed. The codec stages whatever tells the upstream so: a closing frame, or nothing when the wire’s own EOF carries it.

Staging is the append-only view of a WriteBuffer’s free tail that server cores stage into as well: room(), reserve(len) and put(bytes), where reserve and put return None without staging anything when the room is short. It is described with the core contract on The server core.

concepts/src/core.rs
pub enum Handshake {
Done,
AwaitReply,
}
pub enum Reply {
NeedMore,
Step { consumed: usize, next: Handshake },
}

Handshake::Done from start means the protocol sends its header and goes (VMess, VLESS, Trojan, Shadowsocks, sss). Handshake::AwaitReply means the upstream must answer first (SOCKS method selection, an HTTP CONNECT status line): the runtime withholds plaintext, reads the wire and hands the bytes to reply. Reply::NeedMore asks for more wire bytes. Reply::Step reports that the first consumed bytes held a complete reply, and next says whether another round follows; bytes for that round may already be staged.

A Step must make progress: consume bytes, stage bytes, or end the handshake. The runtime rejects a step that does none of these (see The handshake loop). Handshake and Reply derive Debug, Clone, Copy, PartialEq and Eq; Opened below derives the same without Copy.

concepts/src/core.rs
pub trait ProxyCoreEncode: ProxyCoreEncodeHandshake {
fn seal(&mut self, plain: &[u8], out: &mut Staging<'_>) -> Result<usize, Self::Error>;
fn open(&mut self, wire: &mut [u8]) -> Result<Opened, Self::Error>;
}
pub enum Opened {
Frame { consumed: usize, plain: Range<usize> },
NeedMore,
End { consumed: usize },
}
  • seal takes a prefix of plain and stages it as wire frames. It returns how many plaintext bytes it took. That may be fewer than offered, for example one frame’s worth, but must be at least one.
  • open looks at the unparsed wire bytes and opens the leading frame in place. Frame { consumed, plain } says the first consumed bytes are done with, and plain, a sub-range of them, now holds the decrypted plaintext. plain is empty for a control frame. End { consumed } means the upstream ended the flow cleanly with a closing frame, and no plaintext follows. NeedMore asks for more bytes. A Frame or End must consume at least one byte and at most the slice.

A frame with empty plaintext is how a codec consumes a response header without a reply round. The VLESS response header, the VMess response header, the legacy Shadowsocks response salt, and the Shadowsocks 2022 response salt and fixed response header all open as empty frames, and the runtime skips them.

A datagram codec carries packets with a per-packet peer address over a stream to the upstream (Trojan, VLESS, VMess and sss UDP).

concepts/src/core.rs
pub type OpenedFrom = (Opened, Option<Destination>);
pub trait ProxyCoreEncodeDatagram: ProxyCoreEncodeHandshake {
fn seal_to(
&mut self,
plain: &[u8],
to: &Destination,
out: &mut Staging<'_>,
) -> Result<Option<()>, Self::Error>;
fn open_from(&mut self, wire: &mut [u8]) -> Result<OpenedFrom, Self::Error>;
}

One seal_to is one packet, taken whole, or Ok(None) with nothing staged if it does not fit the room offered. One data frame from open_from is one packet, returned with its source. A frame returned with None as its source is not a packet (the VLESS or VMess response header, or a VMess chunk with no plaintext), and the runtime consumes and skips it. open_from follows the same progress rule as open.

How the peer address is used depends on the protocol. TrojanDatagram and SssDatagram write to into every packet frame and read the source from every packet frame. VMessDatagram, and VlessDatagram without a flow, fix the target in the request header, ignore to, and report that target as the source of every packet they open. Under the Vision flow VlessDatagram speaks XUDP instead: it writes to into every frame and reads the source from every frame.

SssDatagram has one more answer: for a packet longer than its stream’s U (max_datagram), seal_to returns Ok(Some(())) with nothing staged and logs sss: dropping a {}-byte datagram above U at debug level. The runtime reports the packet sent, and it is lost, as on a link whose MTU it exceeds.

After NeedMore, the runtime reads more and calls open (or open_from, or reply) again with the same unparsed bytes at the front and the new ones behind them. A codec therefore must not transform in place any byte it has not consumed, or it would decrypt it twice. The codecs that decrypt keep what they have already decoded:

  • ss_aead::ChunkDecoder (protocols/src/ss_aead.rs, shared by both Shadowsocks codecs) opens a record’s sealed length from a copy and remembers it in pending_len, and opens the payload in place only once the whole record is there. a_record_presented_again_is_never_decrypted_twice pins this.
  • vmess::framing::ChunkDecoder decodes a chunk’s size field from a copy and remembers it in pending, since the SHAKE mask advances once per chunk.
  • The VMess response header (protocols/src/vmess/protocol.rs → decode_response_header_slice) is decrypted into separate buffers, not in place, and holds no state, so a second call opens it again from the same bytes. The VLESS response header (parse_response_header) is plaintext and only read. Ss2022Stream opens its fixed and first-payload chunks only once the whole chunk is present.
concepts/src/core.rs
pub enum NoCodec<Target, Error> {
Never(Infallible, PhantomData<(Target, Error)>),
}

NoCodec is uninhabited and implements all three traits with STAGING_RESERVE = 0; every method is match never {}. A ProxyClientConnector always has both a stream codec type and a datagram codec type, so a protocol that carries only one kind names NoCodec for the other. The supervisor aliases it as supervisor/src/topology/outbound/proxy.rs → NoUdp = NoCodec<Destination, io::Error> and uses it for Outbound::Http, SocksOutbound’s tcp client, Outbound::Shadowsocks and Outbound::Ss2022, and on both of SssOutbound’s clients: as the datagram codec of tcp and as the stream codec of udp. The concept tests use NoCodec<String, CodecError>.

Codec File start stages Reply rounds finish stages STAGING_RESERVE One seal takes
HttpConnect protocols/src/http/codec.rs the CONNECT request one: the status head nothing REQUEST_MAX = 1,024 all offered
SocksConnect protocols/src/socks/codec.rs the method request two or three: method, optional username and password, request nothing 528 all offered
TrojanStream protocols/src/trojan/codec.rs the request header, command 0x01 none nothing REQUEST_HEADER_MAX = 320 all offered
TrojanDatagram protocols/src/trojan/codec.rs the request header, command 0x03, address 0.0.0.0:0 none nothing 320 one packet frame
VlessStream protocols/src/vless/codec.rs the request header, TCP command, with the flow’s addons when a flow is set none nothing RESERVE = 296 all offered
VlessDatagram protocols/src/vless/codec.rs the request header: UDP command and the fixed target, or under Vision the mux command with the flow’s addons none nothing 296 one length-prefixed packet, or under Vision one XUDP frame
VMessStream protocols/src/vmess/codec.rs the sealed request header none a terminator chunk HEADER_MAX (358) rounded up to 384 at most MAX_PAYLOAD = 1,966 bytes, one chunk
VMessDatagram protocols/src/vmess/codec.rs the sealed request header, UDP command none a terminator chunk 384 one chunk per packet
SsStream protocols/src/ss_legacy/codec.rs a random salt and the sealed address record none nothing 32 + 34 + 259 + 61 = 386 at most MAX_PAYLOAD = 0x3FFF bytes, one record
Ss2022Stream protocols/src/ss_2022/codec.rs the request header with an empty first payload none nothing 2,048 at most MAX_PACKET_SIZE = 0xFFFF bytes, one record
SssStream protocols/src/sss/codec.rs the request header, command 0x01 none nothing HEADER_MAX = 276 all offered
SssDatagram protocols/src/sss/codec.rs the request header, command 0x02, the first packet’s destination none nothing 276 one record per packet

259 is AddressCodec::MAX_LEN (protocols/src/helpers/address.rs: type, length, a 255-byte name, port), and 34 is ss_aead::RECORD_OVERHEAD: RECORD_HEADER_LEN (18, a sealed two-byte length with its 16-byte tag) plus the payload’s TAG_LEN (16). What each codec does beyond the table:

  • HttpConnect. new(dest, auth) builds the request with http::protocol::build_connect_request: CONNECT <authority> HTTP/1.1, a Host header with the same authority, Proxy-Authorization: Basic <base64 of user:pass> when auth is set, Proxy-Connection: Keep-Alive, and the blank line. start stages it and returns AwaitReply. reply waits for the blank line that ends the head (find_head_end, which looks for \r\n\r\n), parses the status line with httparse into at most MAX_HEADERS (128) headers, and accepts only 200, consuming exactly the head. After the head, bytes pass through verbatim in both directions: seal stages all it is offered, and open returns everything it is given as one frame.

  • SocksConnect. A private Stage (Method, UserPass, Request, Done) tracks the rounds. The method request offers one method (encode_method_request: [5, 1, method]): username and password (0x02) when auth is set, no authentication (0x00) otherwise. The method reply stages the RFC 1929 message (encode_userpass) or, without auth, the request; an accepted account stages the request (encode_request(CMD_TCP_CONNECT, Some(&dest)): [5, 1, 0] and the address). A request reply with status 0 ends the handshake. STAGING_RESERVE covers the larger of a credential message (up to 513 bytes) and a request with a full address. Payload passes verbatim, as for HTTP.

  • TrojanStream, TrojanDatagram. The header is trojan::protocol::encode_request_header: the password’s password_hash (HASH_LEN = 56 bytes, the lowercase hex SHA-224 of the password), CRLF, the command, the address, CRLF. That is where REQUEST_HEADER_MAX = 56 + 2 + 1 + 259 + 2 comes from. TrojanStream then passes bytes verbatim. The UDP header names an unspecified placeholder address, because the server discards it for an association. seal_to stages one packet frame (packet_into: the packet’s own address, a big-endian two-byte length, CRLF, the payload; the part before the payload is at most PACKET_HEADER_MAX = 263 bytes) and answers None when the room is short or the payload exceeds a u16. open_from parses one frame (parse_packet) and returns its address as the source. The wire format is on Trojan.

  • VlessStream, VlessDatagram. Without addons the request header is at most REQUEST_HEADER_MAX = 1 + 16 + 1 + 1 + 259 = 278 bytes. VlessStream::new(uuid, dest, flow) and VlessDatagram::with_flow(uuid, target, flow) also take a VlessFlow: with VlessFlow::Vision the header carries the 18-byte addons block that names xtls-rprx-vision (protocols/src/vless/addons.rs → encode_addons, at most ENCODED_MAX bytes). Both codecs declare RESERVE = REQUEST_HEADER_MAX + ENCODED_MAX = 296, the longest header with those addons. The codec only announces the flow; the Vision framing of the body is a transport stream below it (see The upstream: TransportConnector). VlessDatagram::new is with_flow without a flow. open and open_from first consume the response header as an empty frame: parse_response_header reads the version byte and the addons length and skips that many addon bytes. VlessStream then passes bytes verbatim. Without a flow, seal_to stages a big-endian u16 length and the payload, and answers None for a payload over 65,535 bytes or a short room, and open_from parses one length-prefixed packet (parse_length_packet) and reports the fixed target as its source. Under Vision the header carries the mux command instead of the UDP command and target, and each packet is an XUDP frame of session 0 naming its peer: seal_to stages a New for the first and a Keep for each later one, and drops a packet over 8,192 bytes (MAX_DATA_LEN) by answering Ok(Some(())) with nothing staged; open_from returns a Keep’s data with the peer the frame names. The wire format is on VLESS.

  • VMessStream, VMessDatagram. new(uuid, security, global_padding, dest) builds a protocols/src/vmess/session.rs → OutboundSession, which draws the body key, the body IV and the response byte at random and sets RequestOptions::modern(global_padding): chunk stream and chunk masking always, global padding when asked. The codec keeps the sealed request header, the request ChunkStream, the response ChunkDecoder and the ResponseSession that opens the response header. HEADER_MAX = 2 + 16 + 8 + 38 + 259 + 15 + 4 + 16 = 358 covers the AEAD envelope around the fixed fields, a full address and the padding.

    Body chunks (protocols/src/vmess/framing.rs → ChunkStream) are a two-byte size field, the sealed plaintext with its 16-byte tag, and up to MAX_PADDING (64) random padding bytes. A SHAKE-128 keystream seeded with the body IV gives each chunk its padding length (global padding) and the mask XORed onto its size field (chunk masking). So CHUNK_OVERHEAD_MAX = 2 + 16 + 64 = 82, and MAX_PAYLOAD = 2,048 − 16 − 2 − 64 = 1,966 keeps every sealed chunk within 2 KiB. seal_chunk_into refuses a chunk that would not fit with the worst-case padding before it advances the keystream. The response header opens as an empty frame. After it, a chunk whose size equals the tag plus its padding (ChunkHeader::is_terminator) opens as Opened::End, and finish stages that terminator (seal_terminator_into). VMessDatagram::seal_to ignores to and answers None when the room is below the packet plus CHUNK_OVERHEAD_MAX; open_from reports the fixed target as the source only for a chunk with plaintext. The wire format is on VMess wire format.

  • SsStream. new(method, key, dest) takes the master key (evp_bytes_to_key of the password, which build_outbound derives once). start draws a salt of the method’s key length (random_salt), keys the uplink ChunkEncoder with the session subkey for that salt, stages the salt and seals the address as the first record. ss_aead keeps one little-endian nonce counter per direction that starts at zero and advances once per AEAD operation. A record is the sealed two-byte length with its tag, then the sealed payload with its tag. seal_record refuses a payload over the flavor’s limit and, when the record does not fit, stages nothing and leaves the counter untouched. open takes the response salt as an empty frame and keys the downlink ChunkDecoder with it, then opens records. A zero-length record is an empty frame, not the end, and a declared length over MAX_PAYLOAD (0x3FFF) fails. finish stages nothing, because the legacy writer sends no terminator and the wire’s EOF ends the flow. The wire format is on Shadowsocks.

  • Ss2022Stream. new(method, psk, identity_keys, dest) takes the user PSK and the ordered identity PSK chain (empty for a single-user server). start calls ss_2022::protocol::build_request, which measures the whole header against the room first and stages nothing if it does not fit. It stages, in order:

    1. a random salt of the key length;
    2. one 16-byte identity header per identity key, where each hop encrypts the next PSK’s eih_hash with one AES block under identity_subkey(current PSK, salt);
    3. the fixed chunk, REQUEST_FIXED_LEN = 11 bytes: HEADER_TYPE_CLIENT (0), an 8-byte Unix timestamp, and the variable chunk’s two-byte length;
    4. the variable chunk: the address, a two-byte padding length, the padding and the initial payload. The padding is 1 to MAX_PADDING_LENGTH (900) random bytes unless the initial payload is at least 900 bytes, and this codec’s initial payload is always empty.

    Both header chunks are bare chunks sealed on the same nonce counter as the records that follow. seal takes at most MAX_PACKET_SIZE (0xFFFF) bytes per record. open walks four states of a private Down:

    • Salt: the server’s salt, which keys the downlink, opened as an empty frame.
    • Fixed: response_fixed_len(key_len) = 1 + 8 + key length + 2 bytes plus a tag, checked for HEADER_TYPE_SERVER (1), for a timestamp within 30 s of the current time (check_timestamp_at), and for the echoed request salt (ct_eq), then opened as an empty frame.
    • FirstPayload: the first payload chunk, opened as a frame carrying its plaintext (empty, and skipped, when the server sent none).
    • Records: records, as for SsStream.

    The wire format is on Shadowsocks 2022.

  • SssStream, SssDatagram. new(uuid, dest) (with max_datagram, the stream’s U, for SssDatagram) encodes the header at once with sss::protocol::put_request: the 16-byte id, the command, and the address with its port, at most HEADER_MAX = 16 + 1 + 259 = 276 bytes. A destination the wire cannot carry, a domain that is not 1 to 255 printable ASCII bytes, is kept as an error and fails the flow at start, with nothing staged. There is no reply and no response header, so SssStream passes bytes verbatim from the first byte back. A datagram record is the peer’s address and port, a varint length of one to three bytes and the payload (packet_header, at most PACKET_HEADER_MAX = 262 bytes before the payload). seal_to stages one record for to, and open_from parses one record of at most U bytes and returns its source, which must be an IP address. The codecs transform nothing: sss’s transform chains sit below them, in the connector (see sss: a connector around the transport). The wire format is on sss.

Codecs whose start returns Done answer reply with an io::Error::other, because the runtime never calls it for them: trojan: the server sends no handshake reply, vless: the response header is read with the first frame, vmess: the response header opens with the first frame, shadowsocks: no handshake reply, shadowsocks-2022: no handshake reply and sss: the server sends no reply.

The HTTP, SOCKS, Trojan, VLESS, VMess, legacy Shadowsocks and sss codecs fail with their own <prefix>: staging room below the declared reserve (io::Error::other, with the prefixes http, socks, trojan, vless, vmess, shadowsocks and sss) if they are offered less room than they declared. Both Shadowsocks codecs also stage through ss_aead::ChunkEncoder (and Ss2022Stream through build_request), whose texts are shadowsocks: staging room below the frame and, with kind InvalidInput, shadowsocks: record payload over the limit. The runtime offers start and every reply the whole empty buffer, and every other call at least the declared room, so a codec whose staged bytes stay within its STAGING_RESERVE never sees these errors.

The kind below is the one the codec builds. The runtime wraps every codec error as InvalidData (see Failure paths and cancellation).

Codec Condition Kind Text
HttpConnect The request is longer than REQUEST_MAX InvalidInput http: CONNECT request exceeds the codec's reserve
HttpConnect The head reaches MAX_HEAD bytes without a blank line InvalidData http: proxy response head exceeds maximum size
HttpConnect httparse refuses the head, including a head with more than 128 headers InvalidData malformed proxy response: <error>
HttpConnect The head has no status code InvalidData proxy response missing status code
HttpConnect Any status other than 200 ConnectionRefused proxy responded with status <code>
SocksConnect The method reply’s version is not 5 InvalidData unexpected server version
SocksConnect The server chose a method other than the one offered PermissionDenied auth method not supported
SocksConnect The RFC 1929 status is not zero PermissionDenied server rejects account
SocksConnect The request reply’s status is not zero ConnectionRefused server rejects request: <status>, the status in decimal
SocksConnect reply after the handshake Other socks: handshake already done
TrojanDatagram A reply packet declares more than MAX_LENGTH (8,192) bytes InvalidData trojan: oversize payload
VlessStream, VlessDatagram The response version is not 0 InvalidData unexpected vless response version: <version>
VMessStream, VMessDatagram The response header’s length or payload does not open InvalidData vmess: AEAD header open failed
VMessStream, VMessDatagram The response byte is not the one the request chose InvalidData vmess: unexpected response header
VMessStream, VMessDatagram A size field below the tag plus the padding InvalidData vmess: chunk size below overhead
VMessStream, VMessDatagram A chunk tag that is not 16 bytes InvalidData vmess: invalid tag
VMessStream, VMessDatagram A chunk that does not open InvalidData vmess: body chunk open failed
VMessStream, VMessDatagram A body handed over at another length than its size field InvalidData vmess: chunk body length mismatch
SsStream, Ss2022Stream A tag does not verify InvalidData shadowsocks: invalid AEAD tag
SsStream, Ss2022Stream A record declares more than the flavor’s limit InvalidData shadowsocks: record length <len:#x> exceeds <max:#x>, for example 0x4000 exceeds 0x3fff
SsStream, Ss2022Stream The destination does not encode as an address InvalidInput shadowsocks: address, shadowsocks-2022: address
SsStream, Ss2022Stream ss_aead::Aead::new gets a key of another length than the cipher’s InvalidInput shadowsocks: AEAD key of the wrong length
SsStream, Ss2022Stream Sealing fails Other shadowsocks: AEAD seal failed
SsStream, Ss2022Stream seal before start Other shadowsocks: sealed before start, shadowsocks-2022: sealed before start
Ss2022Stream The variable request chunk is over 65,535 bytes InvalidInput shadowsocks-2022: request header longer than a chunk may carry
Ss2022Stream The fixed response chunk has a header type other than HEADER_TYPE_SERVER InvalidData shadowsocks-2022: bad header type (expected server)
Ss2022Stream The response timestamp is more than 30 s away InvalidData shadowsocks-2022: bad timestamp
Ss2022Stream The echoed salt is not the request salt InvalidData shadowsocks-2022: response salt does not match request salt
SssStream, SssDatagram The destination, or the to of a seal_to, is a domain that is not 1 to 255 printable ASCII bytes InvalidData malformed: sss: a domain must be 1 to 255 printable ASCII bytes
SssDatagram A reply record declares more than U bytes InvalidData malformed: sss: varint exceeds its field's cap
SssDatagram A reply record names a domain as its source InvalidData sss: a datagram from the server names a domain, not its source address
concepts/src/client.rs
pub struct ProxyClientRuntime<const BUF_SIZE: usize, Codec, Conn>
where
Codec: ProxyCoreEncodeHandshake,
Conn: Connector<Codec::Target>,
{ /* private fields */ }
impl<const BUF_SIZE: usize, Codec, Conn> ProxyClientRuntime<BUF_SIZE, Codec, Conn>
where
Codec: ProxyCoreEncodeHandshake,
Codec::Error: Error + Send + Sync + 'static,
Conn: Connector<Codec::Target>,
{
pub fn new(codec: Codec, connector: &mut Conn, target: Codec::Target) -> Self;
pub fn codec(&self) -> &Codec;
}

new asserts BUF_SIZE > Codec::STAGING_RESERVE and otherwise panics with BUF_SIZE must exceed the codec's STAGING_RESERVE or nothing can be sealed. It then calls connector.connect(target) and pins the returned future in a Box. Nothing is polled yet: the dial future first runs on the first poll of any plaintext-side method, or of the ProxyClientConnecting that wraps the runtime.

Which traits the runtime implements depends on the codec:

Codec bound Trait implemented Used as
Codec: ProxyCoreEncode AsyncRead + AsyncWrite a stream outbound
Codec: ProxyCoreEncodeDatagram DatagramLink<Addr = Destination> a datagram outbound
always Unpin required by DatagramLink: Unpin and by the Connector::Stream: AsyncRead + AsyncWrite + Unpin bound

Unpin is implemented unconditionally. That is sound because the dial future is kept as Pin<Box<_>>, the upstream stream is Unpin by the Connector::Stream bound, and the codec is never pinned.

The private state:

Field Type Meaning
codec Codec The protocol state machine.
wire Wire<Conn::Future, Conn::Stream> Connecting(Pin<Box<F>>), Up(S), or Down. Down is terminal: every later call that needs the wire fails with NotConnected (an empty poll_write still returns Ok(0)).
staging WriteBuffer<BUF_SIZE> Sealed bytes not yet written to the upstream.
down ReadBuffer<BUF_SIZE> Bytes read from the upstream. The unparsed region is what the codec has not opened yet.
opened Option<(usize, Range<usize>)> A frame opened but not fully handed to the reader: its wire length and the plaintext still to hand out, as absolute offsets into down.
wire_read_closed bool The upstream’s read side returned EOF. Later fill calls return EOF at once.
ended bool The codec reported Opened::End.
finished bool finish has been staged. It is staged once only.
handshaking bool start or the last reply asked for a reply that has not been parsed yet.
packet_unflushed bool A packet was staged for the upstream, and the upstream has not been flushed since. Only poll_send_to sets it.

ProxyClientConnector and ProxyClientConnecting

Section titled “ProxyClientConnector and ProxyClientConnecting”
concepts/src/client.rs
pub struct ProxyClientConnector<const BUF_SIZE: usize, Make, Conn, Upstream> {
make: Make,
dialer: Conn,
upstream: Upstream,
}
impl<const BUF_SIZE: usize, Make, Conn, Upstream>
ProxyClientConnector<BUF_SIZE, Make, Conn, Upstream>
{
pub fn new(make: Make, dialer: Conn, upstream: Upstream) -> Self;
}
impl<const BUF_SIZE: usize, Make, Conn, Upstream, Flow, S, D> Connector<Flow>
for ProxyClientConnector<BUF_SIZE, Make, Conn, Upstream>
where
Make: FnMut(Flow) -> Outbound<S, D>,
S: ProxyCoreEncode<Target = Upstream>,
S::Error: Error + Send + Sync + 'static,
D: ProxyCoreEncodeDatagram<Target = Upstream>,
D::Error: Error + Send + Sync + 'static,
Conn: Connector<Upstream>,
Upstream: Clone,
{
type Stream = ProxyClientRuntime<BUF_SIZE, S, Conn>;
type Datagram = ProxyClientRuntime<BUF_SIZE, D, Conn>;
type Future = ProxyClientConnecting<BUF_SIZE, S, D, Conn>;
fn connect(&mut self, flow: Flow) -> Self::Future;
}
pub struct ProxyClientConnecting<const BUF_SIZE: usize, S, D, Conn>
where
S: ProxyCoreEncodeHandshake,
D: ProxyCoreEncodeHandshake<Target = S::Target>,
Conn: Connector<S::Target>,
{
runtime: Option<
Outbound<ProxyClientRuntime<BUF_SIZE, S, Conn>, ProxyClientRuntime<BUF_SIZE, D, Conn>>,
>,
}

Flow is whatever the server side routes by: the supervisor’s Flow (supervisor/src/topology/flow.rs, an alias of etemenanki_protocols::flow::Flow<Principal> with the fields destination, user, sniffed and source), and String in the concept tests. Upstream is the upstream proxy’s address, cloned for every dial. ProxyClientConnecting implements Future with Output = io::Result<Outbound<ProxyClientRuntime<BUF_SIZE, S, Conn>, ProxyClientRuntime<BUF_SIZE, D, Conn>>>.

Conn is any Connector<Upstream>. concepts/src/link.rs implements Connector<Target> for every F: FnMut(Target) -> Fut whose Fut yields io::Result<Outbound<S, D>> (with S: AsyncRead + AsyncWrite + Unpin and D: DatagramLink), and its connect calls the closure. The concept tests rely on that: their dialers (upstream, one_shot_dialer, and the closure that refuses with ConnectionRefused in upstream_dial_failure_is_connect_failed_not_connected) are closures that return a std::future::Ready. The supervisor passes a TransportConnector, or for sss an SssConnector around one (see The upstream: TransportConnector).

concepts/src/relay.rs
pub struct UnidirectionalConnection<I, O, const BUF_SIZE: usize = 8192> { /* private fields */ }
impl<I, O, const BUF_SIZE: usize> UnidirectionalConnection<I, O, BUF_SIZE> {
pub fn new(input: I, output: O) -> Self;
pub fn transferred(&self) -> u64;
}
// impl<I: AsyncRead, O: AsyncWrite, ..> Future, Output = io::Result<u64>
pub struct Relayed {
pub a_to_b: u64,
pub b_to_a: u64,
}
pub struct BidirectionalConnection<A, B, const BUF_SIZE: usize = 8192> { /* private fields */ }
impl<A, B, const BUF_SIZE: usize> BidirectionalConnection<A, B, BUF_SIZE> {
pub fn new(a: A, b: B) -> Self;
pub fn relayed(&self) -> Relayed;
}
// impl<A, B, ..> Future, where A: AsyncRead + AsyncWrite + Unpin, B: AsyncRead + AsyncWrite + Unpin;
// Output = io::Result<Relayed>

UnidirectionalConnection pins its input and output through pin_project, so neither needs to be Unpin. BidirectionalConnection owns a and b and borrows each through &mut inside its poll, so one endpoint can be read in one direction and written in the other without splitting it; that is why both must be Unpin. Relayed derives Debug, Clone, Copy, PartialEq, Eq and Default. How they copy is in Relay futures in depth.

A client runtime owns two buffers, staging (a WriteBuffer<BUF_SIZE>) and down (a ReadBuffer<BUF_SIZE>), and one boxed dial future. BUF_SIZE caps both buffers; neither is allocated at that size up front (concepts/src/buffer.rs). new, which ProxyClientConnector::connect calls synchronously before the upstream is dialed, allocates the boxed dial future whole, down at min(2048, BUF_SIZE) bytes (INITIAL, 2 KiB for every supervisor size), and nothing for staging, which holds no storage until the first stage. Both then grow with the bytes that pass through them, up to BUF_SIZE. When new runs depends on the caller:

  • For a TCP flow under a server runtime, it is the moment the runtime applies the core’s Effect::Open and calls its connector: directly with a bare ProxyClientConnector (the concept tests), and in the supervisor through AppConnector::connect, Target::connect_stream, Outbound::connect_stream and ProxyClient::connect, all synchronous.
  • For a UDP flow in the supervisor, AppConnector::connect dials nothing and returns a FanOutLink. The datagram runtime is built when the fan-out opens a sub-link for the first packet routed to that outbound, through Target::connect_datagram (see The path of one TCP flow).
  • For a query of the supervisor’s resolver, it is the first poll of the future that RoutedDialer::dial returned.

In the supervisor the boxes nest. TransportConnector::connect returns its dial future already boxed (DialFuture), SssConnector::connect boxes one more future around that one, and ProxyClientRuntime::new boxes the result again when it stores it. Outbound::connect_stream and Outbound::connect_datagram wrap the ProxyClientConnecting in a boxed StreamFuture or DatagramFuture, and the resolved runtime is boxed once more: as the Pin<Box<dyn Stream>> in OutboundStream::Proxy, or as the Box<dyn DatagramLink> inside OutboundDatagram.

The buffers double up to BUF_SIZE and stop there, so backpressure comes from them being full at the cap.

flowchart LR
  W["poll_write(plain)"] --> S["codec.seal"]
  S --> ST["staging: WriteBuffer"]
  ST --> U["upstream stream"]
  U --> D["down: ReadBuffer"]
  D --> O["codec.open, in place"]
  O --> R["poll_read copies plain out"]
  • staging is FIFO. start, reply, seal, seal_to and finish all append through WriteBuffer::staging(). room() counts against BUF_SIZE, not against what is allocated, and Staging::reserve grows the storage when a stage runs past it: to the larger of the end of the stage, twice the current length and 2 KiB, never past BUF_SIZE. drain writes pending() to the upstream and advances start; when the last pending byte leaves, advance_start resets both ends to 0. WriteBuffer::room() slides the pending bytes to the front only when the tail has reached BUF_SIZE, which is the only copy the buffer makes on its own. The request header staged by start therefore always leaves before the first sealed frame.
  • down has three regions: bytes already opened, [start, end) unparsed, and free space. fill reads into the free tail and, only when the tail is empty, calls make_room(), which moves the unparsed bytes to the front and doubles the storage while it is below BUF_SIZE. If the unparsed region fills all BUF_SIZE bytes (is_saturated(): start == 0 and end == BUF_SIZE), the frame cannot fit and fill fails with InvalidData upstream frame larger than the client runtime's buffer.
  • In place. open and open_from decrypt inside down. The runtime copies plaintext straight from down into the caller’s ReadBuf, with no intermediate buffer. A large frame read through a small ReadBuf is handed out across several calls: opened remembers the absolute range still to deliver, and down.advance_start(consumed) runs only once the last byte has gone. fill carries debug_assert!(self.opened.is_none(), "compacting under an opened frame"), and poll_read returns before calling fill while a frame is opened.

The buffer types themselves are described on The server runtime, which uses the same ReadBuffer and WriteBuffer.

stateDiagram-v2
  [*] --> Connecting: new
  Connecting --> Down: dial error or datagram link
  Connecting --> Down: start error
  Connecting --> Handshaking: start returns AwaitReply
  Connecting --> Open: start returns Done
  Handshaking --> Handshaking: Step, next AwaitReply
  Handshaking --> Open: Step, next Done
  Handshaking --> Down: EOF or wire I/O error
  Open --> Ended: codec opens End
  Open --> Down: wire I/O error
  Ended --> [*]
  Down --> [*]

Connecting, Up and Down are the Wire variants. Handshaking is Up with handshaking = true, Open is Up with the handshake done, and Ended is Open with ended = true. is_ready() is true exactly in Open and Ended. Before that, every plaintext operation returns Pending while the dial or handshake is still in progress.

Three private helpers drive the machine:

  • wire() polls the dial future. On Ok(Outbound::Stream(s)) it moves to Up(s) and calls codec.start at once; AwaitReply sets handshaking. On Ok(Outbound::Datagram(_)) it moves to Down and fails with Unsupported proxy client runtime needs a stream to the upstream, got a datagram socket. On a dial error it moves to Down and returns that error. A start error also moves to Down.
  • ready() is wire() then handshake().
  • prologue() is ready() then drain(), the common start of poll_flush, poll_read and poll_recv_from.

Because both poll_write and poll_read call ready(), a caller that only writes still gets the handshake replies read. plaintext_waits_for_every_handshake_reply in concepts/tests/client.rs pins that a write-only caller does not deadlock.

handshake() loops while handshaking is true:

  1. drain everything staged (the greeting from start, or the round the last reply staged). It returns Pending until the upstream has accepted all of it.
  2. If down holds unparsed bytes, call codec.reply(down.unparsed(), staging):
    • Step { consumed, next } with consumed larger than the bytes given fails with codec consumed more reply than it was given.
    • Step with consumed == 0, nothing staged (measured by comparing staging.room() before and after the call) and next == AwaitReply fails with codec handshake step made no progress. Without this check the loop would spin.
    • Otherwise the runtime calls down.advance_start(consumed), sets handshaking = (next == AwaitReply) and loops.
    • NeedMore falls through to step 3.
  3. fill one chunk from the upstream. EOF here moves the wire to Down and fails with UnexpectedEof upstream closed during the handshake.

Bytes that arrive in the same read as the final reply stay in down and are opened as the first frames. plaintext_waits_for_every_handshake_reply sends the connect reply and a data frame in one write and reads the frame back.

With the supervisor’s HTTP_BUF of 16 KiB, an HTTP status head that has not ended when down is full at 16 KiB fails in fill with upstream frame larger than the client runtime's buffer, before the codec’s own MAX_HEAD (64 KiB) check is reached.

poll_write(plain):

  1. An empty plain returns Ok(0) at once, without driving the dial.
  2. ready(): dial, start, reply rounds.
  3. make_room(STAGING_RESERVE + 1): write staged bytes to the upstream until that much room is free. Pending here is the backpressure path: the upstream is not accepting bytes, so the caller’s write stays pending.
  4. Offer min(plain.len(), room - STAGING_RESERVE) bytes to seal. A return of 0, or more than was offered, fails with codec sealed an impossible byte count.
  5. Try to drain. A Pending drain is ignored, because the bytes are already staged and the next poll or poll_flush sends them. An error is returned.
  6. Return Ok(taken).

make_room returns InvalidInput frame larger than the client runtime's buffer if the staging buffer is already empty and still lacks the room. A stream write never gets there, because BUF_SIZE > STAGING_RESERVE guarantees an empty buffer has STAGING_RESERVE + 1 bytes free.

poll_flush runs prologue() (a Pending drain holds the flush) and then flushes the upstream stream. poll_shutdown runs ready(), stages finish once (after make_room(STAGING_RESERVE)) and sets finished, drains, flushes and finally shuts down the upstream stream’s write side. handshake_then_seal_and_open_over_the_wire checks that a plaintext shutdown puts the close frame on the wire and then half-closes it.

The server runtime follows every poll_write that takes at least one byte of a forward with a poll_flush. If the flush is Pending, it marks the slot need_flush and flushes again the next time it services that key, so a sealed frame does not sit in staging.

poll_read(buf) first runs prologue(), with one difference: a Pending drain does not block the read. The comment in the code puts it as “a stalled wire write must not block reading”. An error from the prologue is returned. If the handshake is not done (!is_ready()), poll_read returns Pending. Otherwise it loops:

  1. If a frame is opened, copy as much of its plaintext as buf holds and return. Once the whole frame has been handed out, clear opened and advance down past the frame.
  2. If ended, return Ok(()) with nothing filled, which is EOF.
  3. If down has unparsed bytes, call codec.open:
    • Frame passes check_frame. An empty plain is skipped (the frame is consumed and the loop continues). Otherwise opened records the frame.
    • End passes check_frame with an empty range, is consumed, and sets ended.
    • NeedMore falls through.
  4. fill. At upstream EOF, return EOF if down is empty, or UnexpectedEof upstream closed inside a frame if a partial frame remains (eof()).

check_frame(len, consumed, plain) rejects consumed == 0, consumed > len, plain.start > plain.end and plain.end > consumed with codec opened an impossible frame. Each of these would otherwise make the loop spin or read outside the frame.

How the stream ends:

Upstream does poll_read returns
Sends a frame the codec opens as End EOF. Later reads return EOF too, and nothing after the closing frame is opened.
Closes the connection between frames EOF. For a codec whose finish stages nothing, this is the normal end of a flow.
Closes the connection inside a frame UnexpectedEof upstream closed inside a frame
Closes the connection during the handshake UnexpectedEof upstream closed during the handshake, and the wire goes Down

With a ProxyCoreEncodeDatagram codec the runtime is a DatagramLink addressed by Destination. The packets still travel over the one upstream stream.

  • poll_send_to(plain, to) runs ready(), then make_room(STAGING_RESERVE + plain.len()). If staging is already empty and there is still not enough room, the packet can never fit, and the call fails with InvalidInput frame larger than the client runtime's buffer. If the codec answers None even though that room was free, the call fails with InvalidInput codec refused a packet that fits its reserve. On success it sets packet_unflushed and tries to drain. Once everything staged has been written, it flushes the upstream stream (flush_packets). A Pending drain or flush is left for a later poll, and the call returns Ok(plain.len()), since a packet is taken whole or not at all. A flush error moves the wire to Down and fails the call.
  • poll_recv_from(buf) runs the same prologue as poll_read. When the prologue has written everything staged, it finishes a flush that a packet left pending (flush_packets). It returns one packet per call. A data frame whose source is Some is copied into buf, truncated if buf is smaller, as UDP does. The whole frame is consumed either way. A frame whose source is None is skipped. After Opened::End, or at upstream EOF with an empty down, the call fails with a bare UnexpectedEof; at upstream EOF with a partial frame it fails with upstream closed inside a frame. A datagram link has no end of stream, so a server core sees the end as an outbound error for the key.

The flush is the runtime’s own because a datagram link has no flush, so nothing above the runtime flushes a datagram outbound. An upstream that holds small writes until it is flushed would otherwise keep a packet until a later one pushed it out: a WebSocket sink keeps messages below its write buffer, and sss’s transform chains hold a short write until a flush. While a flush is pending, the next poll_send_to or poll_recv_from finishes it. a_packet_reaches_a_wire_that_holds_writes_until_flushed pins this with a tokio::io::BufWriter as the upstream.

In the server runtime a failed send becomes Event::SendFailed and the key stays live, while a failed receive becomes Event::OutboundError and removes the key.

connect(flow) does three things synchronously:

  1. Clones upstream.

  2. Calls make(flow). The closure returns Outbound::Stream(codec) or Outbound::Datagram(codec), which decides the flow’s payload shape.

  3. Wraps the codec in ProxyClientRuntime::new(codec, &mut dialer, upstream), which allocates a 2 KiB read buffer and creates the dial future, and returns it inside a ProxyClientConnecting.

ProxyClientConnecting is a future. Each poll calls the runtime’s private poll_connected: ready() (dial, start, every reply round), then drain() (every handshake byte written), then poll_flush on the upstream stream. Only when all three are done does the future resolve to Ok(Outbound::Stream(runtime)) or Ok(Outbound::Datagram(runtime)). On an error it drops the runtime, and with it the upstream connection, and resolves to that error. A flush error also moves the wire to Down before the runtime is dropped. Polling the future again after it has resolved panics with polled after completion.

This timing is what makes a server core’s events mean what they say. The server runtime polls the connector’s future when that key’s waker fires, and turns its result into Event::Connected or Event::ConnectFailed (see The server runtime). So:

  • Connected is delivered only after the upstream is dialed, the codec’s handshake has finished, and the handshake bytes have been written and flushed into the upstream stream. A SOCKS or HTTP server core that answers its own client on Connected therefore answers only once the upstream proxy has agreed.
  • ConnectFailed covers every failure before that point: the dial itself, a refused SOCKS method or request, an HTTP status other than 200, or an upstream that closes during the handshake. The core can send its client a real refusal instead of a premature success.

The server runtime stores the client runtime as the key’s stream only when ProxyClientConnecting resolves; until then the key’s slot holds the connecting future. So no forward aimed at that key reaches the client runtime’s poll_write before the request header has been flushed on its own.

The supervisor wraps each proxy outbound in one ProxyClient:

supervisor/src/topology/outbound/proxy.rs
pub type NoUdp = NoCodec<Destination, io::Error>;
pub type Make<S, D> = Box<dyn FnMut(Flow) -> link::Outbound<S, D> + Send>;
pub struct ProxyClient<const BUF: usize, S, D, C = TransportConnector> {
inner: Mutex<ProxyClientConnector<BUF, Make<S, D>, C, Destination>>,
}
impl<const BUF: usize, S, D, C> ProxyClient<BUF, S, D, C>
where
S: ProxyCoreEncode<Target = Destination, Error = io::Error>,
D: ProxyCoreEncodeDatagram<Target = Destination, Error = io::Error>,
C: Connector<Destination>,
{
pub fn new(make: Make<S, D>, transport: C, server: Destination) -> Self;
pub fn connect(&self, flow: Flow) -> ProxyClientConnecting<BUF, S, D, C>;
}

C is the connector the upstream is dialed through. It defaults to TransportConnector, which every proxy outbound uses except sss, whose C is SssConnector<TransportConnector> (see sss: a connector around the transport).

  • The mutex. ProxyClientConnector::connect takes &mut self (Make is an FnMut, and Connector::connect takes &mut self), while the outbound is shared by every flow. ProxyClient::connect is self.inner.lock().connect(flow): the parking_lot::Mutex guard lives only for that statement, which runs make, allocates the runtime’s 2 KiB read buffer and asks the connector for its dial future. No I/O and no .await happen under the lock; the future is awaited outside it.
  • The codec per flow. supervisor/src/build/outbound.rs → build_outbound builds each client with a make closure; for SOCKS, SocksOutbound::new in supervisor/src/topology/outbound/mod.rs builds the CONNECT closure. Trojan, VLESS and VMess return a datagram codec when flow.destination.network == DialNetwork::Udp and a stream codec otherwise. HTTP, SOCKS CONNECT, Shadowsocks and Shadowsocks 2022 always return a stream codec. sss has two clients, one per kind: SssOutbound::tcp always returns an SssStream and SssOutbound::udp always an SssDatagram, and Outbound::connect_stream and connect_datagram pick the client. VMess always passes global_padding = true, and VLESS passes the outbound’s flow to VlessStream::new and to VlessDatagram::with_flow. Keys are derived once, outside the closure: Trojan’s password_hash, Shadowsocks’ evp_bytes_to_key.
  • The upstream. server is tcp(upstream), the proxy server’s Destination with its network forced to TCP, cloned into every dial.
  • Adapters. proxy_stream and proxy_datagram, generic over the connector C like ProxyClient, fold the resolved runtime into the supervisor’s closed types. OutboundStream has the variants Tcp, Proxy, Wg, Hy2 and Blackhole; a stream runtime is boxed as OutboundStream::Proxy(ProxyStream), where ProxyStream = Pin<Box<dyn Stream>> and Stream is the supervisor’s name for AsyncRead + AsyncWrite + Send, with a blanket impl for every such type. A datagram runtime becomes OutboundDatagram(Box<dyn DatagramLink<Addr = Destination> + Send>). A runtime of the wrong kind is an io::Error::other (a TCP flow was dialed as datagrams, a UDP flow was dialed as a stream); neither happens, because make decides from the same network field that chose between connect_stream and connect_datagram. OutboundStream::Proxy also carries the DNS outbound’s DnsTcpStream and the AnyTLS outbound’s AnyTlsStream, neither of which is a client runtime.

Each Outbound variant fixes the BUF of its runtime (supervisor/src/topology/outbound/mod.rs):

Outbound variant ProxyClient UDP flow (connect_datagram)
Http ProxyClient<HTTP_BUF, HttpConnect, NoUdp> fails with Unsupported http carries no datagrams
Socks SocksOutbound::tcp: ProxyClient<SOCKS_BUF, SocksConnect, NoUdp> SocksUdpLink (see SOCKS UDP)
Trojan ProxyClient<TROJAN_BUF, TrojanStream, TrojanDatagram> TrojanDatagram runtime
Vless ProxyClient<VLESS_BUF, VlessStream, VlessDatagram> VlessDatagram runtime
Vmess ProxyClient<VMESS_BUF, VMessStream, VMessDatagram> VMessDatagram runtime
Shadowsocks ProxyClient<SS_BUF, SsStream, NoUdp> fails with Unsupported shadowsocks carries no datagrams
Ss2022 ProxyClient<SS2022_BUF, Ss2022Stream, NoUdp> fails with Unsupported shadowsocks-2022 carries no datagrams
Sss SssOutbound::tcp: ProxyClient<SSS_TCP_BUF, SssStream, NoUdp, SssConnector<TransportConnector>> SssOutbound::udp: ProxyClient<SSS_UDP_BUF, NoUdp, SssDatagram, SssConnector<TransportConnector>>

The three refusals come from no_udp(what) (<what> carries no datagrams) and are returned without dialing. The other variants hold no ProxyClient: Freedom, Blackhole and Dns reach no proxy, and Wireguard, Hysteria2 and Anytls are connectors of their own. The buffer sizes are in Limits; how build_outbound builds every outbound is on Outbounds.

The inner connector of every ProxyClient is protocols/src/transports/connect.rs → TransportConnector, or, for sss, an SssConnector around one. build_outbound’s transport_connector(spec, dns, socket, vision) builds it as TransportConnector::new(kind, Dialer::new(socket.clone()), dns.servers.clone(), spec.address_family), with TCP, TLS, WebSocket, gRPC or REALITY chosen by the upstream’s StreamShape. vision is the VLESS user id when a VLESS outbound’s flow is Vision, and None for every other outbound.

  • Its Connector<Destination> impl has Stream = TransportStream and Datagram = NoDatagram: it always yields a byte stream, because a proxy’s UDP rides inside that stream.
  • connect clones the connector (its TransportKind is behind an Arc) into a boxed async block that runs dial. ProxyClientRuntime::new boxes that future again when it stores it.
  • dial refuses a UDP destination with Unsupported a proxy transport carries no datagrams of its own. It resolves the server with the supervisor’s dns.servers resolver and the upstream’s address_family strategy, then tries each resolved address in order, one at a time, until one connects (environment/src/dial/tcp.rs → TcpDialer::connect_any; the attempts are not raced). If none connects, connect_any fails with ConnectionRefused failed to connect to any address (<addr>: <error>; ...), listing every attempt, or (none given) for an empty list. The connected socket is then wrapped in the transport.
  • TransportKind is #[non_exhaustive]. It has the variants Tcp, Tls(ClientConfig), Ws { target, tls } and Grpc { authority, service, mode, user_agent, tls }, and, with the protocols crate’s reality feature, which the supervisor turns on, Reality { config, vision }. transport_connector builds Ws and Grpc with TransportKind::ws (a ?ed=N suffix on the path enables WebSocket early data) and TransportKind::grpc (GrpcMode::Gun and DEFAULT_USER_AGENT), and calls neither multi nor user_agent. TransportConnector::tcp(), plain TCP with the default Dialer, Resolver and strategy, has no caller in the workspace.
  • For a REALITY upstream, transport_connector builds TransportKind::reality(config) and, when vision is set, adds .vision(uuid). dial runs the REALITY client handshake over the connected socket and yields TransportStream::Reality, or, with vision, TransportStream::Vision, which wraps that stream in the Vision adapter. The VLESS codec above it still writes plain VLESS, or XUDP for a UDP flow; the adapter frames the body. REALITY is on REALITY transport and the flow on VLESS Vision.

The dial steps and transports are on Outbounds, TCP and TLS transports and WebSocket and gRPC transports. The socket policy the Dialer applies is on Dialers.

sss is the reason ProxyClient takes its connector as a type parameter. Its transform chains sit between the codec and the transport, so protocols/src/sss/client.rs → SssConnector wraps the connector that dials the transport:

protocols/src/sss/client.rs
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSettings {
pub up: Chain,
pub down: Chain,
pub max_datagram: u16,
pub flush_delay: Duration,
}
#[derive(Clone)]
pub struct SssConnector<C> { /* inner: C, settings: ClientSettings */ }
impl<C> SssConnector<C> {
pub fn new(inner: C, settings: ClientSettings) -> Self;
}
impl<C> Connector<Destination> for SssConnector<C>
where
C: Connector<Destination, Datagram = NoDatagram>,
C::Future: Send + 'static,
C::Stream: Send + 'static,
{
type Stream = TransformStream<C::Stream>;
type Datagram = NoDatagram;
type Future = DialFuture<C::Stream>; // Pin<Box<dyn Future<Output = …> + Send>>
}

connect starts the inner dial and, once it yields a stream, wraps it as TransformStream::new(stream, up.encoder(), down.decoder()).with_flush_delay(flush_delay). The codecs above it read and write sss’s plain bytes, and the chains run on the wire side. ClientSettings::default() has identity chains, max_datagram (U) 65,535 and a zero flush_delay (t_c). build_outbound builds one SssConnector over the upstream’s TransportConnector and gives a clone to each of SssOutbound’s two clients.

The flush that ProxyClientConnecting makes before it resolves (see Connecting through ProxyClientConnector) is what puts the sss request header on the wire as one flushed call of its own. Payload follows without waiting for a reply. The chains, the flush delay and the server’s pre-authentication budget are on sss and sss transforms.

flowchart TB
  SR["ProxyServerRuntime, serve.rs drive"] -->|"applies Effect::Open"| AC["AppConnector::connect"]
  AC --> T["Target::connect_stream"]
  T --> O["Outbound::connect_stream"]
  O --> PC["ProxyClient::connect, under the mutex"]
  PC --> RT["ProxyClientRuntime::new, boxed dial future"]
  RT -.->|"polled by the server runtime"| PCC["ProxyClientConnecting resolves"]
  PCC --> PS["proxy_stream: OutboundStream::Proxy"]
  PS --> M["Metered, then close_if_drained"]
  M -->|"Event::Connected"| SR

The supervisor’s serve.rs → drive runs a ProxyServerRuntime over an AppConnector (supervisor/src/connector.rs) with showing_progress. When the runtime applies Effect::Open, it calls AppConnector::connect, which admits the flow on its session, routes it on the current plane, resolves a balancer to its member, and calls Target::connect_stream (supervisor/src/topology/plane.rs). That calls Outbound::connect_stream synchronously, so the client runtime and its dial future exist before AppConnector::connect returns. The returned future awaits ProxyClientConnecting, folds it with proxy_stream, wraps the stream in Metered (Tracker::meter_stream, which files the flow under the outbound version that carries it), and hands the flow’s entry to Target::close_if_drained. When a drain policy closes an outbound version, Target::close_flows sets the version’s drained flag and kills every tracked flow filed under it (Tracker::kill_where); a killed flow’s next read, write, flush or shutdown through Metered fails with ConnectionAborted the flow was killed. close_if_drained covers a flow that was still dialing during the drain: it sees the flag when it lands and is killed then. Supervisor::close_rerouted, when a front end calls it after a route change, kills through Tracker::kill_where too, every flow the current plane would send to another outbound. The server runtime stores the result as the key’s stream and polls it through every wrapper with the key’s own waker, so upstream readiness wakes exactly that key. Routing, admission and drains are on The routing plane, metering on Tracking, and serving on Serving.

A UDP flow is not dialed by AppConnector::connect: it becomes a FanOutLink that routes packet by packet and opens one datagram link per target with Target::connect_datagram, so a Trojan, VLESS, VMess or sss client runtime is one sub-link of it. The fan-out is described on Outbounds.

In Split mode, supervisor/src/build/dns.rs gives the resolver for the through_proxy servers a RoutedDialer (supervisor/src/topology/outbound/dns.rs) as its StreamDialer, with the pre_proxy resolver as its bootstrap. RoutedDialer::dial(server) builds a TCP Flow toward the server’s IP and port for the anonymous user, routes it with Plane::route_upstream (the route table alone, without the port-53 interception that Plane::route applies) under the inbound tag dns (DNS_FLOW_TAG), and opens it with Target::connect_stream. When the rule for that address names a proxy outbound, the query runs over a ProxyClientRuntime, returned as a plain OutboundStream and polled by the resolver’s query future. AppConnector is not involved, so this stream is not wrapped in Metered, and a drain, which kills tracked flows, does not reach it.

The dialer holds the plane cell through a Weak, because the plane owns the resolver through its outbounds and a strong reference would keep both alive forever. Once the cell is gone, the dial fails with NotConnected dns: the supervisor this resolver dials through is gone. The resolver and the DNS service are described on DNS.

katana 6.0.0 has no proxy client code of its own. Its [[outbound]] entries are lowered by src/lower/outbound.rs → lower_outbound into the same OutboundProtocolSpec values, so they run on the supervisor’s ProxyClient:

  • The accepted protocols, compared in lower case, are socks/socks5, http, vmess, vless, shadowsocks/ss (one of the three ciphers 2022-blake3-aes-128-gcm, 2022-blake3-aes-256-gcm and 2022-blake3-chacha20-poly1305 selects Shadowsocks 2022, and an iPSK:...:uPSK password gives the identity chain; any other name goes to the legacy cipher table and, if that does not know it either, fails katana --test with, for example, configuration error: node 1: unsupported shadowsocks cipher "2022-blake3-foo"), wireguard/wg, and direct/freedom.
  • Every proxy upstream uses StreamShape::Tcp with no TLS and no REALITY settings: the module states that TLS, WebSocket and gRPC toward an upstream are out of scope. A VLESS outbound announces no flow (VlessFlow::None).
  • There is no Trojan outbound. A node whose [[outbound]] says protocol = "trojan" fails katana --test with configuration error: node 1: unknown outbound protocol "trojan" (for node_id = 1).

The lowering is on Lowering inbounds and outbounds. katana’s end-to-end tests (tests/unit/e2e.rs) use the client runtime directly as their test client: ProxyClientRuntime<VMESS_BUF, VMessStream, TcpConnector> and ProxyClientRuntime<VLESS_BUF, VlessStream, TcpConnector>, both with a 32 KiB buffer, split into halves with tokio::io::split. an_sss_node_relays_through_its_chains_and_meters drives an sss node with a 16 KiB ProxyClientRuntime over an SssStream codec and SssConnector::new(TcpConnector, settings), with a transform chain in each direction.

SOCKS5 UDP does not fit a ProxyCoreEncodeDatagram codec. Its packets do not ride inside the stream to the upstream: they are separate UDP datagrams, each with its own SOCKS5 UDP header, sent to a relay address that the server names in its reply to UDP ASSOCIATE. So SocksOutbound::connect_datagram (supervisor/src/topology/outbound/mod.rs) does not use the client runtime. It dials a control stream with TransportConnector::dial, so the outbound’s transport applies to it, and hands it to protocols/src/socks/udp_link.rs → SocksUdpLink::associate, together with a closure that binds the local socket with the outbound’s UdpDialer in the relay’s address family. The link implements DatagramLink<Addr = Destination> itself and accepts replies only from the relay address the server named.

The link’s handshake, packet framing, source check, control stream and errors are on SOCKS; how the supervisor builds SocksOutbound is on Outbounds.

UnidirectionalConnection copies input to output in one loop:

  1. When the buffer is drained and the reader has not ended, reset pos and cap and read into the whole buffer. A read of 0 bytes sets read_done; an error is returned. If the read is Pending and bytes were written since the last flush (need_flush), flush the writer first, so a peer is not left waiting on bytes the writer buffers, then return Pending.
  2. Write buf[pos..cap] until it is empty. A write of 0 bytes fails with WriteZero. Each write adds to transferred and sets need_flush.
  3. Once the reader has ended and the buffer is drained, flush and resolve to transferred. It does not shut the writer down.

BidirectionalConnection runs one such loop per direction (a private Half with its own boxed buffer, pos, cap, read_done, shutdown_done, need_flush and transferred) and polls a → b then b → a on every poll. A direction whose reader has ended and whose buffer is drained shuts its writer down once (shutdown_done), which half-closes that side, and then reports ready on every later poll. The future resolves to Relayed once both directions are ready. An error in either direction fails the whole future at once. relayed() reads both counters at any time, which lets a caller watch progress.

Both allocate one Box<[u8; BUF_SIZE]> per direction through boxed_array at construction and nothing after. The SOCKS inbound’s relay_with_idle_guard (protocols/src/socks/server.rs) instantiates BidirectionalConnection with RELAY_BUF (16 * 1024) and compares relayed() every RELAY_IDLE_TIMEOUT (300 s); if nothing moved in that interval, it fails with TimedOut socks: relay idle. See SOCKS. An sss inbound that hands a refused stream to its fallback relays it the same way (protocols/src/sss/server.rs → relay), with 8192-byte buffers, the same RELAY_IDLE_TIMEOUT check and TimedOut sss: fallback idle. See sss.

Data flow: a relay through a client runtime

Section titled “Data flow: a relay through a client runtime”

server_runtime_relays_through_a_client_runtime_in_one_task in concepts/tests/client.rs builds exactly this shape. A passthrough server core reads a 4-byte target and relays the rest. Its connector is a ProxyClientConnector over TinyCodec, a toy codec with a [0xC0][len:u8][target] header and [kind][len:u16][payload ^ 0x55] frames (only the payload is XOR-masked), where kind 1 is data and kind 2 is the close, and at most 32 bytes go into one frame. The server core answers + on Connected and - on ConnectFailed.

sequenceDiagram
  participant C as Client
  participant SR as ProxyServerRuntime
  participant Core as Server core
  participant CR as ProxyClientRuntime
  participant U as Upstream proxy
  Note over SR,CR: one task, no channels
  C->>SR: "dst1" + payload
  SR->>Core: Event::Transport
  Core-->>SR: Open(target), Forward
  SR->>CR: ProxyClientConnector::connect(flow) builds CR
  SR->>CR: poll ProxyClientConnecting
  CR->>U: header from codec.start, drained and flushed
  CR-->>SR: connecting future resolves Ok
  SR->>Core: Event::Connected
  Core-->>C: "+"
  SR->>CR: poll_write(payload), poll_flush
  CR->>U: sealed DATA frame
  U->>CR: DATA frame
  SR->>CR: poll_read (per-key waker fired)
  CR-->>SR: plaintext, opened in place
  SR->>Core: Event::Outbound
  Core-->>C: staged plaintext
  C->>SR: EOF
  SR->>Core: Event::TransportEof
  Core-->>SR: Effect::Shutdown
  SR->>CR: poll_shutdown
  CR->>U: CLOSE frame from codec.finish, then write-side shutdown
  U->>CR: CLOSE frame
  CR-->>SR: poll_read EOF (Opened::End)
  SR->>Core: Event::OutboundEof

The test pins three things beyond the round trip:

  • The upstream pipe holds only 4 bytes and the header is 6 (\xC0\x04dst1), so the header cannot leave until the upstream reads. The client sees no + during that time.
  • The client codec encoded the server core’s target (dst1), not the upstream’s address (upstream).
  • The server runtime’s Traffic counts what crosses the outbound’s plaintext side, not the upstream wire: outbound_tx == 23 (the payload, with no header or framing) and outbound_rx == 8.
  1. Implement ProxyCoreEncodeHandshake with Target = Destination and Error = io::Error, the bounds the supervisor’s ProxyClient requires. Encode the flow’s destination in start. Return AwaitReply only if the upstream must answer before payload, and make every Step consume, stage or finish.

  2. Declare an honest STAGING_RESERVE: the largest handshake round, closing frame or per-seal overhead you ever stage. Then Staging::reserve and Staging::put cannot fail for a codec that keeps to it.

  3. Implement ProxyCoreEncode (take at most one frame per seal, open one frame per open) or ProxyCoreEncodeDatagram (one packet per seal_to and per data frame). Consume a response header as an empty frame instead of adding a reply round, and never decrypt in place a byte you do not consume.

  4. Pick a BUF_SIZE larger than STAGING_RESERVE, or ProxyClientRuntime::new panics on the first flow, and larger than the biggest frame the upstream may send, or reading such a frame fails the flow with upstream frame larger than the client runtime's buffer. Add a *_BUF constant and an Outbound variant in supervisor/src/topology/outbound/mod.rs, and a build_outbound arm with a make closure in supervisor/src/build/outbound.rs. A protocol that must wrap the transport, as sss does with its transform chains, passes its own connector as ProxyClient’s fourth type parameter. The rest of the supervisor and front-end side (spec variant, validation, lowering) is listed in Outbounds.

  5. Add a unit test that drives the codec with no I/O in protocols/tests/unit/<protocol>/codec.rs, included from the codec file with #[cfg(test)] #[path = …] mod tests; as the existing codecs do. Add a new_server_vs_new_client_* pipeline test against the real server core.

Invariant Enforced by Pinned by
No plaintext is sealed or delivered before the handshake is Done ready() at the top of every plaintext-side poll; the is_ready() guard in poll_read and poll_recv_from plaintext_waits_for_every_handshake_reply
The request header leaves before the first frame staging is FIFO; start stages the header before any seal handshake_then_seal_and_open_over_the_wire
A resolved dial means dialed, handshaken and flushed ProxyClientConnecting::poll calls poll_connected (ready, drain, poll_flush) server_runtime_relays_through_a_client_runtime_in_one_task
Upstream refusals become ConnectFailed, not Connected Dial and handshake errors resolve the connecting future with Err upstream_dial_failure_is_connect_failed_not_connected, refused_upstream_handshake_is_connect_failed_not_connected
A codec contract violation fails and never spins The no-progress and consumed > len checks in handshake; check_frame; the seal count check handshake_step_without_progress_is_rejected, zero_length_frame_is_rejected, end_marker_beyond_the_slice_is_rejected, datagram_zero_length_frame_is_rejected; the seal count check is not tested directly
A codec error surfaces as InvalidData with the codec’s message codec_err refused_handshake_fails_the_flow, new_server_refuses_bad_credentials_with_407
A client runtime’s buffers grow to BUF_SIZE and no further ReadBuffer::make_room doubles up to BUF_SIZE; Staging::reserve never grows past it; at the cap the runtime’s make_room waits for the upstream staging_grows_to_n_and_no_further, read_buffer_starts_small_and_doubles_up_to_n, backpressure_from_the_wire_reaches_the_writer
Upstream frames larger than the buffer are rejected fill fails when down.is_saturated() read_buffer_saturation_means_frame_too_large pins is_saturated; the runtime path is not tested directly
The Shadowsocks 2022 buffer holds the largest record Ss2022Stream::BUF_SIZE = MAX_RECORD_LEN ss2022_client_takes_full_size_chunks_from_a_raw_server
down is never moved under an opened frame poll_read returns before fill while opened is set; debug_assert! in fill before make_room small_reads_take_one_frame_across_several_calls exercises the path
A failed dial stays failed Wire::Down is terminal and every later call returns NotConnected dial_failure_surfaces_on_first_use
A truncated upstream frame is an error, not a clean EOF eof() checks for unparsed bytes at wire EOF truncated_upstream_frame_is_unexpected_eof
One receive is one packet poll_recv_from returns after one data frame datagram_codec_sends_and_receives_packets_over_the_stream
A sent packet is flushed to the upstream poll_send_to sets packet_unflushed and calls flush_packets once the drain is done; poll_recv_from and the next poll_send_to finish a pending flush a_packet_reaches_a_wire_that_holds_writes_until_flushed
A response header is consumed as an empty frame Each codec’s first open or open_from stream_codec_consumes_the_response_header_as_an_empty_frame, datagram_codec_frames_to_the_fixed_target, stream_codec_seals_the_header_and_chunks_and_opens_the_response, response_salt_is_an_empty_frame_and_records_open_in_place, request_header_then_records_and_a_bound_response
A Shadowsocks 2022 response is bound to the request salt ct_eq(echoed, request_salt) in Ss2022Stream::open request_header_then_records_and_a_bound_response
A Shadowsocks record presented again is never decrypted twice ss_aead::ChunkDecoder opens the length from a copy and keeps it in pending_len a_record_presented_again_is_never_decrypted_twice
A refused seal leaves the codec’s state untouched ChunkEncoder::seal_record reserves the whole record before sealing; ChunkStream::seal_chunk_into checks the room before it advances the keystream a_refused_seal_stages_nothing_and_keeps_the_counter, chunks_seal_into_staging_and_open_in_place
BidirectionalConnection half-closes each direction when its reader ends Half::poll shuts the writer down once after EOF bidirectional_relays_both_ways_and_half_closes
BUF_SIZE leaves room to seal assert! in ProxyClientRuntime::new enforced at construction

Every failure of the client runtime reaches the caller as an io::Error:

Condition Kind Message Wire afterwards
Inner dial fails the dial error’s kind the dial error; for a TransportConnector whose resolved addresses all fail, ConnectionRefused failed to connect to any address (<addr>: <error>; ...) Down
Inner connector yields a datagram link Unsupported proxy client runtime needs a stream to the upstream, got a datagram socket Down
Any later call after Down NotConnected none Down
start fails InvalidData the codec error Down
reply, seal, open, finish, seal_to or open_from fails InvalidData the codec error unchanged
Upstream write or read fails the I/O error’s kind the I/O error Down
Upstream write returns 0 WriteZero none Down
Upstream flush fails while connecting the I/O error’s kind the I/O error Down
Upstream flush fails after a packet (flush_packets) the I/O error’s kind the I/O error Down
Upstream flush or shutdown fails in poll_flush or poll_shutdown the I/O error’s kind the I/O error unchanged
Upstream closes during the handshake UnexpectedEof upstream closed during the handshake Down
Upstream closes inside a frame UnexpectedEof upstream closed inside a frame unchanged
Datagram receive after the flow ended UnexpectedEof none unchanged
Unparsed upstream bytes fill down InvalidData upstream frame larger than the client runtime's buffer unchanged
A packet cannot fit even into empty staging InvalidInput frame larger than the client runtime's buffer unchanged
Codec refuses a packet that fits its reserve InvalidInput codec refused a packet that fits its reserve unchanged
Step consumed more than it was given Other codec consumed more reply than it was given unchanged
Step made no progress Other codec handshake step made no progress unchanged
open or open_from returned an impossible frame Other codec opened an impossible frame unchanged
seal took 0 or more than it was offered Other codec sealed an impossible byte count unchanged

A codec error always has kind InvalidData, whatever kind the codec used inside, because codec_err wraps it with io::Error::new(io::ErrorKind::InvalidData, e). The message is the codec’s own: HTTP’s proxy responded with status 407 keeps its text (new_server_refuses_bad_credentials_with_407 in protocols/tests/pipeline/http.rs), and refused_handshake_fails_the_flow checks both the InvalidData kind and the method refused text. The inner error, with its original kind (ConnectionRefused for an HTTP status or a SOCKS request refusal, PermissionDenied for a SOCKS method or account refusal), is still reachable through io::Error::get_ref and a downcast to io::Error (err.get_ref().and_then(|e| e.downcast_ref::<io::Error>())).

The server runtime treats any error from poll_write, poll_flush, poll_shutdown, poll_read or poll_recv_from as fatal for that outbound: it drops the outbound and tells the core with OutboundError. A poll_send_to error is reported as SendFailed and the key stays live. Under ProxyServerRuntime a stream outbound whose call fails is dropped at once (fail_outbound), so a stream client runtime left in an “unchanged” state is never polled again. In the supervisor, a UDP flow’s client runtime is not the key’s outbound itself but a sub-link of a FanOutLink, which is described on Outbounds.

The codecs, the client runtime and the relay futures do not log. A client runtime’s errors reach the server core as events, and the core decides what its client sees; a relay future’s error goes to whoever awaits it.

The relay futures fail with the first read, write, flush or shutdown error of either side, or WriteZero when a write accepts 0 bytes; BidirectionalConnection does not finish the other direction first.

Cancellation. The client runtime owns no task and no channel, and holds nothing outside itself. Dropping it (because the server runtime closed the key, the connection finished, or the ProxyClientConnecting future was dropped before it resolved) drops the dial future or the upstream stream, and both buffers, at once. Dropping a gRPC upstream stream aborts its HTTP/2 driver task through AbortOnDropHandle. A dropped relay future drops both endpoints and both buffers. There is nothing to join.

Constant Where Value Meaning
BUF_SIZE ProxyClientRuntime const generic per protocol, below Cap of staging and of down. The largest upstream frame the codec opens must fit down at the cap.
HTTP_BUF supervisor/src/topology/outbound/mod.rs 16 * 1024 HTTP CONNECT client
SOCKS_BUF same 16 * 1024 SOCKS CONNECT client
TROJAN_BUF same 16 * 1024 Trojan client
VLESS_BUF same 16 * 1024 VLESS client
VMESS_BUF same 32 * 1024 VMess client
SS_BUF same, = SsStream::BUF_SIZE 20 * 1024 Shadowsocks (AEAD) client: the salt and one 0x3FFF-byte record with its overhead, with room to spare
SS2022_BUF same, = Ss2022Stream::BUF_SIZE MAX_RECORD_LEN = 65,569 Shadowsocks 2022 client: a record carrying MAX_PACKET_SIZE (0xFFFF) bytes plus RECORD_OVERHEAD, the largest frame a server may send
SSS_TCP_BUF same, = SssCore::TCP_BUF_SIZE (protocols/src/sss/core.rs) 16 * 1024 sss client for a TCP flow: its stream carries no frames of its own
SSS_UDP_BUF same, = SssCore::UDP_BUF_SIZE 66 * 1024 sss client for a UDP flow: a whole record of U = 65,535 bytes
HttpConnect::REQUEST_MAX protocols/src/http/codec.rs 1024 Largest CONNECT request start stages
MAX_HEAD protocols/src/http/protocol.rs 64 * 1024 Largest status head HttpConnect::reply waits for
BidirectionalConnection / UnidirectionalConnection BUF_SIZE concepts/src/relay.rs default 8192 per direction The SOCKS inbound uses RELAY_BUF = 16 * 1024

A client runtime starts with a 2 KiB read buffer, an empty staging buffer and the boxed dial future. Its buffers can grow to at most 2 * BUF_SIZE bytes: 32 KiB for HTTP, SOCKS, Trojan, VLESS and sss TCP flows, 40 KiB for Shadowsocks, 64 KiB for VMess, 131,138 bytes for Shadowsocks 2022, and 132 KiB for sss UDP flows.

The largest packet poll_send_to can accept is BUF_SIZE - STAGING_RESERVE, because an empty staging offers exactly BUF_SIZE bytes of room: 16,064 bytes for Trojan, 16,106 for VLESS, 32,384 for VMess and 67,308 for sss under the supervisor’s sizes. A larger packet fails with frame larger than the client runtime's buffer. Below that limit, SssDatagram drops a packet longer than its U (at most 65,535 bytes). In the other direction, a reply packet whose frame does not fit down fails the flow with upstream frame larger than the client runtime's buffer, and TrojanDatagram refuses a reply packet longer than MAX_LENGTH (8,192 bytes) with trojan: oversize payload.

The client runtime carries exactly one flow per upstream connection; there is no mux.cool client in the tree.

The concept tests in concepts/tests/client.rs drive the runtime with toy codecs (TinyCodec, TwoRoundCodec, Scripted, TinyUdpCodec) over tokio::io::duplex pipes, so each behaviour can be isolated. Scripted returns canned answers from every method to exercise the runtime’s guards, and read_with runs it under a 1 s timeout so a spin fails the test instead of hanging it. Run them with cargo test -p etemenanki-concepts --test client.

Test Behaviour pinned
codec_is_driven_without_any_io A codec is a plain state machine: start stages the header, seal takes at most one frame, open decrypts in place and returns NeedMore on a partial frame.
handshake_then_seal_and_open_over_the_wire The header precedes the first frame, long writes split into several frames, empty frames are skipped, End is EOF, and shutdown sends the close frame and then half-closes the wire.
small_reads_take_one_frame_across_several_calls One opened frame is handed out through 3-byte reads without being reopened.
truncated_upstream_frame_is_unexpected_eof Wire EOF with a partial frame in down is UnexpectedEof.
dial_failure_surfaces_on_first_use The dial error (ConnectionRefused) reaches the first write, and later calls get NotConnected.
backpressure_from_the_wire_reaches_the_writer With a 16-byte upstream pipe, a 200-byte write_all stays pending until the upstream reads.
plaintext_waits_for_every_handshake_reply A two-round handshake: nothing but the greeting before the first reply, no payload before the last one, a write-only caller does not deadlock, and data sent with the final reply is opened.
refused_handshake_fails_the_flow A codec error in reply surfaces as InvalidData carrying the codec’s message.
handshake_step_without_progress_is_rejected The no-progress check fires within the 1 s timeout instead of spinning.
zero_length_frame_is_rejected check_frame rejects consumed == 0.
end_marker_beyond_the_slice_is_rejected check_frame rejects an End that consumes more than the slice.
datagram_zero_length_frame_is_rejected The same guard on poll_recv_from.
datagram_codec_sends_and_receives_packets_over_the_stream seal_to frames a packet with its port, two packets in one wire write come back as two receives, and a close frame turns into UnexpectedEof.
a_packet_reaches_a_wire_that_holds_writes_until_flushed A packet sent over a BufWriter, which holds writes until it is flushed, reaches the far end within 1 s.
server_side::server_runtime_relays_through_a_client_runtime_in_one_task The full relay in one task, Connected only after the header has left through a 4-byte pipe, Shutdown becoming finish, and plaintext Traffic counts.
server_side::upstream_dial_failure_is_connect_failed_not_connected A refused dial reaches the server core as ConnectFailed (the client sees -, never +).
server_side::refused_upstream_handshake_is_connect_failed_not_connected Nothing is answered while the upstream handshake is pending, and a refused method becomes ConnectFailed.

The library tests of etemenanki-concepts (cargo test -p etemenanki-concepts --lib) include bidirectional_relays_both_ways_and_half_closes in concepts/src/relay.rs, which relays a 41-byte message through a 16-byte BidirectionalConnection, half-closes each side, and checks Relayed { a_to_b: 41, b_to_a: 5 }, and the buffer tests in concepts/src/buffer.rs:

Test Behaviour pinned
read_buffer_compacts_unparsed_tail_to_front compact moves the unparsed tail to offset 0 and frees the room before it.
read_buffer_saturation_means_frame_too_large is_saturated is true only when the unparsed region fills all N bytes.
write_buffer_slides_pending_when_full room() slides pending bytes to the front once the tail reaches N.
staging_refuses_over_reservation_without_partial_commit A reservation past the room stages nothing.
read_buffer_starts_small_and_doubles_up_to_n A read buffer starts at 2 KiB and make_room doubles it to 4 KiB and 8 KiB, keeping every byte.
make_room_moves_the_tail_and_grows_below_n make_room moves the tail and grows below N; at N it only moves.
compact_frees_room_in_any_buffer_short_of_saturated compact doubles when the move frees nothing, so a buffer short of saturated always gains room.
a_small_n_is_allocated_whole A buffer whose N is below 2 KiB starts at N.
grow_to_makes_room_for_a_whole_datagram_up_to_n grow_to grows to the asked length, never shrinks, and stops at N.
write_buffer_holds_nothing_until_a_stage A write buffer allocates nothing until the first stage, and its room counts against N.
staging_grows_to_n_and_no_further A first stage past 2 KiB gets its length, doubling stops at N, and a reservation past N is refused.

The real codecs run against the real server cores in protocols/tests/pipeline/*.rs, through the helper client in protocols/tests/support/pipeline.rs, which builds a ProxyClientRuntime over TcpConnector (plain TCP to an IP address). The HTTP, Trojan, VLESS and VMess tests instantiate the client with their server core’s BUF_SIZE, the SOCKS tests with 16 * 1024, and the Shadowsocks tests with SsStream::BUF_SIZE and Ss2022Stream::BUF_SIZE. Run them with cargo test -p etemenanki-protocols --test pipeline.

Test File Behaviour pinned
new_server_vs_new_client_tcp http.rs, socks.rs, trojan.rs, vless.rs, vmess.rs A stream codec’s echo round trip against the real server core (100,000 bytes for HTTP, SOCKS and VMess, 70,000 for Trojan and VLESS; VMess with AES-128-GCM and padding, then ChaCha20-Poly1305 without), then a shutdown and a clean EOF
new_server_vs_new_client_udp trojan.rs, vless.rs, vmess.rs Datagram codecs through DatagramLink, with the source reported as the echo’s address, including a 1,500-byte packet (4,000 bytes for VMess)
ss_new_server_vs_new_client_tcp shadowsocks.rs SsStream with AES-128-GCM, AES-256-GCM, ChaCha20-Poly1305 and XChaCha20-Poly1305, 70,000 bytes, shutdown and clean EOF
ss2022_new_server_vs_new_client_tcp shadowsocks.rs Ss2022Stream with 2022-blake3-aes-128-gcm, 2022-blake3-aes-256-gcm and 2022-blake3-chacha20-poly1305, shutdown and clean EOF
ss2022_multi_user_new_server_vs_new_client shadowsocks.rs Ss2022Stream with one identity PSK against a multi-user server
ss2022_client_takes_full_size_chunks_from_a_raw_server shadowsocks.rs A hand-built server answering with a 0xFFFF-byte first payload and a 0xFFFF-byte record; the client reads both
new_server_refuses_bad_credentials_with_407 http.rs An HTTP 407 fails the first write, and the message carries the status
new_server_refuses_an_unreachable_target_after_trying socks.rs A SOCKS refusal (rejects request) fails the first write, not a later read

Each codec also has unit tests under protocols/tests/unit/<protocol>/codec.rs that call it without I/O, the way codec_is_driven_without_any_io does. The codec file includes them as a #[cfg(test)] module, so they run with the library tests (cargo test -p etemenanki-protocols --lib). The shared framing layers have their own: protocols/tests/unit/ss_aead.rs for the Shadowsocks record stream, protocols/tests/unit/vmess/framing.rs for VMess chunks, and protocols/tests/unit/socks/protocol.rs for the SOCKS client messages.

Test File Behaviour pinned
connect_codec_awaits_a_200_then_passes_through unit/http/codec.rs The request line and Proxy-Authorization header, NeedMore before the blank line, bytes after the head left for open
connect_codec_refuses_a_non_200 unit/http/codec.rs A 407 is a ConnectionRefused error
anonymous_connect_takes_two_rounds unit/socks/codec.rs [5, 1, 0], the request naming a domain, bytes after the reply left for open
credentials_add_a_round_and_a_refusal_is_an_error unit/socks/codec.rs The RFC 1929 round, ConnectionRefused for a refused request, PermissionDenied for a refused account, an error for method 0xFF
stream_codec_sends_the_header_then_passes_bytes_through unit/trojan/codec.rs The header parses as a CONNECT request, payload passes verbatim, reply is an error
datagram_codec_frames_each_packet_with_its_peer unit/trojan/codec.rs The UDP header, one frame per packet with its peer, None with nothing staged when the room is short, NeedMore on a partial frame
stream_codec_consumes_the_response_header_as_an_empty_frame unit/vless/codec.rs The response header as an empty frame, a wrong version refused
datagram_codec_frames_to_the_fixed_target unit/vless/codec.rs to ignored, None when the room is short, the fixed target reported as the source
the_longest_vision_header_fits_the_declared_reserve unit/vless/codec.rs A Vision header to a 255-byte domain takes exactly STAGING_RESERVE, the same for both VLESS codecs
a_vision_datagram_codec_speaks_xudp unit/vless/codec.rs Under Vision: the mux header, a New then a Keep naming each peer, a packet over MAX_DATA_LEN dropped, and a Keep reply, a KeepAlive and an End opened
stream_codec_seals_the_header_and_chunks_and_opens_the_response unit/vmess/codec.rs A server opens the header and a MAX_PAYLOAD chunk; the response header, a data chunk and the terminator open as empty frame, frame and End
datagram_codec_refuses_a_packet_that_does_not_fit unit/vmess/codec.rs None with nothing staged for a packet that does not fit
request_is_a_salt_and_a_sealed_address_then_records unit/ss_legacy/codec.rs The salt, the address record, a payload record, and a MAX_PAYLOAD cap per seal
response_salt_is_an_empty_frame_and_records_open_in_place unit/ss_legacy/codec.rs The response salt as an empty frame, a zero-length record as an empty frame rather than the end
request_header_then_records_and_a_bound_response unit/ss_2022/codec.rs The request header with an empty first payload, the response opened frame by frame, a response bound to another salt refused
a_record_presented_again_is_never_decrypted_twice unit/ss_aead.rs The sealed length alone, then the length with part of the payload, both NeedMore without opening the length twice; then the whole record opens
a_declared_length_over_the_limit_is_refused unit/ss_aead.rs A declared length of 0x3FFF waits for its payload; 0x4000 against a 0x3FFF limit is InvalidData
a_refused_seal_stages_nothing_and_keeps_the_counter unit/ss_aead.rs A payload over the limit and a record without room both fail with nothing staged, and the next record still opens under the untouched counter
chunks_seal_into_staging_and_open_in_place unit/vmess/framing.rs Two chunks and the terminator staged with AES-128-GCM and ChaCha20-Poly1305, with and without global padding, open in place; a chunk without room for the worst case is refused
client_handshake_messages_round_trip_through_slices unit/socks/protocol.rs The method request, the RFC 1929 message, the CONNECT and UDP ASSOCIATE requests, and reply parsing, including None on a short reply
the_stream_codec_sends_its_header_then_plaintext unit/sss/codec.rs The header parses as a TCP request to the domain, and payload passes verbatim both ways
a_domain_the_wire_cannot_carry_fails_the_flow_at_its_start unit/sss/codec.rs A domain with a space fails start for both codecs, with nothing staged
the_datagram_codec_frames_records_both_ways unit/sss/codec.rs The UDP header, one record per packet with its peer, a packet above U dropped with nothing staged, and a reply opened with its source
a_reply_naming_a_domain_is_refused unit/sss/codec.rs A reply record whose source is a domain is an error

sss’s client codecs and SssConnector also run end to end in supervisor/tests/sss.rs: an_sss_outbound_carries_tcp_and_udp_to_an_sss_inbound sends TCP and UDP from one supervisor’s sss outbound to another’s sss inbound under transform chains.