Skip to content

Life of a connection

Source files: 88 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/connector.rs
  • Etemenanki/supervisor/src/guard.rs
  • Etemenanki/supervisor/src/carrier.rs
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/supervisor/src/policy.rs
  • Etemenanki/supervisor/src/system/listener.rs
  • Etemenanki/supervisor/src/system/handoff.rs
  • Etemenanki/supervisor/src/entity/session.rs
  • Etemenanki/supervisor/src/entity/usage.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/plane.rs
  • Etemenanki/supervisor/src/topology/router.rs
  • Etemenanki/supervisor/src/topology/balancer.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/proxy.rs
  • Etemenanki/supervisor/src/topology/outbound/freedom.rs
  • Etemenanki/supervisor/src/topology/outbound/udp_fanout.rs
  • Etemenanki/supervisor/src/topology/outbound/dns.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/topology/spec_plan/plan.rs
  • Etemenanki/supervisor/src/track/mod.rs
  • Etemenanki/supervisor/src/track/metered.rs
  • Etemenanki/supervisor/src/track/sampler.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/app/src/main.rs
  • Etemenanki/ffi/src/proxy.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/trojan/core.rs
  • Etemenanki/protocols/src/vless/core.rs
  • Etemenanki/protocols/src/vmess/core.rs
  • Etemenanki/protocols/src/vmess/accounts.rs
  • Etemenanki/protocols/src/ss_legacy/core.rs
  • Etemenanki/protocols/src/ss_2022/core.rs
  • Etemenanki/protocols/src/ss_2022/crypto.rs
  • Etemenanki/protocols/src/http/core.rs
  • Etemenanki/protocols/src/socks/server.rs
  • Etemenanki/protocols/src/socks/handshake.rs
  • Etemenanki/protocols/src/socks/protocol.rs
  • Etemenanki/protocols/src/socks/udp_link.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/protocols/src/anytls/core.rs
  • Etemenanki/protocols/src/anytls/client/mod.rs
  • Etemenanki/protocols/src/sss/server.rs
  • Etemenanki/protocols/src/sss/core.rs
  • Etemenanki/protocols/src/transports/accept.rs
  • Etemenanki/protocols/src/transports/camouflage.rs
  • Etemenanki/protocols/src/transports/reality.rs
  • Etemenanki/protocols/src/transports/stream.rs
  • Etemenanki/protocols/src/transports/connect.rs
  • Etemenanki/protocols/src/transports/keepalive.rs
  • Etemenanki/protocols/src/transports/proxy_protocol.rs
  • Etemenanki/protocols/src/transports/grpc/settings.rs
  • Etemenanki/protocols/src/transports/grpc/liveness.rs
  • Etemenanki/protocols/src/transports/ws/endpoint.rs
  • Etemenanki/protocols/src/hysteria/server/inbound.rs
  • Etemenanki/protocols/src/hysteria/server/config.rs
  • Etemenanki/protocols/src/hysteria/config.rs
  • Etemenanki/protocols/src/hysteria/connector.rs
  • Etemenanki/protocols/src/hysteria/connection.rs
  • Etemenanki/protocols/src/wireguard/connector.rs
  • Etemenanki/protocols/src/wireguard/device.rs
  • Etemenanki/protocols/src/wireguard/slot.rs
  • Etemenanki/protocols/src/tun/inbound.rs
  • Etemenanki/protocols/src/tun/device.rs
  • Etemenanki/protocols/src/tun/ipv6.rs
  • Etemenanki/protocols/src/tun/udp.rs
  • Etemenanki/concepts/src/core.rs
  • Etemenanki/concepts/src/runtime.rs
  • Etemenanki/concepts/src/buffer.rs
  • Etemenanki/concepts/src/client.rs
  • Etemenanki/concepts/src/link.rs
  • Etemenanki/concepts/src/relay.rs
  • Etemenanki/environment/src/routing.rs
  • Etemenanki/environment/src/dial/tcp.rs
  • katana/src/config.rs
  • katana/src/lower/mod.rs
  • katana/src/lower/inbound.rs
  • katana/src/lower/route.rs
  • katana/src/rule.rs
  • katana/src/manager/node.rs
  • katana/src/api/hysteria.rs
  • katana/src/api/newv2board.rs
  • katana/src/api/helium.rs

This page follows one TCP connection through etemenanki-supervisor, from the moment a listener accepts the socket to the moment the last byte drains and the task ends. It names every function, type and effect the connection passes through, in the order it meets them, and links each step to the page that covers that component in depth.

The path belongs to the supervisor, and every front end runs the same one: etemenanki-app, katana and etemenanki-ffi each lower their own configuration into a Spec and hand it to a Supervisor, which binds the listeners and serves every connection the way this page describes. What differs between them is only the spec, covered under What each front end changes.

Read this page first if you are about to change the serving path, a protocol core, the connector or an outbound: it shows which task owns what, where each timeout sits, and which event the core sees at each point. Two branches leave the path before a runtime exists: a REALITY socket that is not a client of the inbound is relayed to its cover site (step 2), and an sss stream refused at its header gate is drained or handed to a fallback (step 3). The later sections cover what changes for UDP, for the two inbounds that do not accept TCP sockets (Hysteria 2 and TUN), and what an apply or a close does to a connection that is already running.

  1. Accept, admission and the session. run_stream_inbound accepts the socket, takes two permits from its inbound’s semaphores without waiting (or drops the socket), and registers the socket as a session.
  2. Transport accept. Connection::serve_socket reads a PROXY protocol v2 header first when the inbound asks for one, drops the connection if the guard has banned the client’s IP, and runs InboundTransport::accept: TLS, the WebSocket upgrade, the HTTP/2 handshake or REALITY’s handshake, bounded by TRANSPORT_HANDSHAKE_TIMEOUT. gRPC yields one byte stream per HTTP/2 stream, each a session of its own. A REALITY socket that is not a client of the inbound comes back as Disposition::Camouflage and is relayed to the cover site instead of being served. On a WebSocket inbound that reads a real-IP header, a connection from a proxy in the trusted networks takes its client from the upgrade’s header. A TCP socket that a relay on the same host hands over on the inbound’s handoff socket joins the path here: it is received with its client from the PROXY header sent beside it, then meets the ban check and the transport as an accepted TCP socket does.
  3. Core selection. serve_connection picks the protocol’s core, built from the user table current at that moment. SOCKS goes to its own driver instead, and sss reads its header through a pre-authentication gate before any runtime exists.
  4. Drive and the handshake watchdog. drive builds the core inside a ProxyServerRuntime and applies HANDSHAKE_TIMEOUT until the core is established, feeding the session’s wire bytes as it goes. It reports to the guard whether the handshake authenticated and, for VMess, which user it matched.
  5. Request parsing. The core parses and authenticates the request and pushes Effect::Open with a Flow that carries the user’s Principal.
  6. Admission and routing. While applying Open, the runtime calls AppConnector::connect, which binds the session to its user (within the user’s device limit), loads the current plane, routes the flow and picks a balancer member.
  7. Dialing. The target’s connect_stream future dials: directly (freedom), through a proxy client runtime over a TransportConnector (or, for sss, a connector that wraps one), through WireGuard, through Hysteria 2, or on a pooled AnyTLS session. The result is metered, and killed at once if a drain closed its outbound version while it dialed.
  8. Connected. The runtime delivers Event::Connected; the core stages its reply and the forwards queued behind Open go out.
  9. Relay. Client bytes become Forward effects; outbound reads become Event::Outbound and are staged back toward the client. Every outbound read and write is metered and paced.
  10. Half-close and completion. Each EOF becomes a half-close on the other side; when both have ended the core pushes Finish, staging drains, and the task ends. The flow deregisters, the session ends and folds its bytes into its user’s usage.
sequenceDiagram
  participant C as Client
  participant L as Accept loop
  participant S as Sessions
  participant T as serve_socket
  participant D as drive
  participant R as ProxyServerRuntime
  participant K as Core
  participant A as AppConnector
  participant X as Outbound
  C->>L: TCP connect
  L->>L: try_acquire live and handshake permits
  L->>S: open(tag, peer, counted wire, stop)
  L->>T: spawn_until(session token, serve_socket)
  T->>T: PROXY v2 header if sent, ban check
  T->>C: TLS, WebSocket upgrade, HTTP/2 or REALITY handshake
  T->>D: sink(stream), spawn_until(session token, serve_connection)
  D->>R: new(stream, make_core(), connector).showing_progress()
  C->>R: request bytes
  R->>K: Event::Transport(unparsed)
  K-->>R: SetDeadline, Effect::Open(key, Flow), Forward(rest)
  Note over D,K: is_established() is true, drive drops its handshake permit and calls report.succeeded(user_hint)
  R->>A: connect(flow) while applying Open
  A->>A: Session::admit, plane.route, Target::resolve
  A-->>R: boxed connect future
  R->>X: poll the future: resolve, dial, upstream handshake
  X-->>R: Metered of OutboundStream, killed at once if its version was drained
  R->>K: Event::Connected
  K-->>R: stage reply
  R->>X: queued Forward (poll_write, poll_flush)
  R->>C: staged reply
  loop Relay
    C->>R: bytes into the read buffer
    R->>K: Event::Transport
    K-->>R: Forward(range)
    R->>X: poll_write, metered and paced
    X->>R: bytes into scratch
    R->>K: Event::Outbound
    K-->>R: stage
    R->>C: poll_write from staging
  end
  C->>R: EOF
  R->>K: Event::TransportEof
  K-->>R: Shutdown(key)
  R->>X: poll_shutdown
  X->>R: EOF
  R->>K: Event::OutboundEof
  K-->>R: ShutdownTransport, Finish
  R->>C: drain staging, then shut down the write side
  R-->>D: stream ends
  D-->>S: task ends, flow and session drop

The whole connection lives in very few tasks. There is no task per direction and no channel between the client side and the outbound side: a ProxyServerRuntime owns the client transport, the core and every outbound the core opens, and moves bytes between them itself.

Task Spawned by Owns Ends when
run_stream_inbound Listener::start (supervisor/src/system/listener.rs) at commit, one per stream listener, on the supervisor’s TaskTracker the listener, its inbound’s InboundCaps (both semaphores), a watch::Receiver of the current handler the listener’s stop token is cancelled
Connection::serve_socket the accept loop, through Shared::spawn_until under the socket’s session token the accepted socket until the transport yields; for gRPC, the HTTP/2 connection; for a REALITY socket that is not a client, the relay to the cover site the transport has yielded its one stream, the HTTP/2 connection ends, the camouflage relay ends, or the session’s token is cancelled
serve_connection serve_socket’s sink, through Shared::spawn_until under the stream’s session token (awaited inline for a Unix socket) the ProxyServerRuntime: transport, core, outbounds, three buffers capped at BUF_SIZE; or the SOCKS driver the runtime completes or fails, or the session’s token is cancelled

Shared::spawn_until(token, fut) spawns until_cancelled(token, fut) on the supervisor’s TaskTracker: tokio-util’s with_cancellation_token_owned, which ends fut as soon as token is cancelled. Cancelling the token drops the future at whatever .await it is parked on, and with it every socket it owns. It is a combinator rather than an async block over a select!, because such a block keeps both the future it captured and the copy it moves into the select!, and the task would be twice the size of a connection’s future.

The tokens are what make listeners and connections independent. A listener’s stop token is a child of the supervisor’s root token, and so is every session’s token. Stopping a listener ends its accept loop and nothing else: the connections it accepted keep running under their own sessions until they end, are closed by a policy or by Supervisor::close, or the supervisor shuts down. Listeners and the serve loop draws the whole tree.

A few outbounds rely on a background task: every dialed gRPC transport spawns the driver of its own HTTP/2 connection, the Hysteria 2 client runs an HTTP/3 driver (and, when the server relays UDP, a datagram pump) for the QUIC connection all its flows share, the WireGuard outbound runs one device driver per tunnel, and an AnyTLS outbound runs a reaper, holding only a weak reference to its pool, that closes sessions left idle past the timeout. A proxy client runtime (ProxyClientRuntime) itself is polled inside the connection’s task, as the outbound’s AsyncRead and AsyncWrite.

The serving path in supervisor/src/serve.rs:

