HTTP proxy
Source files: 47 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/protocols/src/http/mod.rsEtemenanki/protocols/src/http/config.rsEtemenanki/protocols/src/http/protocol.rsEtemenanki/protocols/src/http/core.rsEtemenanki/protocols/src/http/codec.rsEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/core/harness.rsEtemenanki/protocols/src/flow.rsEtemenanki/protocols/src/sniff/mod.rsEtemenanki/protocols/src/sniff/collector.rsEtemenanki/protocols/src/helpers/address.rsEtemenanki/concepts/src/runtime.rsEtemenanki/concepts/src/buffer.rsEtemenanki/concepts/src/client.rsEtemenanki/protocols/tests/unit/http/core.rsEtemenanki/protocols/tests/unit/http/protocol.rsEtemenanki/protocols/tests/unit/http/codec.rsEtemenanki/protocols/tests/unit/helpers/address.rsEtemenanki/protocols/tests/pipeline/http.rsEtemenanki/protocols/tests/support/pipeline.rsEtemenanki/app/src/config.rsEtemenanki/app/src/lower.rsEtemenanki/app/tests/unit/lower.rsEtemenanki/app/tests/integration/e2e_unix.rsEtemenanki/app/tests/integration/e2e_xray_wrapped.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/users.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/guard.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/build/validate.rsEtemenanki/supervisor/src/topology/flow.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/topology/spec_plan/outbound.rsEtemenanki/supervisor/src/topology/outbound/mod.rsEtemenanki/supervisor/src/topology/outbound/proxy.rsEtemenanki/supervisor/src/system/listener.rsEtemenanki/supervisor/tests/hot_swap.rsEtemenanki/supervisor/tests/support/mod.rsEtemenanki/supervisor/tests/unit/validate.rskatana/src/lower/outbound.rskatana/src/lower/inbound.rskatana/src/api/newv2board.rs
The HTTP proxy lives in protocols/src/http/. It has two halves that share one set of wire helpers:
HttpCore, the server side, is aProxyCoreDecodethat serves one HTTP/1.x proxy request per connection: aCONNECTtunnel, or a plain request with an absolute URI that it rewrites and forwards to the origin.HttpConnect, the client side, is aProxyCoreEncodecodec that sends oneCONNECTto an upstream proxy, waits for a200, and then passes bytes through unchanged.
Around them, etemenanki-supervisor builds each HTTP inbound’s user table, serves every accepted byte stream with a runtime over HttpCore, and wraps HttpConnect in the proxy client of an http outbound. etemenanki-app lowers protocol = "http" inbounds and outbounds into the spec; katana lowers its http outbounds and a panel’s HTTP nodes, which it serves over TLS only.
This page is for contributors who change either half or the code that builds them. It assumes the server-core contract (events, effects, the held buffer and the staging reserve) from Server core, and the shared Timing, SniffPrefix and Passthrough helpers from Protocol crate foundations. The user-facing settings are on the HTTP proxy guide page.
Responsibilities
Section titled “Responsibilities”| Component | Does | Leaves to others |
|---|---|---|
protocol.rs |
Finds and parses request and response heads, holds the four fixed responses and the HOP_BY_HOP list, rewrites a forwarded request, builds a CONNECT request, checks Proxy-Authorization. |
All I/O. Every helper is a pure function over byte slices or parsed headers. |
HttpCore (core.rs) |
Parses the first request head, authenticates it, opens exactly one outbound flow, answers CONNECT, stages the fixed error responses, relays both directions verbatim afterwards. |
Dialing, routing, reading and writing sockets, and the watchdog for a client that never sends a byte (the runtime and the supervisor). |
HttpConnect (codec.rs) |
Stages one CONNECT request, parses the upstream’s status line, then seals and opens bytes verbatim. |
Dialing the upstream proxy and any TLS, WebSocket or gRPC around it (the client runtime and the outbound’s transport). UDP: HTTP proxies carry none. |
HttpServerConfig (config.rs) |
Holds the account map, the anonymous payload and allow_transparent. |
Parsing TOML and choosing the payload type. The supervisor builds it with Principal payloads. |
helpers/address.rs |
Converts between a host[:port] text authority and a TCP Destination (parse_authority, format_authority). |
Resolving: a domain stays a domain for the router. |
| etemenanki-supervisor | Builds HttpServerConfig<Principal> from the users an inbound admits, keeps it in a swappable cell, serves each byte stream with drive over HttpCore, and builds the http outbound. |
The wire protocol. |
| etemenanki-app | Lowers [[inbound]] and [[outbound]] tables with protocol = "http" into InboundProtocolSpec::Http and OutboundProtocolSpec::Http (app/src/lower.rs). |
Building or serving anything. |
| katana | Lowers [[outbound]] tables with protocol = "http" (src/lower/outbound.rs), and a panel’s HTTP node into InboundProtocolSpec::Http (src/lower/inbound.rs → lower_stream_protocol): over the node’s transport, always with TLS under it, with allow_transparent: false, and each panel user’s account their UUID as both name and password (credentials). |
Building the inbound and the outbound: the supervisor does it. Refusing an HTTP node in the clear: the node config helium and katana share gives an HTTP node no security to choose, and katana’s newV2board client refuses a UniProxy one without TLS with node requests kernel-unsupported feature: http without TLS (src/api/newv2board.rs → proxy). |
The helpers are a port of the HTTP proxy in Xray-core (proxy/http/server.go, client.go and common/protocol/http/headers.go); the sans-I/O core and codec around them are native to this crate. protocols/src/http/mod.rs declares the four modules and re-exports HttpConnect, HttpServerConfig and HttpCore.
Key types
Section titled “Key types”Configuration
Section titled “Configuration”protocols/src/http/config.rs → HttpServerConfig:
pub struct HttpServerConfig<T> { pub accounts: HashMap<CompactString, (CompactString, Arc<T>)>, pub anonymous: Arc<T>, pub allow_transparent: bool,}| Field | Meaning |
|---|---|
accounts |
username -> (password, payload), the map check_proxy_auth looks users up in. When it is empty, authenticate reads no header and every request gets the anonymous payload (see open mode). |
anonymous |
The payload every flow carries when accounts is empty. It is ignored otherwise. |
allow_transparent |
Accept a plain request whose target has no authority (GET /path) and take the destination from Host. The name matches Xray’s AllowTransparent. Default sets it to false. |
The three trait impls are written by hand:
Cloneso thatTneeds noClonebound: every payload sits behind anArc.Debugprints the account user names andallow_transparent, and leaves out passwords and payloads.DefaultrequiresT: Default, because it builds the anonymous payload withT::default(). It gives an empty account map, so a default config is in open mode.
The core receives the config as Arc<HttpServerConfig<T>>, and every connection built from the same table shares it. Where the supervisor’s table comes from is in From config to user table.
The server core
Section titled “The server core”protocols/src/http/core.rs → HttpCore:
pub struct HttpCore<T> { /* private */ }
impl<T> HttpCore<T> { pub const BUF_SIZE: usize = MAX_HEAD;
pub fn new(config: Arc<HttpServerConfig<T>>, sniff: bool, source: Option<IpAddr>) -> Self; pub fn is_established(&self) -> bool;}
impl<T: Send + Sync + 'static> ProxyCoreDecode for HttpCore<T> { type Key = Single; type Target = Flow<T>; type Error = io::Error; type TransportAddr = ();
const STAGING_RESERVE: usize = 256;
fn handle( &mut self, event: Event<'_, Self>, fx: &mut Effects<'_, Self>, ) -> Result<usize, io::Error>;
fn held(&self) -> &[u8];}Key = Single means one outbound per connection, and TransportAddr = () means the core runs only over a byte-stream transport (ProxyServerRuntime::new), never over datagrams. HttpCore keeps the trait’s default MAX_DATAGRAM (4096 bytes); it never sees a datagram, so the value is unused. The private fields show where each piece of state lives:
| Field | Type | Role |
|---|---|---|
config |
Arc<HttpServerConfig<T>> |
Accounts, the anonymous payload and allow_transparent. |
sniff |
bool |
Whether the inbound sniffs. The supervisor passes StreamInbound::sniff, which etemenanki-app lowers from the inbound’s sniffing key (default true). Only a CONNECT whose target is an IP literal sniffs (worth_sniffing). |
source |
Option<IpAddr> |
The client’s address, copied into every Flow for routing. The supervisor passes the peer IP its accept loop carried, or the client a PROXY protocol v2 header names when the inbound reads one, or, for a socket a relay on the same host handed over, the client the header sent with it names, or, over WebSocket on an inbound with real_ip, the client a proxy in the trusted networks names in the upgrade’s header, and None on a Unix listener. |
timing |
Timing |
The single deadline, armed per phase. is_established() reads it. |
prefix |
SniffPrefix |
The first tunnel bytes of a sniffing CONNECT, held until the flow opens. |
rewritten |
Vec<u8> |
The origin-form head of a forwarded plain request. |
state |
State<T> |
The state machine below. |
enum State<T> { Handshake, /// A CONNECT to an IP, already answered 200, collecting its prefix. Sniff(Flow<T>), Relay { relay: Passthrough<Single>, reply: bool, }, Done,}reply is true only for a CONNECT whose 200 is still owed: the core stages it on Connected. A sniffing CONNECT and a plain request both enter Relay with reply: false.
held() returns rewritten when it is non-empty and the sniff prefix otherwise. At most one of the two is ever filled on a connection, because a plain request never sniffs and a CONNECT never rewrites.
The private open_sniffed takes the parked flow out with std::mem::replace(&mut self.state, State::Done) and returns without an effect when the state was not Sniff. Its three callers (a Transport or TransportEof event in Sniff, and Expired::Sniff, which Timing reports only in the sniffing phase) all run in that state, so the guard is defensive: opening the flow moves Timing to Relay, and a later call would find no parked flow and do nothing.
The core relies on the server runtime’s event contract (concepts/src/runtime.rs, module docs): every event except Event::Deadline is delivered only when the staging buffer has STAGING_RESERVE bytes free, and an Outbound event only when it has the reserve plus the payload free. That is why Connected can always stage CONNECT_ESTABLISHED, why a refusal can always stage its response, and why Passthrough::on_outbound stages the whole outbound slice with no fallback. A stage that fails anyway returns staging_full() (staging room below the core's declared reserve), which marks a core or runtime bug. Event::Deadline is delivered whatever the room, and HttpCore stages nothing in that handler.
BUF_SIZE is the value the BUF_SIZE parameter of a ProxyServerRuntime over this core must take: MAX_HEAD, so that a whole request head fits the transport read buffer. That buffer is not allocated at MAX_HEAD up front: it starts at 2 KiB and doubles toward this cap each time an incomplete head fills it (concepts/src/buffer.rs → ReadBuffer). The supervisor instantiates drive::<{ HttpCore::<Principal>::BUF_SIZE }, _, _> in supervisor/src/serve.rs → serve_connection, and the pipeline tests use HttpCore::<()>::BUF_SIZE.
The core builds each flow with protocols/src/flow.rs → Flow::new(destination, user, source), which leaves sniffed at None; the sniffing path fills it before Effect::Open.
The client codec
Section titled “The client codec”protocols/src/http/codec.rs → HttpConnect:
pub struct HttpConnect { /* private: request: Vec<u8> */ }
impl HttpConnect { pub const REQUEST_MAX: usize = 1024;
pub fn new(dest: &Destination, auth: Option<(&str, &str)>) -> Self;}
impl ProxyCoreEncodeHandshake for HttpConnect { type Target = Destination; type Error = io::Error; const STAGING_RESERVE: usize = Self::REQUEST_MAX;
fn start(&mut self, out: &mut Staging<'_>) -> io::Result<Handshake>; fn reply(&mut self, wire: &mut [u8], _: &mut Staging<'_>) -> io::Result<Reply>; fn finish(&mut self, _: &mut Staging<'_>) -> io::Result<()>;}
impl ProxyCoreEncode for HttpConnect { fn seal(&mut self, plain: &[u8], out: &mut Staging<'_>) -> io::Result<usize>; fn open(&mut self, wire: &mut [u8]) -> io::Result<Opened>;}new builds the whole request up front with build_connect_request, so the codec’s only state is that byte vector, which start clears once staged. A Staging with less room than the codec needs fails with io::ErrorKind::Other and the text http: staging room below the declared reserve; the client runtime never offers less than the reserve, so that error marks a runtime bug.
The codec has no datagram side. The supervisor pairs it with NoUdp, which supervisor/src/topology/outbound/proxy.rs defines as NoCodec<Destination, io::Error>, in Outbound::Http(ProxyClient<HTTP_BUF, HttpConnect, NoUdp>); see The HTTP outbound.
Wire helpers
Section titled “Wire helpers”protocols/src/http/protocol.rs:
pub const CONNECT_ESTABLISHED: &[u8];pub const RESP_407: &[u8];pub const RESP_400: &[u8];pub const RESP_502: &[u8];pub const MAX_HEAD: usize = 64 * 1024;pub const HOP_BY_HOP: &[&str];
pub struct Header { pub name: String, pub value: Vec<u8>,}
pub struct RequestHead { pub method: String, pub target: String, pub headers: Vec<Header>,}
pub fn find_head_end(buf: &[u8]) -> Option<usize>;pub fn parse_request_head(head: &[u8]) -> io::Result<RequestHead>;pub fn parse_response_status(head: &[u8]) -> io::Result<u16>;pub fn build_connect_request(dest: &Destination, auth: Option<(&str, &str)>) -> Vec<u8>;pub fn header_value<'a>(headers: &'a [Header], name: &str) -> Option<&'a str>;pub fn parse_request_target(target: &str) -> (bool, Option<&str>, &str);pub fn build_forward_request( method: &str, origin_target: &str, host: &str, headers: &[Header],) -> Vec<u8>;pub fn check_proxy_auth<T>( headers: &[Header], accounts: &HashMap<CompactString, (CompactString, Arc<T>)>,) -> Option<(String, Arc<T>)>;Header and RequestHead own their bytes, so a parsed head outlives the buffer it came from. Header::value is raw bytes with no UTF-8 requirement. RequestHead::target is the target as written: authority-form for CONNECT, absolute or origin form otherwise.
| Helper | Behaviour |
|---|---|
find_head_end |
The offset immediately after the first \r\n\r\n, or None. It scans the whole slice on each call. |
parse_request_head |
httparse::Request over at most MAX_HEADERS (128, private) header slots, copied into owned Headers. A partial parse is an error (incomplete http request head), so the caller must pass a complete head. The texts missing http method and missing request target exist for a head without either, which a complete parse never produces. |
parse_response_status |
httparse::Response over the same header budget; returns only the status code. It does not reject a partial parse: it fails only on an httparse error (malformed proxy response: …) or when no status code was parsed (proxy response missing status code), which is what a head made only of blank lines gives. |
build_connect_request |
The request HttpConnect sends (see the CONNECT request). |
header_value |
The first header whose name matches case-insensitively, as UTF-8. A non-UTF-8 value reads as absent; later headers of the same name are not consulted. |
parse_request_target |
Splits a target into (is_https, authority, origin_form). The https:// and http:// prefixes match case-insensitively; the authority ends at the first /, ? or #; an absolute URI with nothing after the authority yields origin form /. Anything else, authority-form and * included, returns (false, None, target). |
build_forward_request |
Builds the origin-form head a plain request is forwarded as (see the forwarded head). |
check_proxy_auth |
Verifies Proxy-Authorization: Basic … against the account map (see authentication). |
There is no async head reader in the crate. The core finds a head in the server runtime’s read buffer and the codec in the client runtime’s; the async helpers that only tests used were removed (see Protocol crate foundations).
Authorities
Section titled “Authorities”protocols/src/helpers/address.rs holds the two text-authority helpers that HTTP shares with Hysteria 2:
pub fn format_authority(dest: &Destination) -> String;pub fn parse_authority(raw: &str, default_port: u16) -> io::Result<Destination>;format_authoritywriteshost:port, with an IPv6 literal in brackets and the port always present.parse_authoritytrims surrounding whitespace, splits host and port with the privatesplit_host_port(a port ofParseHostin Xray’sheaders.go), and returns aDestinationwithnetwork: DialNetwork::Tcp. A host that parses as an IP address becomesRemote::IpAddr; anything else becomesRemote::Domain, left unresolved for the router.
| Input | Result |
|---|---|
example.com |
Domain, default_port. |
example.com:8080, 192.0.2.10:8080 |
Exactly one colon: host and port. |
[2001:db8::1], [2001:db8::1]:443 |
Bracketed IPv6, with default_port when the port is absent. |
2001:db8::1 |
ambiguous authority (bracket IPv6 literals) |
example.com:, example.com:x, example.com:70000 |
invalid port |
:80 |
empty authority host |
[2001:db8::1 |
malformed IPv6 authority |
[2001:db8::1]x |
trailing data after IPv6 authority |
Every error is io::ErrorKind::InvalidData.
Wire format
Section titled “Wire format”Fixed responses
Section titled “Fixed responses”The server core never builds a response dynamically. It stages one of four constants from protocol.rs, all of which fit the 256-byte STAGING_RESERVE:
| Constant | Bytes | Sent when | Then |
|---|---|---|---|
CONNECT_ESTABLISHED |
39 | A CONNECT target connected, or at once for a sniffing CONNECT |
Relay (Sniff for a sniffing CONNECT) |
RESP_407 |
106 | Credentials are required and missing or wrong | ShutdownTransport, Finish |
RESP_400 |
72 | A plain request has no authority and allow_transparent is off |
ShutdownTransport, Finish |
RESP_502 |
47 | A CONNECT target failed to connect and the 200 is still owed |
ShutdownTransport, Finish |
HTTP/1.1 200 Connection established
HTTP/1.1 407 Proxy Authentication RequiredProxy-Authenticate: Basic realm="proxy"Connection: close
HTTP/1.1 400 Bad RequestProxy-Connection: closeConnection: close
HTTP/1.1 502 Bad GatewayConnection: closeEvery line ends in \r\n, and every response ends with an empty line and no body.
The CONNECT request the codec sends
Section titled “The CONNECT request the codec sends”build_connect_request formats the target with format_authority and writes:
| Line | Present | Content |
|---|---|---|
| Request line | always | CONNECT <host>:<port> HTTP/1.1 |
Host |
always | The same <host>:<port>. |
Proxy-Authorization |
when auth is Some |
Basic followed by standard base64 of user:pass. |
Proxy-Connection |
always | Keep-Alive |
| Terminator | always | An empty line. |
The request is 59 bytes plus twice the authority, plus 29 bytes and the base64 of user:pass when credentials are present. It must fit REQUEST_MAX (1024 bytes). Without credentials an authority of up to 482 bytes fits; with a 253-byte domain and a 5-digit port, user:pass may be up to 312 bytes. start checks the length before staging and otherwise fails with InvalidInput and the text http: CONNECT request exceeds the codec's reserve.
The forwarded head
Section titled “The forwarded head”For a plain request, build_forward_request produces this head, which the core keeps in rewritten:
| Part | Content |
|---|---|
| Request line | <method> <origin-form target> HTTP/1.1. The method is copied; the version is always HTTP/1.1. |
Host |
The authority from the absolute URI, or the client’s Host value when the URI had none (transparent mode). |
| Other headers | Every client header in its original order, with its name spelled as the client sent it, written as name: value, except those dropped below. Values are copied as raw bytes, with no UTF-8 requirement. |
Connection |
Always close, appended last. |
| Terminator | An empty line. |
Headers dropped from the client’s head:
- every
Hostheader (replaced by the line above); - every name in
HOP_BY_HOP:proxy-connection,proxy-authenticate,proxy-authorization,te,trailers,transfer-encoding,upgrade,connection,keep-alive(the list mirrorsRemoveHopByHopHeadersin Xray’sheaders.go, plusKeep-Alive); - every name listed in the values of the client’s
Connectionheaders.build_forward_requestcollects them in a first pass: eachConnectionvalue that is valid UTF-8 is split at commas, each token is trimmed, empty tokens are skipped, and the rest are lower-cased. AConnectionvalue that is not UTF-8 lists nothing, though the header itself is still dropped as hop-by-hop. The second pass compares each header name in lower case against the list.
The output vector starts with a capacity of 256 bytes and grows as needed.
Data flow
Section titled “Data flow”The state machine
Section titled “The state machine”stateDiagram-v2 [*] --> Handshake Handshake --> Handshake: head incomplete, consume 0 Handshake --> Relay: CONNECT, Open, reply owed Handshake --> Relay: plain request, Open and ForwardHeld Handshake --> Sniff: CONNECT to an IP with sniffing, 200 staged Sniff --> Relay: verdict, sniff deadline or client EOF Handshake --> Done: 407, 400 or client EOF Relay --> Done: ConnectFailed Done --> [*]
Timing runs alongside with its own phase: Handshake until the flow opens, Sniff while the prefix is collected, and Relay from the moment open calls Timing::enter(Phase::Relay), just before it pushes Effect::Open (http/core.rs → HttpCore::open). The order matters: a deadline queued after the Open would wait out the connect behind it, leaving the sniff window armed to end the flow as idle mid-connect (the doc comment of Timing::enter). is_established() reads Timing::is_established, which is true in Relay and Closing, so it turns true as open runs. Relay ends through the Passthrough half-close bookkeeping or the idle deadline, both of which push Effect::Finish without changing state. Phase::Closing is reached only when the idle deadline passes.
Events by state
Section titled “Events by state”handle calls timing.touch at the top of every Transport and Outbound event. In Handshake the first touch arms HANDSHAKE_TIMEOUT and later ones do nothing, so the limit runs from the first byte; in Sniff a touch does nothing; in Relay every touch re-arms RELAY_IDLE_TIMEOUT.
| Event | Handshake |
Sniff |
Relay |
Done |
|---|---|---|---|---|
Transport |
Parse a head (below). | SniffPrefix::push; open on any verdict but More (Verdict has three: Found, More, Exhausted); consume what was taken. |
Clear prefix and rewritten, then Passthrough::on_transport: one Forward of the whole slice. |
Consume nothing. |
Outbound |
Consume and drop. | Consume and drop. | Clear prefix and rewritten, then stage the whole slice verbatim. |
Consume and drop. |
TransportEof |
Done, Finish. |
open_sniffed, then on_transport_eof (Shutdown on the outbound). |
on_transport_eof. |
Finish. |
OutboundEof |
Nothing. | Nothing. | on_outbound_eof (ShutdownTransport). |
Nothing. |
Connected |
Nothing. | Nothing. | Stage CONNECT_ESTABLISHED if reply, then clear it. |
Nothing. |
ConnectFailed |
Log only. | Log only. | Log; stage RESP_502 if reply; Done; ShutdownTransport, Finish. |
Log only. |
OutboundError |
Log only. | Log only. | Log; on_outbound_gone (ShutdownTransport, Finish). |
Log only. |
Event::Deadline depends on the Timing phase rather than on state: Expired::Handshake returns handshake_timed_out(), Expired::Sniff calls open_sniffed, and Expired::Idle returns Ok(0) because Timing::expired has already pushed Finish. The datagram events (Datagram, SendFailed, TransportDatagram, TransportSendFailed) are ignored.
Parsing the head
Section titled “Parsing the head”On Event::Transport in Handshake, on_transport:
- Calls
find_head_endon the whole unparsed region. With no terminator it returnsOk(0), so the runtime keeps the bytes and reads more, unless the region has reachedMAX_HEAD, which is an error. - Parses exactly
data[..end]withparse_request_head. Bytes afterend(a request body, or tunnel bytes a client sent early) stay in the runtime’s buffer and come back as the nextTransportevent. - Calls
on_head, which authenticates first and then branches on the method, compared case-insensitively withCONNECT. - Returns
Ok(end), consuming only the head.
CONNECT
Section titled “CONNECT”The target is authority-form and goes straight to parse_authority(&head.target, 443); the Host header is not consulted. The core builds Flow::new(dest, user, source), and what happens next depends on whether it has to sniff.
The core opens the flow at once and owes the 200 until the outbound connects:
sequenceDiagram
participant C as Client
participant R as Server runtime
participant H as HttpCore
participant O as Outbound
C->>R: CONNECT example.com:443 HTTP/1.1 and headers
R->>H: Event Transport, whole head
H->>R: SetDeadline RELAY_IDLE_TIMEOUT, Effect Open, reply owed
R->>O: connect through the plane
alt connected
O-->>R: connected
R->>H: Event Connected
H->>R: stage CONNECT_ESTABLISHED
R-->>C: HTTP/1.1 200 Connection established
C->>R: tunnel bytes
R->>H: Event Transport
H->>R: Effect Forward, whole slice
R->>O: bytes, verbatim
else connect failed
R->>H: Event ConnectFailed
H->>R: stage RESP_502, ShutdownTransport, Finish
R-->>C: HTTP/1.1 502 Bad Gateway
endThrough a proxy outbound, Connected means the upstream handshake is done as well: ProxyClientConnecting in concepts/src/client.rs resolves only after poll_connected has dialed, run the codec’s handshake and flushed what it staged. A refused upstream is therefore a ConnectFailed, and the client gets a 502.
A client sends nothing after CONNECT until it sees the 200, so there would be nothing to sniff. The core therefore stages CONNECT_ESTABLISHED in the same call that parsed the head, parks the flow in State::Sniff and calls Timing::enter(Phase::Sniff), which arms SNIFF_TIMEOUT:
sequenceDiagram participant C as Client participant R as Server runtime participant H as HttpCore participant O as Outbound C->>R: CONNECT 192.0.2.10:443 HTTP/1.1 R->>H: Event Transport, whole head H->>R: stage CONNECT_ESTABLISHED, deadline SNIFF_TIMEOUT R-->>C: HTTP/1.1 200 Connection established C->>R: TLS ClientHello R->>H: Event Transport H->>H: SniffPrefix push, domain found H->>R: SetDeadline RELAY_IDLE_TIMEOUT, Effect Open with sniffed domain, ForwardHeld of the prefix R->>O: connect, then the held prefix R->>H: Event Connected Note over H: reply is false, nothing staged
The flow also opens when the prefix reaches SNIFF_LIMIT (Verdict::Exhausted), when the sniff deadline passes (Expired::Sniff), or when the client half-closes during the window (TransportEof opens the flow and then half-closes it). In every case open_sniffed copies SniffPrefix::result() into Flow::sniffed, and open pushes Effect::ForwardHeld for the held prefix when it is non-empty. A server-speaks-first protocol sends nothing, so it opens at the deadline with an empty prefix and no ForwardHeld. How the sniffers recover a domain, and how a sniffed name reaches the route, is on Sniffing.
Once in Relay, the core is a Passthrough<Single>: every transport slice becomes one Effect::Forward of the whole slice, and every outbound slice is staged verbatim toward the client.
Plain forwarding
Section titled “Plain forwarding”For any other method, on_head resolves the destination and the forwarded Host separately:
flowchart TB
target["parse_request_target(head.target)"]
abs{"authority present and non-empty?"}
transparent{"allow_transparent?"}
r400["stage RESP_400, close"]
host{"Host header non-empty?"}
fromHost["destination from Host"]
fromUri["destination from URI authority"]
empty["error: missing target host"]
open["parse_authority, build_forward_request, open"]
target --> abs
abs -- yes --> host
abs -- no --> transparent
transparent -- no --> r400
transparent -- yes --> host
host -- yes --> fromHost --> open
host -- no --> fromUri
fromUri -- "authority present" --> open
fromUri -- "no authority" --> empty
The rules, precisely:
- Authority. An empty authority (
http:///path) counts as none. - Destination. The first
Hostheader wins over the URI authority when it is non-empty.header_valuereads a firstHostwhose value is not UTF-8 as absent, so the URI authority is used then. The default port is 443 for anhttps://target and 80 otherwise. - Forwarded
Host. The URI authority wins over theHostheader. In transparent mode there is no authority, so the client’sHostis forwarded. - Forwarded target. The origin-form part of the URI (
/path?q=1), or the target unchanged in transparent mode.
The core stores the rewritten head in rewritten, builds the flow with sniffed: None, and calls open(flow, false, fx), which enters Phase::Relay (pushing SetDeadline(RELAY_IDLE_TIMEOUT)) and then pushes Effect::Open followed by Effect::ForwardHeld { range: 0..held }. The runtime applies the held forward once the outbound is connected, so the new head reaches the origin before any body byte:
sequenceDiagram participant C as Client participant R as Server runtime participant H as HttpCore participant O as Origin C->>R: GET http://example.com/path?q=1 HTTP/1.1, headers, body R->>H: Event Transport H->>H: build_forward_request into rewritten H->>R: SetDeadline RELAY_IDLE_TIMEOUT, Effect Open, ForwardHeld of rewritten, consumed = head only R->>O: connect, then GET /path?q=1 HTTP/1.1 ... Connection close R->>H: Event Transport, body bytes H->>H: clear rewritten H->>R: Effect Forward, whole slice R->>O: body, verbatim O-->>R: response, then EOF R->>H: Event Outbound, then OutboundEof H->>R: stage response, ShutdownTransport R-->>C: HTTP/1.1 200 OK ...
The core parses one head per connection. After it, everything the client sends is relayed to the same outbound without inspection, and the Connection: close the rewrite appends asks the origin to close after its response. A client that wants a second request has to open a new connection. The core does not stage a 200 for a plain request: the origin’s own response is the reply, relayed verbatim. A plain request whose outbound fails to connect gets no response at all, because reply is false.
Authentication
Section titled “Authentication”authenticate runs before the method branch, so it guards CONNECT and plain requests alike:
- With an empty
accountsmap, every request is accepted as username""with theanonymouspayload. - Otherwise
check_proxy_authmust returnSome. It reads the firstProxy-Authorizationheader throughheader_value, strips aBasicorbasicprefix (any other capitalisation of the scheme is refused), trims the rest, decodes standard base64, requires UTF-8, splits the decoded text at the first:into user name and password, looks up the user name and requires the stored password to be equal. Any failure along that chain yieldsNone.
A None sets State::Done and calls refuse(RESP_407, fx). On success the flow carries a NetworkUser whose authorization is UserAuthorization::UsernamePassword { username, password }, where password is always empty: the credential stops at the core. user_data is the payload from the account map, which in the supervisor is the user’s Principal. For plain requests the Proxy-Authorization header is also removed from the forwarded head by HOP_BY_HOP.
Open mode
Section titled “Open mode”An HTTP inbound without a user set (InboundSpec::users: None) runs in open mode. The layers, from the front end down to the core:
| Layer | Where it shows | Code |
|---|---|---|
| etemenanki-app | An inbound whose accounts list is empty lowers with users: None and gets no user set. |
app/src/lower.rs → lower_inbound |
| Supervisor spec | InboundSpec::users: None. The field’s documentation names “HTTP without accounts” among the protocols’ open or shared modes. |
supervisor/src/topology/spec_plan/inbound.rs |
| Supervisor table | For that inbound user_table builds an HttpServerConfig with no accounts. anonymous is always Principal::anonymous(): no user key, an empty label, which supervisor/src/topology/flow.rs documents as “Nobody in particular: an open or shared-credential inbound”. |
build/inbound.rs → user_table |
| Core | With no accounts, authenticate returns user name "" and config.anonymous without reading any header. |
core.rs → HttpCore::authenticate |
The app’s test a_server_config_lowers_to_its_spec pins the first row (“No accounts is HTTP’s open mode”). In open mode no Proxy-Authorization header is read and no request is answered with 407; a plain request’s Proxy-Authorization is still dropped from the forwarded head.
The client handshake
Section titled “The client handshake”sequenceDiagram
participant A as Client runtime
participant X as HttpConnect
participant U as Upstream proxy
A->>X: start
X->>A: stage CONNECT request, Handshake AwaitReply
A->>U: CONNECT example.com:443 HTTP/1.1
U-->>A: HTTP/1.1 200 ...
A->>X: reply with the unparsed bytes
alt no terminator yet
X->>A: Reply NeedMore
else status 200
X->>A: Reply Step, consumed = head, next Done
else any other status
X->>A: error ConnectionRefused
end
A->>X: seal and open, verbatim
| Method | Behaviour |
|---|---|
start |
Checks the prebuilt request against REQUEST_MAX, stages it, clears the vector and returns Handshake::AwaitReply. |
reply |
Reply::NeedMore until find_head_end finds a terminator; an unterminated region of MAX_HEAD bytes is an error. Then parse_response_status on the head: exactly 200 gives Reply::Step { consumed: end, next: Handshake::Done }; any other code, including other 2xx codes, is refused with ConnectionRefused and the text proxy responded with status <code>. reply never stages. |
seal |
Stages the whole plaintext slice it is given and returns its length. The client runtime offers at most its staging room minus STAGING_RESERVE, so with HTTP_BUF one poll_write seals at most 15,360 bytes. |
open |
Opened::NeedMore for an empty slice, otherwise the whole wire slice as one frame (consumed and plain cover all of it). It never returns Opened::End, so the tunnel ends only at the wire’s EOF. |
finish |
Stages nothing: the wire’s own EOF carries the half-close. |
consumed in reply is the head length only. Bytes the upstream sent after the head stay in the client runtime’s read buffer and become the first tunnel bytes. The client runtime wraps every codec error as InvalidData (codec_err) but keeps its text, which is how the pipeline test sees 407 in the error from the plaintext side.
The plaintext side of the client runtime (concepts/src/client.rs) stays Pending until the dial and this handshake are done. poll_shutdown stages finish (nothing, for this codec), then drains the staging buffer, flushes and shuts down the wire.
In the supervisor and the front ends
Section titled “In the supervisor and the front ends”From config to user table
Section titled “From config to user table”In etemenanki-app, an HTTP inbound’s [inbound.settings] deserialise into app/src/config.rs → HttpInboundSettings, which is #[serde(deny_unknown_fields, default)]:
| Key | Type | Default | Meaning |
|---|---|---|---|
accounts |
array of Account { user, pass } (deny_unknown_fields) |
empty | Basic-auth accounts. |
allow_transparent |
bool | false |
Copied into InboundProtocolSpec::Http. |
Account has no serde defaults, so user and pass are both required keys: a missing one fails deserialisation with an invalid settings: missing field … error before any lowering check runs.
app/src/lower.rs → lower_inbound lowers the "http" arm:
resolve_listenreadslistenandport. Alistenstarting with/is a Unix socket path and must not carry aport; one starting with@(an abstract socket) is refused; anything else is an IP listener on that host,127.0.0.1whenlistenis absent, and needs aport.usersisNonewhenaccountsis empty. Otherwiseaccount_setbuilds aUserSettagged with the inbound’s tag, whose keys areUserName::Username(user)and whose credentials hold anAccount; the inbound’susersis thenSome(<inbound tag>), and the set is returned beside the spec.- The protocol is
InboundProtocolSpec::Http { allow_transparent, transport }, whereinbound_transport(cfg, &listen, "http")resolves the[inbound.stream]shape. On a Unix socket a stream block is refused and the shape is plain TCP. On an IP listener whose shape layers TLS, it requirestls.cert_fileandtls.key_fileand reads both files into the spec’s PEM bytes. - The bind is
BindSpec::TcporBindSpec::Unix(tcp_bind). Unix listeners exist only on Unix platforms: elsewhere the supervisor’s validation refuses a Unix bind withunix sockets are not served on <os>(supervisor/src/build/validate.rs→validate_inbound).
Besides the listener and stream errors above, the lowering refuses an empty or repeated user name (account_set) and an unknown settings key (inbound_settings). etemenanki-app --test prints, for example:
configuration invalid: inbound http-in: accounts[0] has no userconfiguration invalid: inbound http-in: accounts[0] and accounts[1] are both named "alice"configuration invalid: inbound http-in: invalid settings: unknown field `transparent`, expected `accounts` or `allow_transparent`configuration invalid: inbound http-in: port is requiredconfiguration invalid: inbound http-in: a unix socket listen has no port; remove portconfiguration invalid: inbound http-in: abstract unix sockets are not supported; use a filesystem pathconfiguration invalid: inbound http-in: tls stream needs tls.cert_fileconfiguration invalid: inbound http-in: protocol http over a unix socket does not support stream network "ws"In the supervisor, supervisor/src/build/users.rs → credential_kind maps InboundProtocolSpec::Http to CredentialKind::Account: an HTTP inbound admits users by their account credential. supervisor/src/build/inbound.rs → user_table then builds:
InboundProtocolSpec::Http { allow_transparent, ..} => UserTable::Http(HttpServerConfig { accounts: accounts() .map(|(a, p)| (a.user.clone(), (pass(a), p.clone()))) .collect(), anonymous: Principal::anonymous(), allow_transparent: *allow_transparent,}),accounts() is a local closure that yields each admitted user’s account and principal, and pass copies the account’s password out of its Secret into a CompactString. Each entry is keyed by the account’s user name and carries the password and the user’s Arc<Principal>.
build_handler puts the table in StreamProtocol::Http(ArcSwap<HttpServerConfig<Principal>>) inside an Arc<StreamInbound { tag, protocol, transport, sniff, proxy_protocol, real_ip }>. The transport comes from build_transport, which builds TLS with TlsServerConfig::from_pem from the PEM bytes the spec carries:
StreamShape |
InboundTransport |
|---|---|
Tcp |
Plain TCP. |
Tls |
TLS with no ALPN. Without TLS material it fails with InvalidInput and missing tls. |
Ws |
WebSocket on the shape’s path and optional host, reading the inbound’s real-IP header when it has one, with TLS offering http/1.1 when the shape layers it. |
Grpc |
gRPC on the shape’s service, with TLS offering h2 when the shape layers it. Each HTTP/2 stream of a gRPC transport is a session of its own. |
A Unix listener always gets plain TCP. Transports: TCP and TLS and Transports: WebSocket and gRPC describe the transports; the first also lists the errors from_pem returns.
A change to the users of the inbound’s user set does not rebuild the handler. The supervisor rebuilds the table with user_table. While it stages the apply, off the runtime (supervisor/src/supervisor.rs → stage), it takes the listener’s supervisor/src/system/listener.rs → Listener::user_target, and UserTarget::prepare checks with UserTable::fits that the listener’s current handler is an HTTP one; an HTTP table needs no further preparation (UserTable::prepare_for leaves it as it is). At the commit, Listener::store_users stores the table into that handler’s cell through UserTable::store_into (ArcSwap::store). What a user change does to sessions that are already open is on Users, principals and sessions; how handlers and tables are swapped is on Listeners and the serve loop.
Serving one byte stream
Section titled “Serving one byte stream”supervisor/src/serve.rs → serve_connection serves every byte stream an HTTP inbound’s transport yields:
StreamProtocol::Http(config) => { drive::<{ HttpCore::<Principal>::BUF_SIZE }, _, _>( stream, || HttpCore::new(config.load_full(), sniff, source), connector, handshake, report, ) .await}drivecalls the closure once to build the core; its doc comment says why it takes a closure and not a core: anasync fnkeeps its arguments for as long as its future lives, so a core passed in would be held twice.HttpCore::new(config.load_full(), …)reads the handler’s table cell when the core is built.sniffisStreamInbound::sniff;sourceisAppConnector::source(): the peer address the listener captured, or the client a PROXY protocol v2 header names when the inbound reads one, or, for a socket a relay on the same host handed over, the client the header sent with it names, or, over WebSocket on an inbound withreal_ip, the client a proxy in the trusted networks names in the upgrade’s header, orNoneon a Unix listener. etemenanki-app and the mobile library always leaveproxy_protocol,real_ipand the handoff socket off for an HTTP inbound. katana turns them on for its HTTP nodes as for its other stream nodes:proxy_protocolon every TCP bind, a handoff socket when[node.controller] handoff_diris set, andreal_ipfromreal_ip_headerandreal_ip_fromwhen the node’s transport is WebSocket.report(supervisor/src/guard.rs→Report) is where the handshake ends.drivecallsReport::succeededwith the core’suser_hint(alwaysNonehere) once the core is established, andReport::failedfor a core error of kindPermissionDeniedbefore that.- The
Establishedtrait, implemented forHttpCore<Principal>by theestablished!macro with the defaultuser_hint, letsdriveaskis_established().
drive builds ProxyServerRuntime::<BUF, Core, _, _>::new(stream, make_core(), connector).showing_progress(), a stream of Traffic deltas. While the core is not established it wraps each step in tokio::time::timeout(HANDSHAKE_TIMEOUT, runtime.next()); after that it runs the runtime to its end. Each delta’s transport_rx and transport_tx are added to the session’s wire counter; Per-user usage accounting describes how wire bytes are accounted. A runtime error becomes io::Error::other(e.to_string()). A refusal with 407 or 400 ends the runtime without an error, so drive returns Ok(()).
The Flow the core opens goes to the supervisor’s AppConnector (supervisor/src/connector.rs), whose connect:
- Binds the session to the flow’s principal with
Session::admit. An error returns before any routing and reaches the core asEvent::ConnectFailed: the session is closed, its principal was revoked, or the user’s sessions already come from as many IPs as their device limit (the user's sessions already come from as many IPs as their device limit,PermissionDenied). The last two also cancel the session’s token (supervisor/src/entity/session.rs). - Loads the plane once for this flow, so a route change reaches the next flow while this one keeps the target it was opened on, and routes the flow. A front end that wants live flows moved after a route change calls
Supervisor::close_rerouted, which closes every flow the current routing would send to another outbound. - Resolves a balancer to its member now, so the flow is filed under the outbound that carries it.
- Opens the flow with that outbound’s
connect_streamand wraps the stream withTracker::meter_stream, filed under aFlowMetaof the session id, the inbound tag, the source, the target’s id, the matched rule and the plane’s epoch.Target::close_if_drainedthen kills the flow if a drain closed that outbound version while it was dialing.
An error from the outbound’s dial also reaches the core as Event::ConnectFailed. The plane: routing each flow describes routing.
The HTTP outbound
Section titled “The HTTP outbound”Both front ends lower an http outbound into OutboundProtocolSpec::Http { upstream: ProxyUpstream, account: Option<Account> } (supervisor/src/topology/spec_plan/outbound.rs):
app/src/lower.rs → lower_outbound, arm "http":
proxy_upstreamtakesserverandportas a TCPDestinationand resolves[outbound.stream]into the upstream’s transport, so an upstream HTTPS proxy is anhttpoutbound on a TLS transport.[outbound.settings]deserialise intoProxyOutboundSettings { user, pass }(deny_unknown_fields, default), shared with SOCKS.proxy_accountbuilds the optionalAccountfromuserandpass.
A settings key the struct does not have is refused by outbound_settings:
configuration invalid: outbound up: invalid settings: unknown field `username`, expected `user` or `pass`src/lower/outbound.rs → lower_outbound works in this order:
- It lower-cases
protocol. parse_address_familyreadsaddress_family(auto when unset); an unknown value fails first, asconfiguration error: node 1: outbound up invalid address_family "ipv5".parse_serverrefuses an emptyserveror a zeroport, and otherwise builds a TCPDestinationwhose remote isRemote::IpAddrwhenserverparses as an IP andRemote::Domainotherwise. Forserver = ""andport = 3128,katana --testprintsconfiguration error: node 1: outbound needs a non-empty server and non-zero port (got "":3128)."http"lowers toOutboundProtocolSpec::Httpwith an upstream on plain TCP (StreamShape::Tcp, no TLS) and thataddress_family;accountbuilds the optionalAccountfromusernameandpassword. A protocol no arm matches fails asconfiguration error: node 1: unknown outbound protocol "gopher".
supervisor/src/build/outbound.rs → build_outbound turns the spec into Outbound::Http(ProxyClient::new(make, transport, server)):
| Argument | Value |
|---|---|
make |
A boxed closure that owns the user name and password as CompactStrings and returns link::Outbound::Stream(HttpConnect::new(&flow.destination, auth)) for every flow, so each flow gets its own codec and its own CONNECT. |
transport |
A TransportConnector for the upstream’s stream shape, built by the private transport_connector from Dialer::new(socket) over the supervisor’s SocketOptions, the resolver’s servers (dns.servers) for resolving the upstream’s name, and the upstream transport’s address_family. |
server |
tcp(upstream): the upstream’s destination with network forced to DialNetwork::Tcp. |
transport_connector builds client TLS with ClientConfig::with_verify_mode(server_name, verify, alpn), where the ALPN is none for Tls, http/1.1 for Ws and h2 for Grpc. A Reality shape is refused by validation for every protocol but VLESS (reality is for vless only). A shape that needs a piece the spec lacks fails with InvalidInput: missing tls, missing ws host or missing grpc authority. The front ends fill those pieces in and validation checks them first (Validation and apply errors), so these errors are backstops.
supervisor/src/topology/outbound/proxy.rs holds the pieces the handler is made of:
| Item | Definition |
|---|---|
ProxyClient<const BUF, S, D, C = TransportConnector> |
A parking_lot::Mutex around one ProxyClientConnector<BUF, Make<S, D>, C, Destination>. C is the connector the upstream is dialed through: a TransportConnector for http, or one that wraps it (sss’s SssConnector). connect holds the lock only while it builds the dial future. |
Make<S, D> |
Box<dyn FnMut(Flow) -> link::Outbound<S, D> + Send>: picks the stream or datagram codec for a flow. |
NoUdp |
NoCodec<Destination, io::Error>, the datagram codec of a protocol that carries none. |
proxy_stream |
Turns the finished dial into OutboundStream::Proxy (a boxed runtime). A datagram result fails with a TCP flow was dialed as datagrams, which cannot happen for http, whose make always returns a stream. |
supervisor/src/topology/outbound/mod.rs defines the handler type Outbound::Http(ProxyClient<HTTP_BUF, HttpConnect, NoUdp>) with HTTP_BUF = 16 * 1024; its doc comment sizes each client runtime buffer as “the largest wire frame each protocol opens, plus what its codec reserves”. connect_stream calls ProxyClient::connect and passes the result through proxy_stream. connect_datagram fails at once with Unsupported and the text http carries no datagrams. The rest of the outbound machinery is on Outbounds, UDP fan-out and balancers, and how katana lowers its [[outbound]] tables on Lowering inbounds and outbounds.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
| Nothing is consumed until a whole head has arrived. | on_transport returns Ok(0) while find_head_end is None. |
connect_to_a_domain_answers_200_once_connected (a 20-byte prefix consumes 0 and only arms the deadline), head_end_is_found_only_once_the_blank_line_arrives |
| A request head always fits the read buffer, and a larger one fails in the core rather than stalling. | BUF_SIZE = MAX_HEAD; on_transport errors when the region reaches MAX_HEAD with no terminator, before the runtime’s own FrameTooLarge check (protocol frame exceeds the read buffer). |
an_oversized_head_is_refused |
| Only the head is consumed; a body or early tunnel bytes stay for the relay. | on_transport returns end, not data.len(). |
plain_request_is_rewritten_into_the_held_buffer (consumed == wire.len() - 4) |
| No flow opens and no byte reaches an outbound before authentication. | on_head calls authenticate first; failure goes to refuse(RESP_407, …). |
missing_or_wrong_credentials_are_a_407, new_server_refuses_bad_credentials_with_407 |
| The authenticated flow never carries the password. | authenticate puts CompactString::default() in password. |
Not tested directly: missing_or_wrong_credentials_are_a_407 checks only the user name on Open. |
A CONNECT gets its 200 only after the target connected, unless it sniffs. |
State::Relay { reply: true }; Event::Connected stages CONNECT_ESTABLISHED and clears the flag. |
connect_to_a_domain_answers_200_once_connected |
A CONNECT is answered exactly once. |
The sniffing path stages the 200 in on_head and opens with reply: false; Connected then stages nothing. |
connect_to_an_ip_with_sniffing_replies_early_and_holds_the_prefix (“no second 200”), new_server_connect_to_an_ip_answers_before_the_first_bytes, new_server_vs_new_client_tcp (a second 200 would corrupt the echoed bytes) |
A failed CONNECT whose 200 is owed is answered 502. |
Event::ConnectFailed stages RESP_502 when reply is set, then ShutdownTransport and Finish. |
connect_refused_answers_502_and_closes |
| The rewritten head reaches the origin before the body. | open pushes ForwardHeld right after Open; the runtime delivers no byte event until the held effect is applied. |
plain_request_is_rewritten_into_the_held_buffer, new_server_forwards_a_plain_request |
| The held buffer is never cleared under a queued held range. | rewritten and prefix are cleared only at the start of a Relay byte event (Transport or Outbound), which the runtime’s pin rule delays until held effects are applied. |
plain_request_is_rewritten_into_the_held_buffer checks that held() is empty after the body; the pin rule itself belongs to the server runtime. |
| The rewritten head carries no proxy credentials and no hop-by-hop headers. | build_forward_request skips HOP_BY_HOP names, names listed in Connection, and Host. |
forward_request_strips_hop_by_hop, plain_request_is_rewritten_into_the_held_buffer |
| A plain request without an absolute URI is refused unless transparent mode is on. | on_head checks authority.is_none() && !allow_transparent. |
origin_form_without_transparent_is_a_400 |
| Every fixed response fits the staging reserve. | STAGING_RESERVE = 256; the largest response (RESP_407) is 106 bytes. A shortfall is a core bug and surfaces as staging_full(). |
The constants’ lengths. connect_to_a_domain_answers_200_once_connected, connect_refused_answers_502_and_closes, origin_form_without_transparent_is_a_400 and missing_or_wrong_credentials_are_a_407 stage all four, but through CoreHarness, which offers HARNESS_STAGING (64 KiB) of room, so none of them measures the 256-byte bound. |
The core never stages while handling Event::Deadline, the one event delivered without the reserve. |
The Expired::Handshake arm returns an error, Expired::Sniff only pushes SetDeadline(RELAY_IDLE_TIMEOUT), Open and ForwardHeld, and Expired::Idle returns Ok(0). |
Not tested directly. |
| The codec’s request never exceeds its declared reserve. | STAGING_RESERVE = REQUEST_MAX; start checks the length first. |
No test builds an oversized request. |
| The client runtime can always seal. | ProxyClientRuntime::new asserts BUF_SIZE > Codec::STAGING_RESERVE; HTTP_BUF (16 KiB) exceeds REQUEST_MAX (1 KiB). |
Checked when each flow’s ProxyClientRuntime is built (ProxyClientConnector::connect); not tested directly. |
Only a 200 opens a client tunnel, and the tail after it is preserved. |
reply matches 200 and returns consumed: end. |
connect_codec_refuses_a_non_200, connect_codec_awaits_a_200_then_passes_through |
| An HTTP outbound never opens a datagram flow. | Outbound::connect_datagram answers Outbound::Http(_) with no_udp("http"). |
Not tested directly. |
| An inbound without accounts lowers to the open mode. | lower_inbound sets users: None for an empty accounts. |
a_server_config_lowers_to_its_spec |
Failure paths and cancellation
Section titled “Failure paths and cancellation”Server side
Section titled “Server side”Every error that handle returns ends the runtime without a response to the client. The fixed responses cover the cases where the core has something useful to say.
| Situation | Answer | Mechanism |
|---|---|---|
Head reaches MAX_HEAD with no terminator |
None | InvalidData, http head exceeds maximum size |
| Malformed head | None | InvalidData, malformed http request: <httparse error>, for example invalid token or invalid HTTP version |
| More than 128 headers | None | InvalidData, malformed http request: too many headers |
Head made only of blank lines (for example a stray \r\n\r\n before the request) |
None | InvalidData, incomplete http request head (httparse skips leading empty lines and reports a partial parse) |
| Unparsable authority | None | parse_authority: invalid port, empty authority host, ambiguous authority (bracket IPv6 literals), malformed IPv6 authority, trailing data after IPv6 authority |
| Missing or wrong credentials | 407 |
refuse(RESP_407, …), State::Done |
No authority, allow_transparent off |
400 |
refuse(RESP_400, …), State::Done |
Transparent mode, no Host and no authority |
None | InvalidData, missing target host |
CONNECT target fails to connect, 200 owed |
502 |
Event::ConnectFailed stages RESP_502, then ShutdownTransport and Finish |
Sniffing CONNECT or plain request fails to connect |
None | Event::ConnectFailed with reply: false: ShutdownTransport, Finish |
| Outbound errors during the relay | None | Passthrough::on_outbound_gone: ShutdownTransport, Finish, after the bytes already staged |
| Client closes before a complete head | None | TransportEof in Handshake pushes Finish |
| Client stalls after starting its head | None | Timing armed HANDSHAKE_TIMEOUT at the first byte; Expired::Handshake returns handshake_timed_out(): TimedOut, client did not complete its request in time |
No bytes either way for RELAY_IDLE_TIMEOUT |
None | Timing::expired pushes Finish (Expired::Idle) |
| Staging room below the reserve | None | io::ErrorKind::Other, staging room below the core's declared reserve (a runtime or core bug) |
refuse stages the response and then pushes Effect::ShutdownTransport and Effect::Finish. ShutdownTransport only marks the write side for shutdown: the runtime’s poll_transport_write sends and flushes the staged response first and calls poll_shutdown after, and step ends the runtime after Finish only once the staging buffer is empty and the write side is closed.
Half-closes follow Passthrough: client EOF becomes Effect::Shutdown on the outbound, outbound EOF becomes ShutdownTransport, and Finish follows once both halves have closed.
Building the handler and the outbound
Section titled “Building the handler and the outbound”The supervisor builds a handler or an outbound after validation has accepted the spec, so what fails here is construction:
| Situation | Error | Where |
|---|---|---|
| TLS certificate or key that does not load | TlsServerConfig::from_pem’s error, listed on Transports: TCP and TLS |
build_transport |
StreamShape::Tls on an inbound without TLS material |
InvalidInput, missing tls |
build_transport |
| Protocol and bind that do not fit together | InvalidInput, inbound <tag>: protocol and bind do not match; it cannot occur for HTTP, whose table is always UserTable::Http |
build_handler |
| An outbound shape without its TLS settings, WebSocket host or gRPC authority | InvalidInput, missing tls, missing ws host or missing grpc authority |
build/outbound.rs → transport_connector |
Log lines
Section titled “Log lines”| Level | Target | Text | Where |
|---|---|---|---|
debug |
etemenanki_protocols::http::core |
http: connect failed: <error> |
HttpCore::handle, Event::ConnectFailed |
debug |
etemenanki_protocols::http::core |
http: outbound failed: <error> |
HttpCore::handle, Event::OutboundError |
debug |
etemenanki_supervisor::serve |
http connection from <source> ended: <error> |
serve_connection, when drive returns an error. The protocol word is StreamProtocol::name() (supervisor/src/topology/inbound/mod.rs), which is http here. <source> is the Option<IpAddr> in Debug form, such as Some(192.0.2.10) or None. |
debug |
etemenanki_supervisor::serve |
inbound transport failed: <error> |
Connection::serve_tcp, when the inbound’s TLS, WebSocket or gRPC transport fails on an accepted or handed-over socket. |
The third line’s error is the runtime error’s text. A core error reads proxy core: <core error>, for example http connection from Some(192.0.2.10) ended: proxy core: http head exceeds maximum size; a transport error reads transport: <error>; the watchdog’s reads inbound handshake timed out after 10s. A refusal with 407 or 400 is not an error: the runtime ends without one, drive returns Ok(()), and nothing is logged.
Cancellation
Section titled “Cancellation”The core holds no task, lock, channel or timer of its own. It receives time only through its runtime: its one deadline is set through Effect::SetDeadline and comes back as Event::Deadline. When the runtime is dropped the core goes with it.
A client that connects and never sends a byte produces no event and so never arms the core’s deadline. The supervisor’s drive covers that case: it wraps each runtime step in tokio::time::timeout(HANDSHAKE_TIMEOUT, …) until is_established() is true, and fails with TimedOut and the text inbound handshake timed out after 10s. During a sniffing CONNECT the core is not yet established, so the watchdog still applies, and the 300 ms sniff deadline fires first. The connection’s future runs under its session’s token through Shared::spawn_until; see Listeners and the serve loop for what cancels it.
Client side
Section titled “Client side”Every handshake error fails the plaintext stream. The last three rows come from the client runtime, the others from the codec:
| Situation | Error |
|---|---|
Request longer than REQUEST_MAX |
InvalidInput, http: CONNECT request exceeds the codec's reserve |
Status other than 200 |
ConnectionRefused, proxy responded with status <code> |
Response head that httparse rejects |
InvalidData, malformed proxy response: <httparse error> |
| Response head without a status line (only blank lines) | InvalidData, proxy response missing status code |
Response head with no terminator within MAX_HEAD |
InvalidData, http: proxy response head exceeds maximum size |
| Response head larger than the client runtime’s read buffer | InvalidData, upstream frame larger than the client runtime's buffer |
| Upstream closes before a complete reply | UnexpectedEof, upstream closed during the handshake |
| Dial of the upstream fails | The dial’s own error; the runtime is Down from then on |
The client runtime re-wraps the codec’s errors as InvalidData and keeps their text. The supervisor sizes that runtime with HTTP_BUF (16 KiB), smaller than MAX_HEAD, so an oversized response head fails in the runtime before the codec’s own check can fire. Every error in this table is raised before ProxyClientConnecting resolves, so it reaches the server core that dialed the flow as Event::ConnectFailed.
A dial error, a start error, a read or write error on the wire and a failed flush in poll_connected mark the runtime Down, after which every call fails with NotConnected. A reply error returns without marking it, but ProxyClientConnecting drops the runtime on any error, so nothing polls it again.
The runtime also checks the codec’s side of the contract. With HttpConnect none of these can fire, because reply always makes progress or asks for more, seal takes its whole offer and open consumes its whole slice:
| Check | Error |
|---|---|
reply consumed more than it was given |
Other, codec consumed more reply than it was given |
reply consumed nothing, staged nothing and still awaits a reply |
Other, codec handshake step made no progress |
seal took zero bytes or more than offered |
Other, codec sealed an impossible byte count |
open returned a frame outside its slice |
Other, codec opened an impossible frame |
make_room cannot free enough staging for the reserve |
InvalidInput, frame larger than the client runtime's buffer, unreachable while REQUEST_MAX is below HTTP_BUF |
After the handshake, an error on the plaintext stream reaches the server core as Event::OutboundError.
Limits
Section titled “Limits”| Constant | Value | Where | Governs |
|---|---|---|---|
MAX_HEAD |
64 KiB (64 * 1024) |
protocols/src/http/protocol.rs |
Largest request head the core, or response head the codec, will buffer. |
HttpCore::BUF_SIZE |
MAX_HEAD |
protocols/src/http/core.rs |
The runtime’s BUF_SIZE parameter, so a whole head fits the read buffer. |
MAX_HEADERS |
128 | protocols/src/http/protocol.rs |
Header slots given to httparse, for requests and responses. |
HttpCore STAGING_RESERVE |
256 bytes | protocols/src/http/core.rs |
Room guaranteed for a fixed response. |
HttpConnect::REQUEST_MAX |
1024 bytes | protocols/src/http/codec.rs |
Largest CONNECT request, and the codec’s STAGING_RESERVE. |
HANDSHAKE_TIMEOUT |
10 s | protocols/src/core/mod.rs |
From the first byte to a complete head in the core; per step until established in drive. |
SNIFF_TIMEOUT |
300 ms | protocols/src/sniff/mod.rs |
Sniffing window of a CONNECT to an IP, from the early 200. |
SNIFF_LIMIT |
4 KiB | protocols/src/sniff/mod.rs |
Largest sniff prefix held. |
RELAY_IDLE_TIMEOUT |
300 s | protocols/src/core/mod.rs |
Idle limit of a relay, re-armed on every Transport and Outbound event. |
HTTP_BUF |
16 KiB | supervisor/src/topology/outbound/mod.rs |
Client runtime buffer of the http outbound; bounds the upstream’s response head in practice and each sealed write to 15,360 bytes. |
| Default ports | 443 for CONNECT and https://; 80 otherwise |
protocols/src/http/core.rs |
Port used when the authority has none. |
The unit tests in protocols/tests/unit/ are compiled into the crate through #[path] modules, so they can reach private items. The pipeline tests run the real runtimes over loopback TCP: protocols/tests/support/pipeline.rs → serve_runtime runs one ProxyServerRuntime per accepted connection with a direct connector, and client builds a ProxyClientRuntime over TCP.
| File | Test | Pins |
|---|---|---|
protocols/tests/unit/http/core.rs |
connect_to_a_domain_answers_200_once_connected |
Partial heads consume nothing; a domain CONNECT opens immediately, stages nothing until Connected, and is established at Open. |
connect_refused_answers_502_and_closes |
ConnectFailed stages RESP_502, then ShutdownTransport and Finish. |
|
connect_to_an_ip_with_sniffing_replies_early_and_holds_the_prefix |
The early 200, the SNIFF_TIMEOUT deadline, not established while sniffing, then SetDeadline(RELAY_IDLE_TIMEOUT) ahead of the Open with the sniffed domain and the ForwardHeld of the prefix, and no second 200. |
|
plain_request_is_rewritten_into_the_held_buffer |
Origin-form rewrite, header stripping, Connection: close, head-only consumption, exactly two effects, body forwarded after it, held buffer cleared. |
|
origin_form_without_transparent_is_a_400 |
RESP_400 and Finish without opening. |
|
missing_or_wrong_credentials_are_a_407 |
RESP_407 without credentials; a correct Basic header opens a flow as alice. |
|
an_oversized_head_is_refused |
MAX_HEAD bytes without a terminator is an error. |
|
protocols/tests/unit/http/protocol.rs |
target_absolute_form, target_absolute_form_no_path, target_origin_form |
parse_request_target splitting and the https flag. |
forward_request_strips_hop_by_hop |
HOP_BY_HOP and Connection-listed headers are dropped. |
|
head_end_is_found_only_once_the_blank_line_arrives |
find_head_end offsets. |
|
request_head_is_parsed_into_owned_parts |
parse_request_head, header_value, check_proxy_auth with a non-unit payload, and rejection of garbage. |
|
connect_request_and_response_status_round_trip |
build_connect_request parses back; parse_response_status reads 200, 407 and 502 from the fixed responses. |
|
protocols/tests/unit/http/codec.rs |
connect_codec_awaits_a_200_then_passes_through |
The request line and credential, NeedMore on a partial head, the tail after the head, verbatim open and seal. |
connect_codec_refuses_a_non_200 |
A 407 is ConnectionRefused. |
|
protocols/tests/unit/helpers/address.rs |
authority_ipv4_with_port, authority_domain_default_port, authority_ipv6_bracketed |
parse_authority on the three accepted shapes. |
protocols/tests/pipeline/http.rs |
new_server_vs_new_client_tcp |
HttpConnect against HttpCore with credentials, to an IP target with sniffing on (so the early-200 path): 100,000 bytes echoed, clean close. |
new_server_refuses_bad_credentials_with_407 |
A wrong password surfaces as an error containing 407. |
|
new_server_forwards_a_plain_request |
A real origin sees GET /path?q=1 HTTP/1.1 and the client gets its response. |
|
new_server_connect_to_an_ip_answers_before_the_first_bytes |
With sniffing on, the 200 arrives before the client sends payload. |
|
app/tests/unit/lower.rs |
a_server_config_lowers_to_its_spec |
An HTTP inbound without accounts lowers to users: None and no user set. |
a_user_without_the_name_it_is_keyed_by_is_refused |
An HTTP account with an empty user is refused as accounts[1] has no user. |
|
app/tests/integration/e2e_unix.rs |
http_connect_over_a_unix_socket_relays |
The app’s HTTP inbound on a Unix socket answers CONNECT with 200 and relays. |
app/tests/integration/e2e_xray_wrapped.rs |
app_server_http_over_tls, app_client_http_over_tls |
HTTP inside TLS with credentials, against the pinned Xray in both directions: the app’s inbound behind Xray’s client, and the app’s outbound in front of Xray’s server. HTTP over TLS was served before; these are its first end-to-end tests. |
supervisor/tests/hot_swap.rs |
a_protocol_change_on_the_same_port_keeps_the_socket_and_old_connections |
An http_inbound spec applied over a SOCKS inbound on the same bind is a handler swap (report.swapped is ["in"], nothing is rebound), an open SOCKS connection keeps relaying, and a new connection’s CONNECT is answered 200 and relays. supervisor/tests/support/mod.rs supplies http_inbound (plain TCP, users: None, on the same tcp_bind(port) as socks_inbound) and http_connect, which fails unless the reply starts with HTTP/1.1 200. |
supervisor/tests/unit/validate.rs |
an_inbound_carries_tls_material_exactly_when_its_shape_layers_tls, an_inbound_needs_no_ws_host_or_grpc_authority, a_unix_listener_carries_only_the_plain_tcp_shape, a_real_ip_header_needs_a_websocket_a_trusted_proxy_and_a_name |
Transport rules and the real-IP rules, checked on an InboundProtocolSpec::Http; see Validation and apply errors. |
Run them from the Etemenanki workspace:
cargo test -p etemenanki-protocols --lib -- http::core http::protocol http::codec helpers::addresscargo test -p etemenanki-protocols --test pipeline pipeline::http::cargo test -p etemenanki-app --lib -- lower::cargo test -p etemenanki-app --test integration e2e_unix::http_connect_over_a_unix_socket_relayscargo test -p etemenanki-app --test integration -- e2e_xray_wrapped::app_server_http_over_tls e2e_xray_wrapped::app_client_http_over_tlscargo test -p etemenanki-supervisor --lib -- an_inbound_carries_tls_material an_inbound_needs_no_ws_host a_unix_listener_carries_onlycargo test -p etemenanki-supervisor --test hot_swap a_protocol_change_on_the_same_portA bare --lib http:: filter would also run the HTTP sniffer’s tests in sniff::http. The core tests drive HttpCore through CoreHarness (protocols/src/core/harness.rs), a hand-driven stand-in for the runtime, and the file’s moves helper filters SetDeadline effects out so assertions stay about behaviour. A change to an event path belongs in tests/unit/http/core.rs; a change to what a real client or origin sees on the wire also needs a pipeline test. Testing describes the harnesses.