#[derive(Clone)]
pub(crate) struct Shared {
pub plane: PlaneCell,
pub sessions: Arc<Sessions>,
pub flows: Tracker,
pub tracker: TaskTracker,
pub guard: Arc<Guard>,
}
pub(crate) async fn run_stream_inbound(
listener: StreamListener,
handler: watch::Receiver<Arc<StreamInbound>>,
shared: Shared,
stop: CancellationToken,
);
struct Connection {
inbound: Arc<StreamInbound>,
peer: Option<IpAddr>,
carrier: Arc<Session>,
stop: CancellationToken,
shared: Shared,
live: Arc<OwnedSemaphorePermit>,
handshake: Arc<OwnedSemaphorePermit>,
}
async fn serve_connection<S>(
inbound: Arc<StreamInbound>,
stream: S,
local_ip: Option<IpAddr>,
connector: AppConnector,
live: Arc<OwnedSemaphorePermit>,
handshake: Arc<OwnedSemaphorePermit>,
report: Report,
) where
S: AsyncRead + AsyncWrite + Unpin + Send + 'static;
async fn drive<const BUF: usize, Core, S>(
stream: S,
make_core: impl FnOnce() -> Core,
connector: AppConnector,
handshake: Arc<OwnedSemaphorePermit>,
report: Report,
) -> io::Result<()>
where
S: AsyncRead + AsyncWrite + Unpin,
Core: ProxyCoreDecode<Target = Flow, Error = io::Error, TransportAddr = ()> + Established;
pub trait Established {
fn is_established(&self) -> bool;
fn user_hint(&self) -> Option<UserHint> { None }
}

Where each stream reports how its handshake ended (supervisor/src/guard.rs), what the streams of one gRPC connection share (supervisor/src/carrier.rs), and the policies that decide what follows (supervisor/src/policy.rs):

pub(crate) struct Guard { /* carrier_max_failures, the per-IP failure records */ }
impl Guard {
pub(crate) fn set_policy(&self, policies: &Policies);
pub(crate) fn is_banned(&self, ip: IpAddr) -> bool;
pub(crate) fn sweep(&self);
}
pub(crate) struct Report { /* guard, source, carrier */ }
impl Report {
pub(crate) fn new(
guard: Arc<Guard>,
source: Option<IpAddr>,
carrier: Option<Arc<Carrier>>,
) -> Self;
pub(crate) fn carrier_hint(&self) -> Option<UserHint>;
pub(crate) fn succeeded(&self, user: Option<UserHint>);
pub(crate) fn failed(&self);
}
// supervisor/src/carrier.rs
pub(crate) struct Carrier { /* failed streams in a row, the connection's token, the last user */ }
impl Carrier {
pub(crate) fn new(token: CancellationToken) -> Self;
pub(crate) fn failed(&self) -> u32;
pub(crate) fn succeeded(&self, user: Option<UserHint>);
pub(crate) fn last_user(&self) -> Option<UserHint>;
pub(crate) fn close(&self);
}
pub struct Policies {
pub user_removal: UserRemovalPolicy,
pub drain: DrainPolicy,
pub ip_ban: Option<IpBanPolicy>,
pub carrier_max_failures: Option<NonZeroU32>,
}
pub struct IpBanPolicy {
pub max_failures: NonZeroU32,
pub window: Duration,
pub duration: Duration,
}

What a decoded connection is, who it belongs to, and where it entered (protocols/src/flow.rs, supervisor/src/topology/flow.rs):

pub struct Flow<T> {
pub destination: Destination,
pub user: NetworkUser<T>,
pub sniffed: Option<SniffedBehavior>,
pub source: Option<IpAddr>,
}
pub type Flow = etemenanki_protocols::flow::Flow<Principal>;
pub struct Principal {
user: Option<UserKey>,
label: CompactString,
revoked: OnceLock<UserRemovalPolicy>,
}
pub struct FlowContext {
pub inbound_tag: CompactString,
pub source: Option<IpAddr>,
}

A Principal is what an inbound’s user table hands back on a successful handshake: the user it admitted, or nobody (Principal::anonymous()) for an inbound in its open or shared mode. Each inbound holds its own principal per user, so removing a user from one inbound revokes that inbound’s principal without touching the user’s sessions elsewhere.

The connector every inbound dials through (concepts/src/link.rs, supervisor/src/connector.rs):

pub trait Connector<Target> {
type Stream: AsyncRead + AsyncWrite + Unpin;
type Datagram: DatagramLink;
type Future: Future<Output = io::Result<Outbound<Self::Stream, Self::Datagram>>>;
fn connect(&mut self, target: Target) -> Self::Future;
}
#[derive(Clone)]
pub struct AppConnector {
plane: PlaneCell,
ctx: FlowContext,
tracker: Tracker,
session: Option<Arc<Session>>,
charge_datagrams: bool,
}
impl Connector<Flow> for AppConnector {
type Stream = Metered<OutboundStream>;
type Datagram = FanOutLink;
type Future = ConnectFuture;
fn connect(&mut self, flow: Flow) -> ConnectFuture;
}

Routing and dialing (supervisor/src/topology/plane.rs, supervisor/src/topology/router.rs, supervisor/src/topology/outbound/mod.rs):

pub type PlaneCell = Arc<ArcSwap<Plane>>;
impl Plane {
pub fn route(&self, flow: &Flow, ctx: &FlowContext) -> Routed<'_>;
pub fn route_upstream(&self, flow: &Flow, ctx: &FlowContext) -> Routed<'_>;
pub fn ipv6_unreachable(
&self,
destination: SocketAddr,
ctx: &FlowContext,
may_sniff: bool,
own: &[IpAddr],
) -> bool;
}
pub struct Routed<'a> {
pub target: &'a Arc<Target>,
pub rule: Option<RuleId>,
}
impl Target {
pub fn resolve(self: &Arc<Self>, prefer: Option<&OutboundId>) -> Arc<Target>;
pub fn connect_stream(self: &Arc<Self>, flow: Flow)
-> impl Future<Output = io::Result<OutboundStream>> + Send + 'static;
pub fn connect_datagram(self: &Arc<Self>, flow: Flow)
-> impl Future<Output = io::Result<OutboundDatagram>> + Send + 'static;
pub fn lacks_ipv6(&self, destination: SocketAddr, own: &[IpAddr]) -> bool;
pub(crate) fn close_flows(&self, tracker: &Tracker) -> usize;
pub(crate) fn close_if_drained(&self, flow: &FlowEntry);
}
pub fn route_target<'a>(flow: &'a Flow, ctx: &'a FlowContext) -> routing::RouteTarget<'a>;
impl Outbound {
pub fn connect_stream(&self, flow: Flow) -> StreamFuture;
pub fn connect_datagram(&self, flow: Flow) -> DatagramFuture;
}

The runtime and the core contract it drives (concepts/src/runtime.rs, concepts/src/core.rs):

pub struct ProxyServerRuntime<const BUF_SIZE: usize, Core, Trans, Conn, Mode = ProxyRunsQuiet>
where
Core: ProxyCoreDecode,
Conn: Connector<Core::Target>;
pub fn new(transport: T, core: Core, connector: Conn) -> Self;
pub fn showing_progress(
self,
) -> ProxyServerRuntime<BUF_SIZE, Core, Trans, Conn, ProxyShowsProgress>;
fn handle(
&mut self,
event: Event<'_, Self>,
effects: &mut Effects<'_, Self>,
) -> Result<usize, Self::Error>;

Listener::start spawns run_stream_inbound when an apply commits a new stream listener; the socket was bound earlier, in the apply’s prepare phase. The loop is a biased tokio::select! of the listener’s stop token over StreamListener::accept. Biased means the stop is checked first on every turn, so once the listener is stopped not one more socket is accepted. A StreamListener is a TCP or a Unix socket listener (Unix ones exist on Unix only); only the TCP one reports a peer address at accept, which becomes the flow context’s source so that source_cidr rules have something to match, unless a PROXY protocol header or a trusted reverse proxy’s header names another client (step 2).

Admission happens before any byte is read, and it never waits:

  1. live.clone().try_acquire_owned() takes a place from the inbound’s live-connection semaphore (MAX_LIVE_CONNECTIONS_PER_INBOUND, 4,194,304).
  2. handshakes.clone().try_acquire_owned() takes a place from the inbound’s handshake semaphore (MAX_HANDSHAKES_PER_INBOUND, 204,800).

If either semaphore is empty, the socket is dropped on the spot, together with any permit already taken, and the loop logs at debug level (dropping inbound connection; live connection limit reached or … handshake limit reached). Refusing instead of waiting keeps the loop accepting, so an overloaded listener sheds connections rather than letting the kernel’s listen backlog fill silently. Both semaphores belong to the inbound (InboundCaps, supervisor/src/serve.rs): its TCP listener and its handoff socket count against the same two, and a listener an apply adds beside a kept one joins the kept one’s (caps_for in supervisor/src/supervisor.rs). A listener keeps them while it runs, so their counts survive a handler swap.

With both permits taken, the socket becomes a session before anything else happens:

  1. The loop reads the handler current now, handler.borrow().clone(). An apply that changes the inbound on the same bind replaces the watch value, so each socket is served by the handler current at its accept.
  2. Sessions::open(tag, peer, Wire::counted(), &stop) registers the socket as a session with no user yet. Its token is a child of the supervisor’s root token, not of the listener. open checks the stop token under the session registry’s lock and returns None once it is cancelled; the loop then breaks and drops the socket, so a connection accepted as its inbound is removed either is swept with the inbound’s sessions or never opens one.
  3. A Connection carries the handler, the peer, the session (as carrier), clones of the stop token and of Shared, and both permits as Arc<OwnedSemaphorePermit>.
  4. shared.spawn_until(carrier.token(), connection.serve_socket(socket)).

The live permit travels as an Arc. A socket can yield several byte streams (gRPC yields one per HTTP/2 stream), each served by its own task, and every one of those tasks keeps a clone: the place returns to the semaphore only when the last task serving the socket has ended.

An accept error is classified by should_backoff_accept_error: ConnectionAborted and Interrupted are logged at debug level (accept error: <error>) and retried at once; anything else (running out of descriptors, for example) is logged at warn level (accept error, backing off 100ms: <error>) and followed by an ACCEPT_ERROR_BACKOFF (100 ms) sleep that the stop token cuts short. When the token is cancelled the loop breaks and drops the listener, which closes the port or removes the Unix socket file while it is still the one the listener created.

Deeper: Listeners and the serve loop, Users, principals and sessions and Limits, timeouts and memory.

Two checks come before the transport, on a TCP socket only, accepted or handed over:

  1. The client’s address. When the inbound’s spec sets proxy_protocol, the TCP listener reads a PROXY protocol v2 header when one is sent (protocols/src/transports/proxy_protocol.rs → read_v2) and takes the client address from it. Only version 2 is read; a connection without a header keeps its socket peer, and the header read has a timeout, PROXY_HEADER_TIMEOUT (10 s).
  2. The ban. If the guard has banned the client’s IP (Guard::is_banned), serve_socket returns, and the connection closes before its transport handshake. Connections from that IP already open run on.

A handed-over socket comes another way. On an inbound whose spec sets handoff (a HandoffSpec: a Unix socket path, its file mode and group; Unix only, beside a stream protocol’s TCP listener), each connection the handoff socket accepts is a relay’s control connection, and serve_socket first receives the TCP socket it carries (supervisor/src/system/handoff.rs → receive). The relay sends one message within RECEIVE_TIMEOUT (5 s): the socket as SCM_RIGHTS, exactly one descriptor, and a whole PROXY protocol v2 header with nothing after it, decoded by proxy_protocol::decode_v2. The message is read into MAX_V2_LEN + 1 bytes, so even a byte after a header of the full length is seen and refused. The descriptor must be a connected IP stream socket. When everything checks out, the relay is answered 0x00 and the control connection closes; otherwise the answer is 0x01, the descriptor received is closed, and the relay keeps its connection. A relay that hangs up without sending, or sends nothing in time, gets no answer. The client is the one the header names, or the socket’s own peer for a LOCAL header or an address that names no TCP client, and it becomes the session’s source (Session::set_source). From there the socket takes the TCP path above, through Connection::serve_tcp: the ban check (a banned client’s socket is taken, then dropped), then the inbound’s transport and protocol. Nothing is read from the handed-over stream before its transport.

serve_socket then hands the socket to the inbound’s InboundTransport (protocols/src/transports/accept.rs):

pub async fn accept<F>(&self, tcp: TcpStream, mut sink: F) -> io::Result<Disposition>
where
F: FnMut(Accepted);
#[non_exhaustive]
pub enum Disposition {
Done,
Camouflage(Camouflage),
}

accept first enables TCP keepalive on the socket (set_keepalive: first probe after TCP_KEEPALIVE_IDLE, 120 s, then every TCP_KEEPALIVE_INTERVAL, 30 s, giving up after TCP_KEEPALIVE_RETRIES, 3), then runs the transport’s own handshake within TRANSPORT_HANDSHAKE_TIMEOUT (10 s), failing with tls handshake timed out (or websocket …, grpc …). It returns Disposition::Done once every stream the socket yielded went to the sink; only REALITY returns Disposition::Camouflage, for a socket the sink never saw:

InboundTransport Handshake under the 10 s limit Streams yielded to sink
Tcp none exactly one, at once
Tls(ServerConfig) the TLS accept exactly one
Ws { route, tls } optional TLS, then the WebSocket upgrade (path and Host check) exactly one
Grpc { paths, tls } optional TLS, then the HTTP/2 server handshake one per accepted HTTP/2 stream on a known path, until the connection ends
Reality(RealityServer) (protocols’ reality feature, which the supervisor turns on) the dial of the cover site, then REALITY’s handshake, whose decision keeps a deadline of its own of the same 10 s: running out of time before the decision hands the socket to the cover site rather than failing exactly one for an authenticated client; none for anyone else, which comes back as Disposition::Camouflage

For gRPC, the transport keeps driving the HTTP/2 connection after the handshake. Each accepted stream whose path GrpcPaths::classify recognises (/{service}/Tun or /{service}/TunMulti) is answered with the gRPC response headers and passed to sink; any other path is reset with REFUSED_STREAM. Liveness (protocols/src/transports/grpc/liveness.rs) watches the connection:

  • Idle. A connection that carries no streams for H2_IDLE_TIMEOUT (30 s) is told to go away with a GOAWAY (graceful_shutdown). A stream handed to the sink restarts that deadline, and so does a change in the number of open streams; a request refused for its path does not.
  • Gone. A PING goes out every H2_KEEPALIVE_INTERVAL (60 s). The peer is judged dead, and the connection dropped, once nothing at all has been heard from it for H2_KEEPALIVE_TIMEOUT (20 s) since the PING went out. Any byte counts, not only the PONG: the connection’s I/O is wrapped in Heard, which stamps a shared ReadClock on every read.
  • Not reading. A PONG still owed after H2_PONG_TIMEOUT (300 s) also ends the connection, so a peer that keeps sending but never reads does not hold the connection.

For REALITY (protocols/src/transports/reality.rs), the transport dials the cover site itself, under the supervisor’s socket policy, through the system resolver rather than the spec’s DNS, and outside routing and accounting (build_reality in supervisor/src/build/inbound.rs), and hands both sockets to etemenanki-reality’s server. An authenticated client’s stream goes to the sink as TransportStream::Reality. Anyone else, and any handshake that fails before the server’s flight is sent, comes back as a Camouflage relay holding what each side already said. serve_tcp then takes the connection off the serving path:

  1. It logs at debug level (<tag>: <source> goes to dest: <reason>, where the reason is a category safe to log).
  2. It drops the connection’s handshake permit and keeps its live permit.
  3. It runs the relay with RELAY_IDLE_TIMEOUT (300 s) as its idle limit, still under the session’s token, so closing the session or shutting down ends it like any connection.

Nothing in the relay is reported to the guard: a probe must not see the server react, and the clients behind its address must not pay for it. A cover site that cannot be dialed fails every connection (inbound transport failed: …), and the transport warns about it at most once a minute.

On a WebSocket inbound whose spec sets real_ip (a RealIpSpec: a header name and the networks of the trusted proxies), the upgrade callback reads that header (WsRoute::real_ip_header), and the sink first settles who the client is (real_ip_source). The header counts only on a connection from a proxy in the trusted networks (RealIpSpec::trusts); from anyone else it is ignored, so a client cannot name itself someone else. From a trusted proxy, an address list names the rightmost address that no trusted network holds, or the leftmost when they hold every one. A missing or malformed header leaves the proxy as the client, with a debug log (trusted proxy <ip> sent no <header> header; serving it as the client, or … sent a <header> header that lists no addresses; …). A named client that differs from the connection’s is held to the ban check (a banned one is dropped), becomes the session’s source through Session::set_source before the session binds, so the device limit counts it, and is the source the connector, the Report and the flows see.

The sink decides each stream’s session and spawns serve_connection for it, with the socket’s permits, its local_addr IP (which only the SOCKS driver uses) and a Report for the guard:

  • One stream per socket (TCP, TLS, WebSocket). The stream is the socket’s own session: its connector is built for the carrier with connector_for(tag, source, carrier), and the task runs under the carrier’s token.
  • gRPC. Each HTTP/2 stream is a session of its own, opened through Shared::connector with a Wire of its own. A protocol authenticates per stream, so streams sharing one HTTP/2 connection may belong to different users, and closing one user’s must leave the others. Every stream’s Report also carries the connection’s Carrier (supervisor/src/carrier.rs): once carrier_max_failures streams in a row have failed to authenticate, the carrier’s token is cancelled and the connection closes. The Carrier also keeps the user the connection’s last authenticated VMess stream matched, which the connection’s next VMess stream tries first (step 3).

On a VLESS inbound that serves the XTLS Vision flow (StreamProtocol::Vless { vision: true, .. }), the sink also wraps the stream in the Vision server adapter (TransportStream::into_vision_server) before it spawns serve_connection, so the core reads plain VLESS over it. The adapter takes only a REALITY stream (vless vision rides only over reality), which validation already guarantees; anything else is dropped with a debug log (<tag>: vision setup failed: …).

A Unix socket skips the transport entirely. The front end refuses any stream settings on a Unix listener (etemenanki-app: inbound local: protocol http over a unix socket does not support stream network "ws"), and validation holds the supervisor to the same rule (a unix socket carries no transport; its shape must be plain tcp). serve_socket awaits serve_connection directly on the carrier session, with local_ip and source both None.

A transport that fails before yielding anything ends serve_socket with a debug log (inbound transport failed: …); the socket and its session are dropped, and the client never reaches a core. Unix sockets are served on Unix only: elsewhere validation refuses a Unix bind (unix sockets are not served on <os>), and listener::bind fails with unix socket <path>: not served on this platform.

Deeper: TCP and TLS transports, WebSocket and gRPC transports, Transports: REALITY, etemenanki-reality overview and VLESS Vision.

serve_connection reads the client address from the connector (connector.source(): the peer IP, or None over a Unix socket) and sniff from the handler, then matches on the handler’s StreamProtocol and hands drive a closure that constructs a fresh core for this connection. drive calls it itself: an async fn keeps its arguments in its future for as long as the future lives, and the runtime holds a second copy of a core passed in, so every connection would pay for its core twice (a VMess core is about a KiB). Each variant holds its user table in an ArcSwap, and the core is built from load_full() of it, so a user change stored while the connection runs never changes the table under its handshake. VMess is the exception: its Arc<AccountValidator> swaps its users in place. Every core is instantiated on Principal, and the runtime’s buffer size is the core’s own BUF_SIZE constant:

StreamProtocol Driver Core constructor BUF_SIZE
Socks SocksInbound::serve on socks.load_full() none: bespoke driver RELAY_BUF, 16 KiB per direction of a BidirectionalConnection
Http drive HttpCore::new(config.load_full(), sniff, source) MAX_HEAD, 65,536
Trojan drive TrojanCore::new(validator.load_full(), sniff, source) 16,384
Vless { users, vision } drive VlessCore::new(users.load_full(), sniff, source) 16,384
Vmess drive VMessCore::new(validator.clone(), now_unix, sniff, source).with_hint(hint) 32,768
Shadowsocks drive ShadowsocksCore::new(resolved.load_full(), sniff, source) 20,480
Ss2022 drive Ss2022Core::with_system_clock(users.config, users.validator, sniff, source) MAX_RECORD_LEN, 65,569
Anytls { users, padding } drive AnyTlsCore::new(users.load_full(), padding.clone(), sniff, source) 16,384
Sss { users, settings } serve_sss: the header gate, then drive SssCore::new(users, max_datagram, sniff, source) TCP_BUF_SIZE, 16,384, for a TCP stream; UDP_BUF_SIZE, 67,584, for a UDP one

VMess’s hint is report.carrier_hint(): on a gRPC connection, the user the connection’s last authenticated stream matched (Carrier::last_user), and None anywhere else. AccountValidator::verify_from tries that user first, then the users that last matched from the client’s address, then the hot tier of recently matched users, and only then every user. A guess only picks which key is tried: the CRC, the clock check and the replay set decide exactly as for a full scan, so a stale guess never admits another user. See VMess crypto.

Shadowsocks 2022’s buffer is the largest record a peer may send: a 65,535-byte payload plus RECORD_OVERHEAD (a 2-byte length and two 16-byte tags, 34 bytes), from protocols/src/ss_2022/crypto.rs. Cores receive time through events and through their constructor: VMess gets now_unix and Shadowsocks 2022 the system clock as constructor arguments, and deadlines arrive as Event::Deadline.

An AnyTLS connection is one session that carries many streams, each an outbound of the core keyed by its stream id, the shape of the mux.cool demultiplexer. It still runs on the ordinary drive path: the core is established once the password’s hash and the first padding (padding0) are read, so drive releases the handshake permit then, while the live permit and the session cover every stream of the connection. A wrong password fails on the hash alone with PermissionDenied and counts toward the IP ban. See AnyTLS.

sss reads its header before any runtime exists. serve_sss (boxed, so other protocols’ connections do not grow by its size) runs sss::accept (protocols/src/sss/server.rs) over the stream: it wraps the stream in the inbound’s transform chains and reads the request header within the header time T_h (counted from the accept; 10 s unless configured) and the pre-authentication budget B_pre of raw bytes.

  • Admitted. A complete header naming a known user is admitted: drive runs the core over the decoded side, with a runtime sized for the header’s command, so the session’s wire counts sss bytes after the transforms are undone. The core reads the header again from the same decoded bytes.
  • Refused. Anything else is refused without a byte in reply and logged at debug level as a category (<tag>: sss stream from <source> refused: <reason>). The refused stream is drained (read and discarded until the peer closes or T_h passes), keeping its handshake permit as a stream still waiting for its header would. Or it is handed to the configured fallback address, which gets every raw byte read so far and is relayed from then on; that releases the handshake permit, the stream being past its handshake like a REALITY camouflage. A fallback that cannot be reached drains instead.

No refusal is reported to the guard: what the server does must not depend on which check failed. See sss and sss transforms.

SOCKS is the one server that does not fit ProxyCoreDecode: its UDP side lives on a second socket that the control connection only keeps alive, and that socket hears only the control connection’s client (see How UDP differs). SocksInbound::serve runs the SOCKS 4/4a/5 handshake under its own HANDSHAKE_TIMEOUT, calls connector.connect(flow) with the same AppConnector, writes the granted reply only after the connect succeeds (or a refusal code if it fails; a sniffed IP target is the exception, see step 5), writes the prefix it held while sniffing to the upstream and flushes it, so an upstream that keeps small writes until a flush (a WebSocket sink, sss’s transform chains) passes the client’s first bytes on, and relays with a BidirectionalConnection guarded by RELAY_IDLE_TIMEOUT. No runtime reports what the SOCKS stream moved, so serve_connection wraps it in WireCounted, which adds every byte read and written to the session’s wire. Everything from step 4 on describes the core path.

Deeper: Listeners and the serve loop and, for the SOCKS driver, SOCKS.

drive builds the core and the runtime in stream mode:

let mut runtime = ProxyServerRuntime::<BUF, Core, _, _>::new(stream, make_core(), connector)
.showing_progress();

showing_progress turns the runtime from a Future into a Stream of Traffic deltas, one per unit of work. drive uses those yields twice. Between two of them it can check the core. And each delta’s transport_rx and transport_tx are added to the session’s Wire (wire.add(transport_rx, transport_tx)), in the handshake and the relay alike: the bytes of the protocol stream after its transport, which is what per-user usage counts.

A runtime delivers no event before the client sends its first byte, and the core’s own Timing arms its handshake deadline only on that first byte event. A client that connects and says nothing would otherwise never be timed out, so drive is the watchdog: while runtime.core().is_established() is false, every runtime.next() is wrapped in tokio::time::timeout(HANDSHAKE_TIMEOUT, …). On expiry drive returns inbound handshake timed out after 10s and the connection is dropped.

The two deadlines cover each other. drive catches a client that never speaks; once the first byte arrives, Timing::touch arms HANDSHAKE_TIMEOUT exactly once (it does not re-arm while the phase is still Handshake), so a client that trickles its request byte by byte still hits the core’s deadline 10 s after its first byte, and the core fails with client did not complete its request in time.

is_established() comes from Timing::is_established: true once the core is in Phase::Relay or Phase::Closing. A core enters Relay when it accepts the request: for a plain TCP request in the same call that pushes Open, before the dial completes; for a UDP or mux request as soon as the header is authenticated; for a sniffed request only when sniffing ends. At that point drive drops its handle to the handshake permit (handshake.take()), calls report.succeeded(runtime.core().user_hint()), and polls the runtime until it ends; from here on the core’s own deadlines govern the connection. Established::user_hint is None for every core but VMess’s, which names the user its auth id matched; on a gRPC connection the Carrier keeps that user for the next stream.

drive also tells the guard how the handshake ended, through the stream’s Report. Every core keeps one contract (protocols/src/core/mod.rs): a core that refuses a credential, because no user it knows matches, fails with io::ErrorKind::PermissionDenied, and fails with that kind for nothing else before it is established. So a RuntimeError::Core of that kind before establishment makes drive call report.failed(). A failure counts against the client’s IP under the spec’s IpBanPolicy: once max_failures have counted within window of the first, the IP is banned for duration, and its next TCP connections are dropped in step 2. On a gRPC connection it also counts against the connection’s Carrier. A success clears both counts, though a ban runs to its end. The guard keys the per-IP records by BanKey: an IPv4 client by its address, an IPv6 client by its /64, and an IPv4-mapped IPv6 address as the IPv4 address inside it, so for an IPv6 client the failures, the ban and the success that clears the count all apply to its whole /64. guard::sweep_until drops the records of IPs neither banned nor within their window every SWEEP_INTERVAL (30 s).

Deeper: Listeners and the serve loop, Server runtime and Protocol foundations.

Transport reads land in the runtime’s read buffer (up, a ReadBuffer<BUF_SIZE>), which starts at 2 KiB (or BUF_SIZE, if that is smaller). The runtime hands the core the whole unparsed region as Event::Transport(&mut [u8]); the core returns how many leading bytes it consumed. A core that needs more returns Ok(0), and the runtime reads again, keeping the unconsumed tail. When reading has used up the free tail, make_room moves the unparsed bytes to the front and doubles the buffer, up to BUF_SIZE. If the unparsed region fills all BUF_SIZE bytes and the core still consumes nothing, the runtime fails with RuntimeError::FrameTooLarge.

VlessCore is a plain example. On its first byte event Timing::touch pushes Effect::SetDeadline(Some(HANDSHAKE_TIMEOUT)). Once parse_request_header has a whole header, the core looks the UUID up in its user table (validator.get), which hands back the user’s Principal, and builds the flow with that principal and the client’s address. It then enters Phase::Relay, which pushes Effect::SetDeadline(Some(RELAY_IDLE_TIMEOUT)), and opens the flow with Effect::Open { key: FlowKey::Direct, target: flow }. The call returns the header length.

Every core enters Relay before it pushes Open. The runtime applies effects strictly in order, and a forward to a key that is still connecting holds the queue until the key is up. A deadline pushed after such a forward would wait out the connect with the previous phase’s deadline still armed, and the sniffing window’s 300 ms would end the flow as idle mid-connect.

The runtime immediately offers the rest of the buffer again, and the core pushes a Forward { key: FlowKey::Direct, range } for the payload that arrived with the header. That forward waits behind the Open until the key is up.

An unknown user makes the core return an error (invalid vless request user id, PermissionDenied), which the runtime reports as RuntimeError::Core; the connection ends with no reply, and drive reports a failed authentication. The user id is looked up before the flow is read, so an unknown user is refused this way whatever flow the request asks for. The core serves plain VLESS only: a known user’s request that carries a flow is refused (vless flow (xtls vision) is not served by this core, Unsupported). On an inbound that serves Vision, the adapter the sink put in front (step 2) strips the flow from the header before the core reads it.

When the inbound has sniff on and the request names an IP (worth_sniffing), the core does not open yet. It enters Phase::Sniff (deadline SNIFF_TIMEOUT, 300 ms) and copies the first payload bytes into a SniffPrefix, up to SNIFF_LIMIT (4 KiB), until a TLS SNI or an HTTP Host turns up, the budget runs out, or the deadline fires. The prefix’s Collector owns no memory until its first bytes, which reserve the whole 4 KiB at once. Then the core sets flow.sniffed, enters Relay, pushes Open, and forwards the collected bytes with Effect::ForwardHeld from its held buffer. The sniffed domain only feeds the router; the dial still goes to flow.destination.

Protocols whose client waits for a reply before it sends payload (HTTP CONNECT, SOCKS, Hysteria 2) answer “connected” first when they sniff an IP target, then collect the prefix.

Deeper: Server core, Sniffing, and each protocol’s page, for example VLESS or Trojan.

6. AppConnector admits and routes the flow

Section titled “6. AppConnector admits and routes the flow”

Routing runs synchronously inside the runtime’s task, at the moment the runtime applies Effect::Open. In drive_effects the runtime removes the effect, refuses a key that is already live (RuntimeError::DuplicateKey), creates the key’s KeyWaker, calls self.connector.connect(target), stores the returned future boxed in LinkState::Connecting, and schedules the key.

AppConnector::connect (supervisor/src/connector.rs) does, in order:

  1. Admit. When the connector has a session, session.admit(&flow.user.user_data) runs first, for TCP and UDP alike. The first flow binds the session to the principal it presents: the session is indexed under that user, and the user’s account in the usage ledger is opened on the session’s wire. A session whose first flow presents a principal that was already revoked is closed and refused (the user was removed before the session opened a flow), whatever the removal policy; a session that was closed meanwhile is refused with the session was closed. The bind is also where a user’s device limit (UserSpec::device_limit) holds: when the user’s bound sessions already come from as many distinct IPs as the limit and this session’s IP is not one of them (Inner::over_device_limit), the session’s token is cancelled and the flow is refused with PermissionDenied (the user's sessions already come from as many IPs as their device limit). An IP frees its place when its last session ends. A refusal comes back as an already-failed future, so the core sees a connect failure.
  2. UDP becomes a fan-out. A flow whose destination.network is DialNetwork::Udp is not routed here. The connector returns a FanOutLink at once, which routes packet by packet (see How UDP differs).
  3. Load the plane. self.plane.load() reads the current Plane from the PlaneCell (an Arc<ArcSwap<Plane>> shared by every connector) once for this flow: a route change reaches the next flow, while this one keeps the target it is opened on.
  4. Route. plane.route(&flow, &self.ctx) returns the target and the matching rule. When the spec has a split DNS, a flow to port 53 goes to the supervisor’s DNS service, Outbound::Dns, with no rule; otherwise CompiledRoutes::decide runs the route table and returns a slot, which the plane maps to its target, and the RuleId that matched (None for the default route).
  5. Resolve. routed.target.resolve(None): an outbound target stays as it is, and a balancer picks its member now (Balancer::select_preferring), so a member that went down is skipped from the next flow on and the flow is filed under the outbound that carries it.
  6. Describe and open. FlowMeta::of(…) fixes what the flow tracker will report (session, inbound tag, principal, source, requested destination, sniffed name, outbound version, rule and plane epoch), and target.connect_stream(flow) starts the dial. When the dial resolves, Tracker::meter_stream wraps the stream in Metered, which registers the flow and sends FlowEvent::Opened, and target.close_if_drained(stream.entry()) kills the new flow at once if a drain closed its outbound version while it was dialing.

route_target (supervisor/src/topology/router.rs) adapts the flow to the route model’s RouteTarget:

RouteTarget field Taken from Used by
remote, port flow.destination domain, cidr, geoip and port matchers
sniffed_domain flow.sniffed every domain matcher, geosite included, tries it as well as remote
inbound_tag ctx.inbound_tag inbound_tag
source flow.source.or(ctx.source) source_cidr
network flow.destination.network (Tcp or Udp) network

The flow’s own source wins over the listener’s. For a TCP inbound they are the same address; a QUIC or TUN inbound serves many peers and only the flow knows which one it came from.

Inside decide, the route model’s Router tries the rules in order; the first rule with any matching matcher wins, and otherwise the default applies. The compiled table names slots rather than outbounds, and each plane fills the slots with the targets of the same publish, so routes and outbounds are swapped together by one store and a rule can never name a tag the plane lacks.

Deeper: The plane: routing each flow and Route model.

Target::connect_stream(flow) calls Outbound::connect_stream(flow), which returns a boxed StreamFuture; nothing is dialed until the runtime polls it in service_key. Outbound::Blackhole resolves at once to OutboundStream::Blackhole, which reads EOF and swallows writes. Outbound::Dns resolves at once to a stream answered in-process by the DNS service. Every outbound socket the supervisor opens (dials, UDP sockets, the SOCKS relay socket, WireGuard and Hysteria 2 sockets, resolver queries, balancer probes, the probe sockets of the TUN IPv6 screen, and a REALITY inbound’s dial of its cover site) goes through the host socket policy that SupervisorBuilder::socket_options installs, if the front end installed one.

FreedomConnector::dial resolves flow.destination with the Resolver and AddressFamilyStrategy the outbound was built with, then TcpDialer::connect_any tries the addresses one after another, each bounded by DEFAULT_CONNECT_TIMEOUT (10 s), and returns every failure in one error (failed to connect to any address (…)). The result is OutboundStream::Tcp.

A dial that fails returns its error before the metering wrapper is built, so a failed open is never registered as a flow.

Deeper: Outbounds, UDP fan-out and balancers, Client runtime, Dialers, WireGuard, Hysteria 2 client, AnyTLS, Transports: REALITY.

8. Connected, and the reply the core stages

Section titled “8. Connected, and the reply the core stages”

service_key polls the connect future whenever the key’s waker fires. On Ready(Ok(outbound)) the slot becomes LinkState::Stream, the key is rescheduled so its first read is attempted, and the core receives Event::Connected { key }. What the core does with it is protocol-specific:

Core On Connected (TCP) On ConnectFailed
HttpCore (CONNECT) stages HTTP/1.1 200 Connection established stages HTTP/1.1 502 Bad Gateway (unless the 200 already went out for a sniffed IP target), then ShutdownTransport and Finish
VlessCore stages the 2-byte RESPONSE_HEADER closes without a reply
VMessCore stages its sealed response header closes without a reply
TrojanCore nothing: Trojan has no reply closes
ShadowsocksCore nothing closes
Ss2022Core nothing yet: the response header is sealed with the first downlink bytes, or at outbound EOF if there are none closes
AnyTlsCore a version 2 client gets a SYNACK for that stream; a version 1 client nothing a version 2 client gets a SYNACK carrying outbound connection failed, then a FIN for that stream; a version 1 client only the FIN. The session and its other streams carry on
SssCore nothing: sss has no reply closes

Right after the core returns, handle_meta runs drive_effects, and the forwards that were waiting behind Open are written to the outbound. The staged reply goes to the client on the next poll_transport_write.

On Ready(Err(error)) the runtime calls forget_key, which removes the slot and drops every queued effect still aimed at that key, and then delivers Event::ConnectFailed { key, error }. A connect failure is an event for the core to answer, not a runtime error. Single-stream cores answer through Passthrough::on_outbound_gone, which pushes ShutdownTransport and Finish.

UDP and mux requests are answered earlier: VLESS and VMess stage their response header as soon as the request is authenticated, because those flows are opened per packet or per sub-flow later.

Deeper: VLESS, VMess wire format, HTTP, Shadowsocks 2022, AnyTLS, sss.

From here the runtime alternates between the two directions. Each step works through, in order: the deadline, effects still waiting on an outbound, staged writes toward the client, then the client read and the ready outbounds, taking turns (prefer_transport) so neither side starves the other.

Uplink (client to target). A transport read fills up; Event::Transport hands the core the unparsed bytes; a relaying core pushes Forward { key, range } (for a plaintext core, Passthrough::on_transport forwards the whole slice). A queued forward pins the transport buffer: the runtime does not read from the client again until the forward has been written. drive_effects writes with poll_write and then poll_flush; if the outbound returns Pending, the queue waits there, and the client is not read. That is how backpressure reaches the client.

Downlink (target to client). An outbound is serviced only when its KeyWaker has fired, and read only when the staging buffer has STAGING_RESERVE + 1 bytes of room. The read goes into scratch (allocated at the first outbound read; at most the room left above the reserve) and reaches the core as Event::Outbound { key, data }, which the core must consume whole: it stages the bytes, sealing them for an encrypted protocol. poll_transport_write writes staging to the client. A client that stops reading fills staging, and the runtime stops reading the outbound.

Metering and pacing. Every read and write on the outbound goes through Metered. It checks the flow’s kill flag, then waits on the user’s pacer (a token bucket per user, unlimited until the spec gives the user a speed_limit), then counts the payload that moved into the flow’s counters. A drain with Close sets the same kill flag on every flow of the version (Target::close_flows → Tracker::kill_where). Those counters are payload between the core and the outbound. The session’s wire bytes are counted separately, on the client side, by drive (step 4).

Idle. Timing::touch runs at the top of every byte event and re-arms RELAY_IDLE_TIMEOUT (300 s). When the deadline fires with nothing moved in either direction, Timing::expired returns Expired::Idle and pushes Finish.

When the outbound is a proxy client runtime, the core’s Forward lands in ProxyClientRuntime::poll_write, which seals the bytes with the codec into its own staging buffer and writes them to the upstream; poll_read opens frames in place and copies plaintext out. All of it runs inside the connection’s task.

Deeper: Server runtime, Links and types and Tracking flows, stats and speed limits.

Single-stream cores keep a Passthrough for the close bookkeeping:

Event Passthrough call Effects pushed
Event::TransportEof (client finished sending) on_transport_eof Shutdown { key }, then Finish if the outbound had already ended
Event::OutboundEof { key } (target finished sending) on_outbound_eof ShutdownTransport, then Finish if the client had already ended
Event::ConnectFailed or Event::OutboundError on_outbound_gone ShutdownTransport, Finish

Effects apply in order, so Shutdown { key } reaches the outbound (poll_shutdown) only after every forward queued before it has been written. ShutdownTransport shuts the client’s write side only after staging has drained and been flushed. A slot whose read and write sides have both closed is removed from the runtime’s outbounds map, which drops (and closes) the outbound.

After Finish, the runtime stops reading from either side and only drains staging. step returns None once the core has finished, staging is empty, and any requested transport shutdown has completed. The progress stream ends and drive returns Ok(()). Then everything unwinds by drop:

  1. The runtime drops its outbounds. Dropping the Metered wrapper drops its FlowHandle, which removes the flow from the tracker, queues its last counts for the sampler, and sends FlowEvent::Closed.
  2. serve_connection returns, dropping the connector and the connection’s clone of the live permit; the permit returns to its semaphore when the last clone for that socket is gone.
  3. When the last handle to the session drops, Session’s Drop cancels its token, folds what the session carried since its user’s last report into the user’s account, and deregisters the session.

A failure ends the same way, earlier. drive turns any RuntimeError into an io::Error with the runtime’s text, and serve_connection logs it at debug level with the protocol’s StreamProtocol::name() and the client address, for example vless connection from Some(203.0.113.7) ended: inbound handshake timed out after 10s.

Deeper: Server core for Passthrough and the close effects, Server runtime for the drain, Per-user usage accounting for what a session’s end reports.

A UDP flow reaches the connector the same way, as an Effect::Open whose Flow has DialNetwork::Udp. After admitting it, AppConnector does not route or dial it: it returns a FanOutLink at once, so the core’s Connected arrives on the next poll and every packet is routed on its own. An AnyTLS stream to the UDP-over-TCP address and an sss stream whose header names UDP open their flow this way too:

flowchart TB
  core["Core: Effect::SendTo(key, to, range)"]
  send["FanOutLink::poll_send_to"]
  route["flow.toward(to), plane.load(), plane.route"]
  resolve["Target::resolve, preferring the member in use"]
  known{"Sub-link open for this OutboundId?"}
  write["sub-link poll_send_to, move to most recently used"]
  opendg["Target::connect_datagram(flow.toward(to))"]
  meter["meter_datagram, close_if_drained, add to the table"]
  drop["open failed: packet dropped"]
  core --> send --> route --> resolve --> known
  known -->|yes| write
  known -->|no| opendg
  opendg -->|ok| meter --> write
  opendg -->|error| drop
  • Routing input. Each packet routes as self.flow.toward(to): the association’s user and source, the packet’s own destination (whose network is Udp), and no sniffed domain (toward resets it). The plane is loaded for every packet, so a route change reaches the very next packet of a live association.
  • Identity. Sub-links are keyed by the OutboundId (tag and version) of the resolved outbound, never by the address of a target, which a freed and rebuilt outbound could reuse. A new version of a tag is a new key, so the next packet routed to it opens a sub-link of its own.
  • Balancers. A balancer is resolved per packet, preferring the member the association already uses for that route, so a healthy member keeps the association instead of it hopping between members packet by packet.
  • Failures. A failed open drops its packet and reports it as sent (Ok(buf.len())), so the association does not stall on an unreachable peer. A sub-link whose flow is killed, by a kill or by a drain with Close of its outbound version, is removed; the next packet routed there opens a fresh one, and the association itself carries on.
  • Bound. At most MAX_SUBS (64) sub-links stay open; opening the 65th evicts the least recently sent-to.
  • Replies. poll_recv_from polls the sub-links round robin from where the last receive stopped and returns the first packet with its source, which reaches the core as Event::Datagram { key, from, data }. A sub-link whose receive fails is removed; the association carries on with the rest.
  • Each sub-link is a flow. Every sub-link is registered with the tracker as a MeteredDatagram of its own, under the association’s session, so killing one ends that sub-link alone.

Target::connect_datagram opens the per-outbound link: a dual-stack socket for freedom, the protocol’s datagram codec over a ProxyClientRuntime for Trojan, VLESS, VMess and sss (an sss UDP flow is an sss stream of its own, and a VLESS outbound with the Vision flow carries its packets as XUDP over mux.cool, as Xray’s client does), a UDP-over-TCP stream on a pooled session for AnyTLS, a SocksUdpLink for SOCKS (which takes a datagram as a reply only if endpoint of its sender equals endpoint of the relay the server named, so a dual-stack socket still hears an IPv4 relay), a tunnel association for WireGuard, a session on the shared QUIC connection for Hysteria 2, and the DNS service’s own link for a port-53 packet intercepted by the plane. HTTP, Shadowsocks and Shadowsocks 2022 outbounds return Unsupported (… carries no datagrams), so their packets are dropped. A datagram link has no flush of its own, so a ProxyClientRuntime flushes the wire after each packet it writes, and a flush that has to wait is finished on the link’s next poll: a wire that holds small writes until a flush (a WebSocket sink, sss’s transform chains) would otherwise keep a packet back until the next one.

SocksInbound::serve runs its handshake through handshake_with_udp_source, which returns, alongside the Handshake, a UDP ASSOCIATE’s DST.ADDR and DST.PORT (None for any other request). For a UDP ASSOCIATE, associate builds an ExpectedSender from the control connection’s source, that declared source and the relay IP before it binds the relay socket (the hub):

  • One client. Over TCP, every datagram must come from the control connection’s IP, compared in canonical form by endpoint (protocols/src/socks/protocol.rs), so an IPv4-mapped IPv6 address is the IPv4 one. A datagram from any other sender is dropped before it is parsed and does not reset the association’s RELAY_IDLE_TIMEOUT.
  • Port pinning. The first datagram forwarded (one that parses and carries a payload) pins the port, and replies go to that address alone. A request that names the control connection’s own IP with a non-zero port pins that port up front. A request naming any other source is set aside, neither trusted nor refused.
  • No client to hold to. Over a Unix socket source is None, so the request must name its exact IP address and a non-zero port. A request that does not, and a hub whose family cannot receive from the client (hears: an IPv4 or IPv4-mapped hub hears only IPv4, the unspecified IPv6 hub both, any other IPv6 hub only IPv6), get the SOCKS5 reply STATUS_NOT_ALLOWED (0x02) before any socket is bound.

On the first datagram it forwards, the driver asks the same AppConnector for a UDP flow, with the control connection’s source as the flow’s source, and gets the same FanOutLink, which it drives from its own select loop. serve_connection built that connector with charging_datagrams(): a SOCKS association’s datagrams never cross the control stream, so each sub-link’s payload is added to the session’s wire instead.

Deeper: Outbounds, UDP fan-out and balancers, Route model, SOCKS: the association’s client, mux.cool and XUDP for UDP inside a mux carrier.

Neither inbound accepts TCP sockets, so steps 1 to 4 are replaced by the inbound’s own run loop in the protocols crate, wrapped by a supervisor task. Both loops take a closure that, given a client address, builds the AppConnector for that client, and from Effect::Open on everything above applies unchanged.

Hysteria 2 (run_hysteria_inbound → Hy2Inbound::run) TUN (run_tun_inbound → TunInbound::run)
Accepts QUIC connections on one UDP socket, each under a max_connections place (a full or stopping listener refuses the handshake) TCP connections and UDP flows terminated by a userspace IP stack on the device
Prepared the endpoint is opened on the bound socket in the apply’s prepare (Hy2Inbound::open) the device handle (tun::Device: a descriptor on Unix, a share of the Wintun session on Windows) is duplicated and registered in prepare (TunInbound::prepare)
Session one per QUIC connection: make(ip, ConnectionBytes) opens it with Wire::quic, which counts the connection’s UDP bytes, and returns the connector with the session’s token, whose cancellation closes that connection none: a device admits no users, so its flows carry Principal::anonymous() and a connector without a session
Authentication once per QUIC connection, over HTTP/3 none
Send rate each QUIC connection is accepted with a congestion controller of its own (Negotiated), which switches to Brutal when a send rate is agreed at /auth; see Congestion control the outbound’s
IPv6 carried like IPv4 screened at the SYN, see below
TCP one ProxyServerRuntime over Hy2StreamCore per classified proxy stream, each under a max_circuits place one ProxyServerRuntime over PassthroughCore per TCP connection, under a max_flows permit
UDP when the listener relays UDP, one runtime per authenticated QUIC connection over Hy2UdpCore and QuicDatagrams when UDP is enabled, one runtime per client source over TunUdpCore and TunUdpLink, under a max_flows permit, fed that source’s new flows through a FLOW_QUEUE (16) channel
Changes applied inside the running endpoint (set_connection_config, set_authenticator, set_quic, set_obfs) a new handler restarts the runtime on a duplicated handle
On stop the run loop drains: new clients are refused, live connections run on; after the last one Hy2Inbound::shutdown releases the port the runtime is cancelled and every flow on the device ends; TunInbound::shutdown waits for the device to close

make reads the inbound’s tag per connection, because a listener kept across an apply may serve a renamed inbound. A client that finishes its QUIC handshake just as the listener stops gets a connector without a session and a token that is already cancelled, so no session escapes the close of a removed inbound. At shutdown, once the root token is cancelled, run_hysteria_inbound closes the endpoint under the draining run loop, so a client still in its QUIC handshake does not hold shutdown up.

PassthroughCore knows its destination before the first byte, because the IP stack already knows where the client is going. It opens on the first event and relays verbatim, with optional sniffing. Since a runtime delivers no event before the client speaks, TUN’s serve_stream applies the same silent-client watchdog as drive: HANDSHAKE_TIMEOUT around each step until the core is established (tun: the client never spoke).

Before ipstack sees a packet from the client, the device judges it (protocols/src/tun/ipv6.rs → Ipv6Screen). ipstack completes every handshake it is shown, and a flow is dialed only after the client has spoken, so a connection that cannot be relayed would look established and then die mid-request. A RST to its SYN is a refused connect instead, which a client answers at once by trying its next address: IPv4, for a name that has both.

  • ipv6 = false (TunSpec.ipv6, TunInbound::without_ipv6): every IPv6 TCP SYN is answered with an RST, and every other IPv6 packet is dropped.
  • Otherwise run_tun_inbound installs ipv6_unreachable (TunInbound::screening_ipv6, supervisor/src/serve.rs), which asks Plane::ipv6_unreachable about each IPv6 SYN, with the inbound’s tag and the client as the source, on the plane current when the SYN arrives. The SYN is answered with an RST only when every target the route table may send the flow to is known to lack IPv6, counting, when the inbound sniffs, every earlier rule a sniffed domain could still reach (CompiledRoutes::every_outcome). A flow to port 53 is always reachable when the DNS service exists. Only a freedom and a WireGuard outbound can tell (Outbound::lacks_ipv6): freedom lacks it when its address-family strategy rules IPv6 out or the kernel has no route there, asked through a probe socket under its socket policy (UdpDialer::source_toward), and WireGuard whether its address-family policy allows IPv6 and its tunnel has an IPv6 address to send from (WgConnector::reaches); any other outbound is assumed to reach IPv6.

The Hysteria 2 front-end defaults come from protocols/src/hysteria/server/config.rs: DEFAULT_MAX_CONNECTIONS 262,144 and DEFAULT_MAX_CIRCUITS 4,194,304. Its QUIC defaults are QuicOptions::server() in protocols/src/hysteria/config.rs.

Deeper: Listeners and the serve loop, Hysteria 2 server, TUN.

etemenanki-app, katana and the ffi consume the same Supervisor and run the pipeline above unchanged. None of them has a connector, an accept loop or a meter of its own. Each lowers its configuration into a Spec, and the spec decides what the pipeline serves:

etemenanki-app katana etemenanki-ffi
Lowers a TOML config (app/src/lower.rs) each panel node, its users and its audit rules (src/lower/) a client config for a phone (ffi/src/client.rs)
Users keyed by UserName: each user’s email or username Uid, the panel’s user id; the principal’s label is the uid UserName
Listeners whatever the config lists one inbound per node, bound at lower::inbound::bind_host(listen_ip), which binds 0.0.0.0 as :: where one IPv6 socket also takes IPv4 client inbounds, and the platform’s TUN device as TunSource::Fd
Grace at shutdown SHUTDOWN_GRACE, 5 s (app/src/main.rs) Duration::ZERO (src/manager/node.rs) STOP_GRACE, 2 s (ffi/src/proxy.rs)

katana puts its node-specific behaviour into the spec as well:

  • Node kinds. A panel node lowers to one inbound: VMess, VLESS (over REALITY too, with or without Vision), Trojan, Shadowsocks (plain, or inside TLS, WebSocket or gRPC), AnyTLS, SOCKS or HTTP with TLS only, sss, or Hysteria 2. Every one of them meets the path above.
  • Destination audit. Each panel rule id becomes a blackhole outbound of its own, audit#<id>, and a route in front of the node’s own rules that sends the domains its patterns match there (src/rule.rs → audit_routes), so a flow to an audited name is routed to that blackhole (step 6) and goes no further. katana records no hit and reports none to its panel. Rules match domain names only, requested or sniffed.
  • Speed limits. Each user’s UserSpec::speed_limit is the limit the panel sends for that user, or [node.api] speed_limit instead whenever that is set (the panel clients read it into every user, src/api/newv2board.rs and src/api/helium.rs); zero is none. The supervisor paces every flow of the user against it (step 9).
  • The client’s address. Every TCP inbound katana lowers sets proxy_protocol (src/lower/inbound.rs → lower_inbound), so its listener reads a PROXY protocol v2 header when one is sent (step 2).
  • Connections a relay hands over. [node.controller] handoff_dir gives every stream node a handoff socket at <handoff_dir>/<port>.sock, or <handoff_dir>/<listen_ip>-<port>.sock when listen_ip is one address rather than all, mode 0o660, in the group handoff_group names (src/lower/inbound.rs → handoff), so a relay on the same host can hand it the client sockets it accepts (step 2). A Hysteria 2 node gets none. etemenanki-app and the ffi set no handoff.
  • The client behind a reverse proxy. [node.controller] real_ip_header with real_ip_from (both or neither) lowers to InboundSpec::real_ip on a WebSocket node only (src/lower/inbound.rs → real_ip), so the upgrade’s header names the client on a connection from an address in real_ip_from (step 2). etemenanki-app and the ffi set no real_ip.
  • Device limits and IP bans. Under [node.controller] enable_device_limit, each user’s UserSpec::device_limit is the device limit the panel sends for that user, which a helium panel’s users answer says once for every user (step 6), and the spec’s Policies::ip_ban bans an IP once ban_max_failures of its authentications fail within ban_window_secs, for ban_secs (defaults 30, 120 s and 300 s; src/lower/mod.rs → policies). carrier_max_failures (default 8) closes a gRPC connection after that many failed streams in a row (step 2).
  • VMess clock check. disable_vmess_clock_check lowers a VMess inbound with clock_check: false.
  • Hysteria 2 rates. A Hysteria 2 inbound takes the panel’s up_mbps, down_mbps and ignore_client_bandwidth, each overridden by [node.hysteria] when set there, and the congestion fallback that block names. On a helium node the panel’s rates stand, and the panel also says whether UDP is relayed, with its idle timeout, and what the masquerade answers: [node.hysteria] may name the congestion fallback alone.
  • Usage. katana reads the per-user usage the sessions reported with Supervisor::take_usage and reports it to its panel. A helium node under enable_device_limit also reports the client IPs each user’s sessions came from: spawn_client_ips (src/manager/node.rs) reads them off the tracker’s FlowEvent::Opened events, and each report adds those of the sessions still open (Supervisor::sessions).
  • Removed users. A user the panel no longer lists is dropped from the node’s user set on the next apply, and the default UserRemovalPolicy::Close closes their sessions through Sessions::revoke; the other users’ connections keep running.

Deeper: etemenanki-app: from TOML to a spec, Lowering a node into a spec, Destination audit, ffi.

A reload or a panel update is an apply of a new spec. The apply ends nothing by itself: a connection is affected only when the plan names something it depends on, and then only as the policy for that step says.

Change Step What the connection sees
A route changes PublishPlane An open TCP flow keeps the target it was opened on. The next flow, the next mux sub-flow and the next UDP packet are routed on the new plane. A client that switched a node calls Supervisor::close_rerouted after the apply to close the live flows the new routing sends to another outbound (see Closing what a route change moved).
An outbound is rebuilt or removed Drain, with the outbound’s DrainPolicy (default Keep) Keep leaves the flows on the old version until they end. Close kills them through the tracker (Target::close_flows → Tracker::kill_where), so each fails at its next read or write with the flow was killed, and a flow still dialing is killed when it lands (close_if_drained). CloseAfter(grace) does so after grace. A WireGuard outbound’s flows are always closed with Close, whatever the policy.
A user is removed, or their credentials change the inbound’s UserRemovalPolicy (default Close), applied by Sessions::revoke Close cancels the user’s sessions on that inbound; Keep leaves them running; CloseAfter(grace) cancels them after grace. A session that has not bound yet and presents the revoked principal is refused at its first flow.
A user’s device limit changes published when an apply or a user edit commits (Actor::publish_limits → Sessions::set_device_limits) A lowered limit closes no session; it holds from the next session that binds.
An inbound is removed, or renamed on the same bind StopAccepting and CloseSessions Every session of the old tag is cancelled.
An inbound moves to another bind Bind and StopAccepting The old listener stops accepting; its connections run on.
A handoff socket is added, moved or removed, or its mode or group changes Bind or StopAccepting for that bind alone, and SwapHandler on the listener kept The TCP listener keeps its socket. Every open connection runs on, the handed-over ones included; a socket with a new mode or group is bound afresh, under a staging name beside its path, and moved over the path at commit, so a refused apply leaves the running one in place.
An inbound’s protocol or settings change on the same bind SwapHandler The listener and its socket are kept; connections accepted before keep the handler they started with, new ones get the new handler. A REALITY setting, an AnyTLS padding scheme and sss settings change this way too.
A Hysteria 2 obfuscation change Disrupt Refused with ApplyError::Disruptive unless the front end passes ApplyOptions::allow_disruptive. etemenanki-app refuses such a change on reload, and a restart applies it.
A TUN change — etemenanki-app refuses a TUN change, and a restart applies it.

Outside an apply, Supervisor::close(Selector) cancels the tokens of the sessions it selects, and a flow killed through the tracker fails its next read or write with the flow was killed, which the runtime delivers to the core as Event::OutboundError for that key. A killed mux sub-flow or UDP sub-link ends alone; a killed single flow ends its connection through on_outbound_gone.

Supervisor::shutdown(grace) stops every listener, waits up to grace for the tasks on the tracker, then cancels the root token, which cancels every session token still live and drops every connection task.

Deeper: Planning and applying a change, Users, principals and sessions, The plane: routing each flow, Reloading etemenanki-app.

Invariant Mechanism Pinned by
A socket is admitted only with a free live-connection place, and the place is held for as long as any task serving the socket lives live.try_acquire_owned() before spawning; the Arc<OwnedSemaphorePermit> rides into every serve_connection no dedicated test
A session outlives its listener session tokens are children of the root, not of the listener; Sessions::open checks the stop token under the registry lock supervisor/tests/unit/plan.rs → a_bind_change_binds_anew_and_stops_the_old_listener_without_closing_sessions; supervisor/tests/hot_swap.rs → a_protocol_change_on_the_same_port_keeps_the_socket_and_old_connections; supervisor/tests/unit/session.rs → a_stopped_listener_opens_no_session, cancelling_the_root_cancels_every_session
An apply that keeps an inbound does not touch its connections Step::Reuse; a user table is stored only when the admissions changed supervisor/tests/hot_swap.rs → an_established_connection_survives_an_apply_that_keeps_its_inbound; app/tests/integration/e2e_reload.rs → an_open_connection_keeps_transferring_across_a_reload
One gRPC connection yields one stream per HTTP/2 stream; an idle one is told to go away, and a silent one is dropped the transport calls sink per accepted stream; Liveness with the ReadClock stamped by Heard protocols/tests/pipeline/transports.rs → one_grpc_connection_carries_many_streams; protocols/tests/unit/transports/accept.rs → a_connection_that_opens_no_stream_is_given_up_on, an_idle_connection_is_told_to_go_away, a_refused_stream_does_not_restart_the_idle_deadline, a_peer_still_sending_is_kept_while_its_pong_waits_behind_a_slow_downlink, a_peer_that_goes_silent_is_dropped_once_a_ping_goes_unheard, a_peer_that_sends_but_never_reads_is_dropped_once_its_pong_is_overdue
A PROXY v2 header, when sent, names the session’s client; a connection without one is its own client proxy_protocol::read_v2 in serve_socket supervisor/tests/guard.rs → a_proxy_header_names_the_client_and_a_bare_connection_is_its_own
A handed-over socket is taken only when the whole message checks out, and anything else is refused and stays the relay’s handoff::receive: one message, exactly one descriptor, a connected IP stream socket, a whole header with nothing after it supervisor/tests/handoff.rs → a_malformed_handoff_is_refused_and_the_connection_stays_the_relays
A handed-over socket is served as one the TCP listener accepted, with the client its header names Connection::serve_tcp, shared by both supervisor/tests/handoff.rs → a_handed_over_connection_is_served_with_the_client_its_header_names, a_handed_over_client_failing_to_authenticate_is_banned, tls_grpc_and_vmess_run_over_a_handed_over_connection
An IP that keeps failing to authenticate is turned away at its next TCP connection, and other IPs are not drive calls Report::failed on a PermissionDenied core error; Guard::is_banned in serve_socket supervisor/tests/guard.rs → an_ip_failing_to_authenticate_is_turned_away_and_others_are_not; supervisor/tests/unit/guard.rs → an_ip_is_banned_at_the_limit_and_until_the_ban_ends, failures_outside_the_window_start_a_new_count, a_success_clears_the_count_but_not_a_ban, a_sweep_drops_what_no_longer_counts, without_a_ban_policy_nothing_is_counted
An IPv4 client is counted and banned by its address, an IPv6 client by its /64, and an IPv4-mapped address as its IPv4 BanKey::of in Guard::failed, Guard::succeeded and Guard::is_banned supervisor/tests/unit/guard.rs → an_ipv6_client_is_counted_and_banned_by_its_64, a_success_anywhere_in_the_64_clears_its_count, an_ipv4_mapped_address_counts_as_its_ipv4
A trusted proxy’s header names a WebSocket session’s client; anyone else’s is ignored, and the named client is the one the device limit and the IP ban count real_ip_source in serve_socket’s sink, RealIpSpec::trusts, Session::set_source supervisor/tests/guard.rs → a_trusted_proxys_forwarded_header_names_the_websocket_client, a_forwarded_header_from_anyone_untrusted_is_ignored, the_device_limit_counts_the_forwarded_client, a_forwarded_client_failing_to_authenticate_is_banned_and_others_are_not; supervisor/tests/unit/serve.rs → a_trusted_proxys_header_names_the_client_and_no_one_elses_does
The next VMess stream of a gRPC connection tries the user the connection’s last authenticated stream matched Carrier::succeeded keeps the user, Report::carrier_hint hands it on, VMessCore::with_hint takes it supervisor/tests/unit/guard.rs → a_carrier_hands_its_last_user_to_the_next_stream; protocols/tests/unit/vmess/core.rs → a_core_hands_on_the_user_it_matched
A gRPC connection whose streams keep failing to authenticate is closed the connection’s Carrier, shared by every stream’s Report supervisor/tests/guard.rs → a_grpc_connection_whose_streams_keep_failing_is_closed; supervisor/tests/unit/guard.rs → a_carrier_is_closed_after_failed_streams_in_a_row
A REALITY socket that is not a client is relayed to the cover site with its handshake permit back and its live permit held, ends with its session, and is never counted by the guard Disposition::Camouflage in Connection::serve_tcp supervisor/tests/unit/serve.rs → a_camouflaged_connection_gives_its_handshake_permit_back
An sss stream refused before authentication gets no reply: silence until it closes, or the fallback’s service sss::accept and Rejection::run in serve_sss supervisor/tests/sss.rs → a_probe_gets_silence_until_it_closes, a_probe_is_handed_to_the_fallback, mismatched_chains_carry_nothing
An sss connection’s future holds one runtime: the gate and what follows it are states of one future serve_sss returns gate.then(…) supervisor/tests/unit/serve.rs → an_sss_connections_future_holds_one_runtime_and_little_besides
Every stream of an AnyTLS session counts toward its one user, a wrong password counts toward the IP ban, and removing the user ends the session with every stream the ordinary drive path over AnyTlsCore supervisor/tests/anytls.rs → streams_of_one_session_count_exactly_toward_its_user, a_wrong_password_counts_toward_the_ip_ban, removing_the_user_ends_the_session_and_every_stream
The handshake deadline arms once, then the idle deadline re-arms on every byte event Timing::touch, Timing::enter protocols/tests/unit/core/mod.rs → timing_arms_handshake_once_then_idle_per_byte_event, timing_reports_handshake_and_sniff_expiry_to_the_core
Bytes forwarded in the same batch as Open wait for the connect, and held bytes survive until applied drive_effects stops at a Connecting slot; held ranges resolve at apply time concepts/tests/runtime.rs → held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites
The read buffer grows to BUF_SIZE and no further; a frame larger than that fails the connection make_room doubles the buffer up to BUF_SIZE; RuntimeError::FrameTooLarge once it is saturated concepts/tests/runtime.rs → frame_larger_than_the_buffer_is_an_error, a_frame_past_the_first_read_buffer_is_relayed_whole_both_ways, a_frame_past_the_grown_buffer_is_still_an_error
The flow’s own source wins over the listener’s flow.source.or(ctx.source) in route_target supervisor/tests/unit/router.rs → the_circuits_own_source_wins_over_the_listeners, without_one_the_listeners_source_is_used, a_circuit_source_works_with_no_listener_source
Route context reaches the matchers route_target sets inbound_tag, source and network app/tests/integration/e2e_route_context.rs → inbound_tag_selects_the_route, source_cidr_matches_the_client_address, network_separates_tcp_from_udp
A sniffed domain routes an IP-addressed flow SniffPrefix sets flow.sniffed; RouteTarget::sniffed_domain app/tests/integration/e2e_sniff.rs → an_http_host_routes_an_ip_addressed_flow, a_tls_sni_routes_an_ip_addressed_flow, turning_sniffing_off_stops_the_domain_rule_matching
A route change reaches the next flow, sub-flow and UDP packet, never an open stream the plane is loaded once per connect and once per packet supervisor/tests/hot_swap.rs → a_route_change_reaches_the_next_udp_packet_but_not_an_established_tcp_flow, a_route_change_reaches_the_next_mux_sub_flow_of_a_live_session
Port 53 goes to the DNS service when there is one, except the service’s own queries Plane::route against Plane::route_upstream supervisor/tests/unit/plane.rs → port_53_is_intercepted_except_for_the_services_own_queries
Removing a user closes only that user’s sessions, and refuses them afterwards Sessions::revoke; Session::admit checks the revocation supervisor/tests/hot_swap.rs → removing_a_user_closes_only_their_sessions_and_refuses_them_after; supervisor/tests/unit/session.rs → a_session_whose_first_flow_presents_a_revoked_principal_is_refused_under_every_policy; app/tests/integration/e2e_reload.rs → a_reload_that_removes_a_user_closes_only_their_connections
A user’s sessions come from no more IPs than their device limit Inner::over_device_limit when a session binds supervisor/tests/guard.rs → a_users_sessions_come_from_no_more_ips_than_their_device_limit; supervisor/tests/unit/session.rs → a_session_from_one_ip_too_many_is_refused_and_closed, an_ip_frees_its_slot_when_its_last_session_ends, the_limit_is_per_user_and_absent_means_any, a_source_told_before_binding_is_the_one_counted
A replaced outbound’s flows stay unless its drain policy closes them, and a flow dialing through a drain is closed when it lands Target::close_flows sets the version’s drained flag and kills its flows through Tracker::kill_where; close_if_drained after meter_stream and meter_datagram supervisor/tests/hot_swap.rs → a_changed_outbound_keeps_its_old_flows_unless_drained_with_close, a_drain_with_close_ends_a_udp_sub_link_but_not_its_association; supervisor/tests/unit/plane.rs → a_balanced_stream_is_closed_by_its_members_drain_not_the_balancers, a_flow_dialing_through_a_drain_is_closed_when_it_lands
Killing one flow ends that flow alone the kill flag in Metered; the core’s on_outbound_gone for that key supervisor/tests/tracking.rs → killing_one_mux_sub_flow_leaves_its_siblings_and_the_carrier
A session’s wire counts what its client’s side carried drive adds each step’s transport bytes; WireCounted and charged datagrams for SOCKS; Wire::quic for Hysteria 2 supervisor/tests/tracking.rs → mux_sub_flows_and_their_session_count_exactly_what_moved, a_udp_association_counts_each_sub_link_and_charges_its_session, a_hysteria2_session_bills_its_quic_connections_bytes
Connected means the upstream really accepted the flow ProxyClientConnecting waits for poll_connected (dial, handshake, flush) concepts/tests/client.rs → upstream_dial_failure_is_connect_failed_not_connected, refused_upstream_handshake_is_connect_failed_not_connected
A reply is staged only once the target is up, except when sniffing an IP target for a protocol whose client waits reply staged in the Event::Connected arm protocols/tests/unit/vless/core.rs → tcp_request_opens_and_replies_only_once_connected, a_refused_connect_closes_without_a_reply; protocols/tests/unit/http/core.rs → connect_to_a_domain_answers_200_once_connected, connect_refused_answers_502_and_closes, connect_to_an_ip_with_sniffing_replies_early_and_holds_the_prefix; protocols/tests/unit/vmess/core.rs → tcp_request_opens_and_replies_once_connected
A connect failure is an event, not a runtime error forget_key then Event::ConnectFailed concepts/tests/runtime.rs → connect_failure_reaches_the_core_as_an_event; protocols/tests/unit/trojan/core.rs → connect_failure_ends_the_connection_without_a_reply
A stalled outbound stalls the uplink instead of buffering it a queued forward pins the transport buffer concepts/tests/runtime.rs → stalled_outbound_holds_uplink_but_not_other_downlink
A proxy outbound runs inside the connection’s task ProxyClientRuntime is the outbound’s AsyncRead/AsyncWrite concepts/tests/client.rs → server_runtime_relays_through_a_client_runtime_in_one_task
A packet a proxy outbound sends reaches a wire that holds writes until a flush ProxyClientRuntime flushes after each packet (flush_packets) concepts/tests/client.rs → a_packet_reaches_a_wire_that_holds_writes_until_flushed
Each EOF half-closes the other side, and the connection finishes after both Passthrough, Effect::Shutdown, Effect::ShutdownTransport concepts/tests/runtime.rs → half_close_propagates_both_ways_and_finishes; protocols/tests/unit/core/mod.rs → passthrough_half_closes_each_side_and_finishes_on_the_second
UDP is routed per packet and replies merge back into one association FanOutLink app/tests/integration/e2e_udp_route.rs → one_association_routes_each_peer_separately, replies_from_several_peers_merge_back_correctly
A TUN client’s IPv6 connection is refused at its SYN when no target it may reach carries IPv6, or when the device does not relay IPv6 Ipv6Screen; Plane::ipv6_unreachable over CompiledRoutes::every_outcome protocols/tests/unit/tun/ipv6.rs → with_ipv6_off_a_syn_is_answered_with_a_reset_the_client_accepts, with_ipv6_off_everything_else_of_ipv6_is_dropped_and_ipv4_passes, with_ipv6_on_only_a_syn_the_gate_calls_unreachable_is_refused; supervisor/tests/unit/plane.rs → ipv6_is_unreachable_only_when_every_possible_target_lacks_it
A SOCKS UDP association hears only its control connection’s client, and a request cannot widen that ExpectedSender::admits and pin; endpoint for both ends protocols/tests/unit/socks/server.rs → only_the_control_peer_is_heard_and_its_first_datagram_pins_the_port, an_ipv4_mapped_address_is_the_ipv4_one, a_request_naming_the_peer_pins_its_port_up_front, a_request_naming_any_other_source_is_set_aside, over_a_unix_socket_the_request_must_name_the_exact_source, a_relay_that_cannot_hear_the_client_is_refused; protocols/tests/pipeline/socks.rs → udp_association_ignores_another_ip, udp_association_ignores_another_port_once_pinned, udp_association_holds_to_the_port_the_request_names, udp_association_sets_aside_a_source_it_cannot_hold_to, udp_association_is_not_widened_by_the_request, udp_association_over_a_unix_socket_needs_its_exact_source, udp_association_refuses_a_relay_that_cannot_hear_the_client, udp_link_ignores_datagrams_not_from_the_relay, udp_link_on_a_dual_stack_socket_hears_an_ipv4_relay; protocols/tests/unit/socks/protocol.rs → endpoint_sees_through_ipv4_mapping_and_ignores_flow_info
katana’s node behaviour rides on the same pipeline the spec: user sets keyed by uid, audit routes, speed limits, device limits, the IP ban policy, the removal policy, Hysteria 2 rates katana tests/unit/e2e.rs → a_retired_user_stops_while_the_rest_keep_their_connections, a_users_speed_limit_paces_their_traffic, a_users_clients_come_from_no_more_ips_than_their_device_limit, an_ip_failing_to_authenticate_is_banned_and_others_are_served, a_panel_that_sets_rates_has_the_node_send_at_the_agreed_one, an_sss_node_relays_through_its_chains_and_meters
Where What happens What the client sees
A semaphore is empty at accept socket dropped, debug log the connection closes before any byte
The listener stops as a socket is accepted Sessions::open returns None; the loop ends the connection closes
Accept error 100 ms backoff unless ConnectionAborted or Interrupted nothing; the next accept continues
TCP connection from an IP the guard has banned serve_socket returns before the transport (Guard::is_banned) the connection closes before any byte
A trusted proxy’s real-IP header names a banned client the accept sink drops the stream (Guard::is_banned) the connection closes after the upgrade, before any request byte is read
Transport handshake fails or exceeds 10 s serve_socket logs inbound transport failed TLS or upgrade failure, or a close
A REALITY socket that is not a client, or whose handshake fails before the server’s flight Disposition::Camouflage: the handshake permit goes, the relay runs under the session, nothing reaches the guard the cover site’s own answers
REALITY’s cover site cannot be dialed inbound transport failed; a warning at most once a minute the connection closes
An sss header that is incomplete within T_h or B_pre, does not decode, is malformed or names no known user sss::accept refuses; a debug log naming the category; nothing reaches the guard silence until it closes or T_h passes (drain), or the fallback’s service
gRPC stream on an unknown path REFUSED_STREAM that stream is reset; the connection stays up
gRPC connection with no streams for 30 s Liveness judges it idle; graceful_shutdown sends a GOAWAY told to go away; a stream opened before the GOAWAY arrives is still served
gRPC peer silent for 20 s after a PING, or a PONG 300 s overdue Liveness judges it dead; the connection is dropped every stream on it ends
carrier_max_failures streams in a row on one gRPC connection fail to authenticate the connection’s Carrier cancels the carrier’s token the connection closes
Silent client drive times out after HANDSHAKE_TIMEOUT close
Malformed request or unknown user the core returns an error; RuntimeError::Core. A PermissionDenied error before establishment is a refused credential, which drive reports with report.failed() close, with no protocol reply; past the ban policy’s limit, the IP’s next TCP connections close at once
First flow presents a revoked principal, or the session was already closed Session::admit refuses, and the session’s token is (or already was) cancelled the connection closes
First flow comes from one IP too many for the user’s device limit Session::admit refuses with PermissionDenied and cancels the session’s token the connection closes
IPv6 TCP SYN on a TUN device with ipv6 = false, or with no target that carries IPv6 Ipv6Screen answers with an RST before ipstack sees the SYN a refused connect; the client tries its next address
Routing cannot fail: the default route always answers —
SOCKS UDP ASSOCIATE with no client the relay could hold to (a Unix-socket request without an exact address and port, or a udp_bind in a family the client cannot reach) ExpectedSender::new fails before the hub is bound; PermissionDenied SOCKS5 reply 0x02, then close
SOCKS relay datagram from anyone but the association’s client dropped before parsing, without resetting the idle timer; the association carries on nothing
Dial or upstream handshake fails Event::ConnectFailed; the core answers HTTP 502, a SOCKS refusal code, a Hysteria refusal, or a close
Outbound read or write error during relay, a drain with Close, or a kill the runtime drops the key, then Event::OutboundError ShutdownTransport and Finish: a clean close after staged bytes; for a mux sub-flow, an End frame for that sub-flow only
Transport read or write error RuntimeError::Transport ends the runtime the socket is already gone
Idle for RELAY_IDLE_TIMEOUT Expired::Idle pushes Finish staged bytes drain, then close
The session’s token is cancelled (user removal, inbound removal, Supervisor::close, shutdown) spawn_until drops the connection’s future an abrupt close, with no protocol-level goodbye

Cancellation is by drop throughout. Nothing in the path needs an explicit shutdown call: dropping the runtime closes the transport and every outbound, dropping the Arc permit handles returns the places to their semaphores, dropping a flow’s wrapper deregisters it, and dropping the last session handle ends the session. Protocol and transport code must therefore keep its cleanup in Drop, never after an .await. A Hysteria 2 session is closed by the protocols crate instead, with a QUIC application close.

Constant Value Defined in Applies to
MAX_LIVE_CONNECTIONS_PER_INBOUND 4,194,304 supervisor/src/serve.rs live sockets per stream inbound, its TCP listener and handoff socket together
MAX_HANDSHAKES_PER_INBOUND 204,800 supervisor/src/serve.rs connections in their handshake per stream inbound, its TCP listener and handoff socket together
ACCEPT_ERROR_BACKOFF 100 ms supervisor/src/serve.rs sleep after a non-transient accept error
PROXY_HEADER_TIMEOUT 10 s supervisor/src/serve.rs reading a PROXY protocol v2 header, on an inbound that reads one
RECEIVE_TIMEOUT 5 s supervisor/src/system/handoff.rs a relay’s message on a handoff socket’s control connection
MAX_V2_LEN 4096 bytes protocols/src/transports/proxy_protocol.rs the longest PROXY protocol v2 header taken, TLVs included
SWEEP_INTERVAL 30 s supervisor/src/guard.rs dropping the guard’s records of IPs neither banned nor within their window
TRANSPORT_HANDSHAKE_TIMEOUT 10 s protocols/src/transports/accept.rs TLS, WebSocket upgrade, HTTP/2 handshake; for REALITY, the dial of the cover site and the decision
DEFAULT_HEADER_TIMEOUT 10 s protocols/src/sss/server.rs an sss stream’s header time T_h when none is configured
MAX_STREAMS 256 protocols/src/anytls/core.rs streams one AnyTLS session holds at once; a SYN past it is answered with a FIN
H2_IDLE_TIMEOUT 30 s protocols/src/transports/grpc/settings.rs a served gRPC connection with no streams, before its GOAWAY
H2_KEEPALIVE_INTERVAL, H2_KEEPALIVE_TIMEOUT 60 s, 20 s protocols/src/transports/grpc/settings.rs the PING a served gRPC connection sends, and the silence after it that ends the connection
H2_PONG_TIMEOUT 300 s protocols/src/transports/grpc/settings.rs a PONG still owed while the peer is heard from
TCP_KEEPALIVE_IDLE, …_INTERVAL, …_RETRIES 120 s, 30 s, 3 protocols/src/transports/keepalive.rs every socket InboundTransport::accept receives
HANDSHAKE_TIMEOUT 10 s protocols/src/core/mod.rs drive’s watchdog, the core’s handshake deadline, the SOCKS handshake, TUN TCP flows
SNIFF_TIMEOUT, SNIFF_LIMIT 300 ms, 4 KiB protocols/src/sniff/mod.rs the sniffing window
RELAY_IDLE_TIMEOUT 300 s protocols/src/core/mod.rs idle relay, a REALITY camouflage relay and an sss fallback relay
DEFAULT_CONNECT_TIMEOUT 10 s per address environment/src/dial/tcp.rs TCP connects by freedom and TransportConnector
OPEN_STREAM_TIMEOUT 5 s protocols/src/hysteria/connection.rs opening a Hysteria 2 proxy stream
DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_CIRCUITS 262,144, 4,194,304 protocols/src/hysteria/server/config.rs front ends’ defaults for a Hysteria 2 inbound
QuicOptions::DEFAULT_MAX_INCOMING_STREAMS 65,536 protocols/src/hysteria/config.rs a Hysteria 2 server’s default for the concurrent bidirectional streams one connection may open; configurable as quic.max_incoming_streams
WORK_BUDGET 64 units concepts/src/runtime.rs a runtime polled as a Future (the Hysteria 2 runtimes and TUN’s UDP runtimes; drive uses stream mode) yields after this many units
INLINE_EFFECTS 4 concepts/src/core.rs effects stored inline before the list spills to the heap
MAX_SUBS 64 supervisor/src/topology/outbound/udp_fanout.rs open sub-links per UDP association
HTTP_BUF, SOCKS_BUF, TROJAN_BUF, VLESS_BUF 16 KiB supervisor/src/topology/outbound/mod.rs proxy client runtime buffers
VMESS_BUF; SS_BUF; SS2022_BUF 32 KiB; SsStream::BUF_SIZE = 20 KiB; Ss2022Stream::BUF_SIZE = 65,569 supervisor/src/topology/outbound/mod.rs proxy client runtime buffers
SSS_TCP_BUF, SSS_UDP_BUF 16 KiB, 66 KiB supervisor/src/topology/outbound/mod.rs an sss outbound’s TCP and UDP client runtime buffers
EVENT_CAPACITY 1,024 supervisor/src/track/mod.rs flow lifecycle events a slow subscriber may fall behind by
DEFAULT_SAMPLE_INTERVAL 1 s supervisor/src/track/sampler.rs the sampler’s tick
SHUTDOWN_GRACE, STOP_GRACE 5 s, 2 s app/src/main.rs, ffi/src/proxy.rs the grace etemenanki-app and the ffi pass to Supervisor::shutdown

Memory per connection follows from the buffer sizes, which are caps rather than allocations (concepts/src/buffer.rs). A server runtime’s read buffer starts at 2 KiB (INITIAL, or BUF_SIZE if smaller) and doubles as reading uses it up, staging holds nothing until the first stage and then grows with what is staged, and scratch is allocated whole at the first outbound read. A connection that never gets past its handshake holds only the 2 KiB read buffer. One moving data reaches the cap within its first few reads, so at most a VMess connection costs 96 KiB of buffers, an HTTP one 192 KiB, a Shadowsocks 2022 one 3 × 65,569 bytes, and an sss UDP stream 3 × 66 KiB. A proxy outbound adds its client runtime’s two buffers (staging and read), which grow the same way, to at most 2 × 32 KiB for VMess. Each opened outbound adds one KeyWaker Arc and one boxed connect future. The limits across the whole workspace are collected on Limits, timeouts and memory.

  • concepts/tests/runtime.rs drives toy cores through the runtime: open, relay, half-close, connect failure, deadlines, held bytes and backpressure. stream_mode_reports_each_unit_of_work pins the showing_progress mode drive relies on, and deadline_event_lets_the_core_time_out and deadline_is_armed_against_the_tokio_clock pin the timer behind Effect::SetDeadline.
  • concepts/tests/client.rs covers ProxyClientRuntime, the Connected semantics of ProxyClientConnector and the flush after each datagram.
  • protocols/tests/unit/*/core.rs hand-drive each core, most of them through CoreHarness: when it opens, what it stages on Connected and ConnectFailed.
  • protocols/tests/pipeline/ runs each server core in a real runtime against its client codec over loopback sockets; transports.rs covers the TCP, TLS, WebSocket and gRPC inbound transports, including many streams on one gRPC connection, reality.rs the REALITY transport and anytls.rs the AnyTLS core behind a real TLS transport.
  • concepts/src/buffer.rs carries the buffer tests inline, among them read_buffer_starts_small_and_doubles_up_to_n and staging_grows_to_n_and_no_further.
  • supervisor/tests/hot_swap.rs runs applies against live traffic: what a route change, an outbound change (kept, closed, closed after a grace, or a UDP sub-link closed while its association runs on), a user removal, an inbound removal and a protocol change on the same port do to connections that are already open, that close_rerouted after a route change closes only the flows it moved, and that shutdown ends pending grace timers.
  • supervisor/tests/tracking.rs checks flows and sessions end to end: what each flow and each session counts, and that killing one mux sub-flow leaves its siblings and the carrier.
  • supervisor/tests/guard.rs runs the guard against live connections: a PROXY header naming the client, a trusted proxy’s header naming a WebSocket client (and an untrusted one ignored), device limits, an IP turned away after failed authentications, and a gRPC connection closed after failed streams. supervisor/tests/unit/guard.rs pins the ban arithmetic, the ban key (an IPv6 client’s /64, an IPv4-mapped address as its IPv4) and the carrier’s last user.
  • supervisor/tests/anytls.rs and supervisor/tests/sss.rs run real supervisors: an AnyTLS session’s streams billed to one user, a wrong password banned, a user removal ending every stream, a padding change leaving live sessions alone; sss TCP and UDP under transform chains, billing after the transforms, mismatched chains, a probe drained in silence and a probe handed to the fallback. Each also carries TCP and UDP from one supervisor’s outbound to another’s inbound.
  • supervisor/tests/handoff.rs (Unix only) hands real sockets over with sendmsg: one served with the client its header names beside the TCP listener, refusals that leave the relay its connection, a handed-over client banned, TLS, gRPC and VMess over a handed-over socket, a reload adding, moving and removing the handoff socket while every connection runs on, and refused applies that leave a running socket at its path.
  • supervisor/tests/unit/serve.rs → accept_error_backoff_classification pins the accept-error classification, a_camouflaged_connection_gives_its_handshake_permit_back the camouflage branch, a_trusted_proxys_header_names_the_client_and_no_one_elses_does pins real_ip_source, and a_due_hot_tier_is_refreshed_by_the_listener pins the VMess hot-tier refresh; a_connections_future_holds_one_runtime_and_little_besides and a_spawned_connection_is_no_bigger_than_its_future pin the size of a connection’s task, and the three until_cancelled_* tests pin spawn_until. supervisor/tests/unit/session.rs, router.rs and plane.rs pin the session registry and the device limit, route_target, the plane’s DNS interception, drains, the IPv6 screen and Plane::reroutes. drive’s silent-client timeout and the admission semaphores have no dedicated test.
  • app/tests/integration/ starts the real etemenanki-app binary: e2e_route_context.rs, e2e_sniff.rs and e2e_udp_route.rs exercise steps 6 and 7 and the UDP fan-out end to end; e2e_reload.rs checks that an open connection keeps transferring across a reload and that removing a user closes only their connections; e2e_unix.rs covers the Unix path that skips the transport; e2e_hysteria_inbound.rs and e2e_tun.rs cover the two inbounds with their own run loops. e2e_xray_reality.rs (VLESS over REALITY, with and without Vision and with UDP under Vision, against Xray-core in both directions), e2e_singbox_anytls.rs (AnyTLS against sing-box), e2e_xray_wrapped.rs (Shadowsocks, SOCKS and HTTP inside a transport) and e2e_sss.rs (two app processes) run those protocols and transports end to end.
  • katana’s tests/unit/e2e.rs runs the real node behind a fake panel: retiring a user, pacing a user’s traffic, holding a user to a device limit, banning an IP, the Hysteria 2 rates a panel sets, and an sss node relaying through its chains and reporting the user’s bytes.

See Testing for how to run each layer.