Skip to content

Hysteria 2: server

Source files: 62 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/src/hysteria/mod.rs
  • Etemenanki/protocols/src/hysteria/config.rs
  • Etemenanki/protocols/src/hysteria/negotiate.rs
  • Etemenanki/protocols/src/hysteria/server/mod.rs
  • Etemenanki/protocols/src/hysteria/server/config.rs
  • Etemenanki/protocols/src/hysteria/server/endpoint.rs
  • Etemenanki/protocols/src/hysteria/server/inbound.rs
  • Etemenanki/protocols/src/hysteria/server/shim.rs
  • Etemenanki/protocols/src/hysteria/server/io.rs
  • Etemenanki/protocols/src/hysteria/server/datagrams.rs
  • Etemenanki/protocols/src/hysteria/server/authenticator.rs
  • Etemenanki/protocols/src/hysteria/server/masquerade.rs
  • Etemenanki/protocols/src/hysteria/obfs.rs
  • Etemenanki/protocols/src/hysteria/auth.rs
  • Etemenanki/protocols/src/hysteria/protocol.rs
  • Etemenanki/protocols/src/hysteria/quic.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/protocols/src/helpers/crypto.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/supervisor/src/system/listener.rs
  • Etemenanki/supervisor/src/build/inbound.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/topology/spec_plan/plan.rs
  • Etemenanki/supervisor/src/entity/session.rs
  • Etemenanki/supervisor/src/entity/usage.rs
  • Etemenanki/supervisor/src/policy.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/protocols/tests/unit/hysteria/server/shim.rs
  • Etemenanki/protocols/tests/unit/hysteria/server/inbound.rs
  • Etemenanki/protocols/tests/unit/hysteria/server/datagrams.rs
  • Etemenanki/protocols/tests/unit/hysteria/server/authenticator.rs
  • Etemenanki/protocols/tests/unit/hysteria/server/masquerade.rs
  • Etemenanki/protocols/tests/unit/hysteria/obfs.rs
  • Etemenanki/protocols/tests/unit/hysteria/protocol.rs
  • Etemenanki/protocols/tests/unit/hysteria/negotiate.rs
  • Etemenanki/protocols/tests/pipeline/hysteria.rs
  • Etemenanki/protocols/tests/pipeline/hysteria_options.rs
  • Etemenanki/protocols/tests/support/udp_range.rs
  • Etemenanki/app/tests/unit/lower.rs
  • Etemenanki/app/tests/integration/e2e_hysteria_inbound.rs
  • Etemenanki/app/tests/integration/e2e_hysteria_options.rs
  • Etemenanki/supervisor/tests/unit/validate.rs
  • Etemenanki/supervisor/tests/unit/plan.rs
  • Etemenanki/supervisor/tests/hot_swap.rs
  • Etemenanki/supervisor/tests/tracking.rs
  • katana/src/lower/inbound.rs
  • katana/src/lower/mod.rs
  • katana/src/config.rs
  • katana/src/api/mod.rs
  • katana/src/api/helium.rs
  • katana/src/api/hysteria.rs
  • katana/src/api/newv2board.rs
  • katana/src/manager/node.rs
  • katana/tests/unit/lower/inbound.rs
  • katana/tests/unit/lower/spec.rs
  • katana/tests/unit/api/helium.rs
  • katana/tests/unit/api/newv2board.rs
  • katana/tests/unit/manager/node.rs

The Hysteria 2 server is the one inbound in the workspace that does not sit under the generic stream accept loop. A Hysteria 2 client authenticates once per QUIC connection and then opens a bidirectional QUIC stream per proxied TCP connection, with UDP riding the same connection’s datagram channel. No part of that arrives as a single byte stream, so the server owns its UDP socket and its quinn endpoint, and drives one ProxyServerRuntime per proxy stream plus one per connection’s datagram channel. Two QUIC endpoints cannot share a port, and rebinding one drops every client it carries, so the listener is reconfigured inside its running endpoint rather than replaced.

This page is for contributors who change protocols/src/hysteria/server/. It covers the listener (Hy2Inbound) with its two-phase start and in-place reconfiguration, the HTTP/3 dispatch shim that tells proxy streams from HTTP/3 streams, the credential exchange and masquerade, the stream core (Hy2StreamCore), the datagram core (Hy2UdpCore), the authenticator, how etemenanki-supervisor runs the listener, and shutdown. The dialling side, the shared wire primitives and Salamander obfuscation are on Hysteria 2: client. The whole module is behind the hysteria feature of etemenanki-protocols; etemenanki-supervisor enables it.

Component File → symbol Owns
Listener server/inbound.rs → Hy2Inbound, OpenedEndpoint, ConnectionBytes The quinn::Endpoint, the two-phase start (open, run), the accept loop, the connection limit, the per-connection task set, the in-place setters, shutdown and port release.
QUIC setup server/endpoint.rs → server_config, for_connection, bind, from_socket rustls TLS 1.3 with ALPN h3; each accepted connection’s own transport parameters (flow-control windows, stream limit, idle timeout) and congestion controller factory; the switchable Salamander socket wrapper.
Rate negotiation negotiate.rs → server_rx_header, parse_client_rx, server_tx; server/inbound.rs → Rate What the server answers in Hysteria-CC-RX, and the rate it sends to each client.
Dispatch shim server/shim.rs → Hy2H3Conn, classify, PrefixedBidi Reading the first varint of each bidirectional stream and replaying it to h3 when the stream is not a proxy stream.
Credential exchange server/inbound.rs → http3, answer The HTTP/3 server: 233 for a good /auth, the masquerade for everything else.
Proxy streams server/inbound.rs → Hy2StreamCore; server/io.rs → QuicIo TCPRequest parsing, the TCPResponse, sniffing, and the verbatim relay.
UDP server/datagrams.rs → QuicDatagrams, Hy2UdpCore Sessions keyed by session id, reassembly, fragmentation of replies, the idle sweep.
Credentials server/authenticator.rs → Authenticator A shared password, a user:pass table, or a table of opaque credentials.
Masquerade server/masquerade.rs → Masquerade The fixed response every unauthenticated request gets.

What it leaves to others:

  • Routing and dialling. Each connection gets a connector, and a token that closes it, from the caller’s make_connector(ip, bytes) closure. In etemenanki-supervisor that is an AppConnector bound to a session (supervisor/src/serve.rs → run_hysteria_inbound); see In the supervisor and Listeners and the serve loop.
  • Configuration checks. The front ends lower their configuration into a spec, and supervisor/src/build/validate.rs refuses what the spec gets wrong. The user-facing settings are on the Hysteria 2 guide page.
  • Per-user admission. Sessions, and what happens to them when a user is removed, belong to the supervisor (see Swapping the table under a live listener).
protocols/src/hysteria/server/config.rs
pub const DEFAULT_MAX_CONNECTIONS: usize = 262_144;
pub const DEFAULT_MAX_CIRCUITS: usize = 4_194_304;
#[non_exhaustive]
pub struct ServerConfig<T> {
pub authenticator: ArcSwap<Authenticator<T>>,
pub masquerade: Masquerade,
pub sniff: bool,
pub udp: Option<std::time::Duration>,
pub circuit_permits: Arc<Semaphore>,
pub bandwidth: BandwidthConfig,
pub ignore_client_bandwidth: bool,
pub congestion: Fallback,
pub quic: QuicOptions,
}
impl<T> ServerConfig<T> {
pub fn new(
authenticator: Authenticator<T>,
masquerade: Masquerade,
circuit_permits: Arc<Semaphore>,
) -> Self;
}
pub struct ListenerConfig<T> {
pub connection: Arc<ServerConfig<T>>,
pub quic: quinn::ServerConfig,
pub obfs: Option<Obfs>,
pub max_connections: usize,
}

ServerConfig is what one connection needs. Each connection loads the current one as it arrives and keeps it for its whole life. udp is both the switch and the association idle timeout: None means the server tells clients Hysteria-UDP: false and never starts a datagram runtime. circuit_permits is the listener-wide circuit budget. Because a connection holds the config it arrived under, a replacement config shares one budget with it only by carrying the same semaphore. T is the per-user payload carried into routing: every front end runs the listener through etemenanki-supervisor, which uses T = Principal; the tests use ().

The last four fields come from protocols/src/hysteria/config.rs, the types the client uses too (see Hysteria 2: client):

Field Meaning
bandwidth This server’s rates: down is answered to every client in Hysteria-CC-RX, and up caps what it sends to one client. disable_loss_compensation makes Brutal send exactly its rate.
ignore_client_bandwidth Upstream’s ignoreClientBandwidth: answer auto, so neither end sends at a fixed rate, whatever the client declares.
congestion The controller a connection runs when no fixed rate is agreed (Fallback::Cubic, NewReno or Bbr).
quic The transport parameters each connection is accepted with: receive windows, idle timeout, keep-alive, path-MTU discovery and max_incoming_streams.

ServerConfig is #[non_exhaustive], so code outside the crate builds it with ServerConfig::new(authenticator, masquerade, circuit_permits) and sets the rest. new gives no sniffing, no UDP, an empty BandwidthConfig, ignore_client_bandwidth: true, Fallback::Cubic and QuicOptions::server(). Ignoring client bandwidth is the default so that a server given no rates answers auto and never sends at a client’s claimed rate; upstream’s default is false.

ListenerConfig is what a listener starts with. Its quic carries the TLS half only: each connection is accepted with transport parameters built from ServerConfig::quic, so the ones inside quic are never used. All of it can be replaced while the listener runs, through the setters below. A replacement reaches only connections that arrive after it, except obfs, which covers every packet on the socket and so closes the connections it replaces.

protocols/src/hysteria/server/inbound.rs
pub struct Hy2Inbound<T> {
shared: Arc<Shared<T>>,
}
struct Shared<T> {
connection: ArcSwap<ServerConfig<T>>,
salamander: SalamanderSwitch,
endpoint: Mutex<EndpointState>,
max_connections: AtomicUsize,
}
struct EndpointState {
quic: quinn::ServerConfig,
obfs: Option<Obfs>,
endpoint: Option<quinn::Endpoint>,
keyed: CancellationToken,
}
pub struct OpenedEndpoint(quinn::Endpoint, Arc<RecvGate>);
impl<T> Hy2Inbound<T> {
pub fn new(config: ListenerConfig<T>) -> Self;
pub fn set_connection_config(&self, config: Arc<ServerConfig<T>>);
pub fn set_authenticator(&self, authenticator: Arc<Authenticator<T>>);
pub fn set_quic(&self, quic: quinn::ServerConfig);
pub fn set_obfs(&self, obfs: Option<Obfs>) -> io::Result<()>;
pub fn set_max_connections(&self, max: usize);
pub async fn shutdown(&self);
pub fn open(&self, socket: std::net::UdpSocket) -> io::Result<OpenedEndpoint>;
}
impl<T: Send + Sync + 'static> Hy2Inbound<T> {
pub async fn run<C, F>(
&self,
endpoint: OpenedEndpoint,
make_connector: F,
token: CancellationToken,
)
where
F: Fn(IpAddr, ConnectionBytes) -> (C, CancellationToken) + Send + Sync + 'static,
C: Connector<Flow<T>> + Clone + Send + 'static,
C::Future: Send,
C::Stream: Send,
C::Datagram: DatagramLink<Addr = Destination> + Send;
}
#[derive(Clone)]
pub struct ConnectionBytes(quinn::Connection);
impl ConnectionBytes {
pub fn bytes(&self) -> (u64, u64);
}

Hy2Inbound is Clone by hand (no T: Clone bound): its one field is an Arc, so every clone shares the same state. That is how a caller runs run on one handle and keeps another for the setters and shutdown.

Shared field Role
connection The per-connection config. Each connection loads it once, as it arrives, and keeps what it loaded.
salamander The key the endpoint’s socket obfuscates under, loaded per packet (see Hysteria 2: client).
endpoint A parking_lot::Mutex<EndpointState>: what the next endpoint is built from (quic, obfs), the live endpoint, and keyed. They are locked as one, so a setter racing run either reaches the endpoint run built or is what run builds it from.
max_connections The connection limit, read as each connection arrives.

keyed is a CancellationToken that is cancelled when the obfuscation changes. Every connection watches the one current when it arrived, so a switch reaches exactly the connections negotiated under the obfuscation it replaced.

ConnectionBytes reads what one client’s QUIC connection carried: bytes() returns (received, sent) from quinn’s udp_rx and udp_tx statistics, so it counts every UDP datagram of the connection, handshake, QUIC framing and TLS included. The counts never decrease. It holds the connection, so it counts until it is dropped with the connection’s other handles.

protocols/src/hysteria/server/endpoint.rs
pub fn server_config(cert_pem: &[u8], key_pem: &[u8]) -> io::Result<ServerConfig>;
pub fn for_connection(
base: &ServerConfig,
options: &QuicOptions,
congestion: Arc<dyn quinn::congestion::ControllerFactory + Send + Sync>,
) -> io::Result<Arc<ServerConfig>>;
pub fn bind(listen: SocketAddr, config: ServerConfig, obfs: SalamanderSwitch) -> io::Result<Endpoint>;
pub fn from_socket(
socket: std::net::UdpSocket,
config: Option<ServerConfig>,
obfs: SalamanderSwitch,
gate: Arc<RecvGate>,
) -> io::Result<Endpoint>;

server_config builds the TLS half of the configuration:

Setting Constant Value
TLS versions rustls::version::TLS13 only TLS 1.3
ALPN ALPN_H3 h3
Crypto provider rustls::crypto::ring::default_provider() named explicitly
Client certificates with_no_client_auth() none

It also sets transport parameters from QuicOptions::server() with a Cubic factory, which an endpoint would fall back on; the listener never uses them. for_connection(base, options, congestion) clones base and gives the clone transport parameters of its own from hysteria::quic::transport_config(options, congestion), the function the client uses too. The listener calls it for every connection it accepts (see Accepting a connection), so each connection has its own congestion controller factory, which a Negotiated factory requires, and the quic settings of the connection config current when it arrived. With QuicOptions::server():

Setting QuicOptions field Default
Per-stream receive window stream_receive_window 8 MiB (DEFAULT_STREAM_RECEIVE_WINDOW)
Connection receive window conn_receive_window 20 MiB (DEFAULT_CONN_RECEIVE_WINDOW)
Concurrent bidirectional streams per connection max_incoming_streams 65 536 (DEFAULT_MAX_INCOMING_STREAMS; upstream’s defaultMaxIncomingStreams is 1024, raised 64 times for busy nodes)
Idle timeout max_idle_timeout 30 s
Keep-alive keep_alive_period none: a server does not ping
Path-MTU discovery disable_path_mtu_discovery on
Congestion controller factory the congestion argument Negotiated::new(config.congestion), one per connection

Two of the TLS settings are not stylistic, and the comments on tls_config say why:

  • The provider is named rather than taken from rustls::ServerConfig::builder(), because that builder panics when a downstream unifies a second crypto-provider feature into the build.
  • TLS 1.3 is pinned. QuicServerConfig unwraps rustls::quic::ServerConnection::new inside start_session. A configuration without TLS 1.3 would pass QuicServerConfig::try_from and then panic on the first packet of the first connection, inside the accept loop.

Certificate and key errors are prefixed with hysteria2:: could not read the certificate: … and could not read the private key: … for PEM that does not parse, the certificate file contains no certificates, the key file contains no private key, and certificate and key do not match: … when rustls refuses the pair.

from_socket builds an endpoint on a socket someone else bound; binding again here would race a second socket against it on the same port. It sets the socket non-blocking, wraps it for quinn’s Tokio runtime, and always wraps it again in SalamanderSocket::switchable(socket, obfs, gate). While the switch is empty the wrapper passes packets through untouched, offload included, so obfuscation can be switched on, off or to another key under the running endpoint. Salamander is symmetric and holds no per-peer state, so the client’s wrapper serves unchanged. Without a config the endpoint admits nobody, refusing incoming handshakes, until one is set with Endpoint::set_server_config; and it reads nothing off the socket until gate is open. bind binds the address itself and passes a config and an opened gate, for callers that serve at once. The stream limit costs nothing to hold: QUIC enforces it by withholding stream credit, so a client at the limit waits in open_bi instead of having streams accepted and dropped.

protocols/src/hysteria/server/shim.rs
pub enum FrameType {
ProxyRequest,
Http3(u64),
}
pub struct Classified {
pub kind: FrameType,
pub frame_type_bytes: Bytes,
pub rest: Bytes,
}
impl Classified {
pub fn replay(&self) -> Bytes;
}
pub async fn classify<R>(stream: &mut R) -> Result<Classified, StreamErrorIncoming>
where
R: quic::RecvStream<Buf = Bytes> + Unpin;
pub struct AuthState<U> {
user: OnceLock<U>,
}
impl<U> AuthState<U> {
pub fn new() -> Self;
pub fn authenticate(&self, user: U);
pub fn user(&self) -> Option<&U>;
pub fn is_authenticated(&self) -> bool;
}
pub struct PrefixedRecv<R> {
prefix: Bytes,
inner: R,
}
pub struct PrefixedBidi<S, B> {
prefix: Bytes,
inner: S,
_buf: PhantomData<fn() -> B>,
}
pub fn discard<S, B>(stream: &mut S, code: Code)
where
S: quic::SendStream<B> + quic::RecvStream,
B: Buf;
pub type Hy2BidiStream<B> = PrefixedBidi<h3_quinn::BidiStream<B>, B>;
pub struct Hy2Opener(h3_quinn::OpenStreams);
pub struct Hy2H3Conn<B: Buf> {
inner: h3_quinn::Connection,
classify_tx: mpsc::Sender<h3_quinn::BidiStream<B>>,
h3_ready_rx: mpsc::Receiver<Hy2BidiStream<B>>,
}
impl<B: Buf> quic::Connection<B> for Hy2H3Conn<B> {
type RecvStream = h3_quinn::RecvStream;
type OpenStreams = Hy2Opener;
// poll_accept_bidi, poll_accept_recv, opener
}

Hy2H3Conn implements h3’s quic::Connection over an h3-quinn connection, so h3::server::Connection runs on top of it without knowing that some streams are taken out of its accept path. The section Classifying streams explains the design.

protocols/src/hysteria/server/io.rs
pub struct QuicIo<S> {
stream: S,
pending: Bytes,
finished: bool,
}
impl<S> QuicIo<S> {
pub fn new(stream: S, prefix: Bytes) -> Self;
pub fn into_inner(self) -> S;
}
impl<S> AsyncRead for QuicIo<S> where S: quic::RecvStream<Buf = Bytes> + Unpin { /* … */ }
impl<S> AsyncWrite for QuicIo<S> where S: quic::SendStreamUnframed<Bytes> + Unpin { /* … */ }

Proxy streams reach the core as h3 stream types, because h3-quinn’s stream constructors are private and the shim cannot hand out raw quinn streams. QuicIo adapts them to AsyncRead and AsyncWrite:

  • pending holds the rest of the last poll_data chunk, since a caller’s buffer may be smaller than one chunk. new seeds it with the bytes the classifier read past the frame type.
  • finished latches the peer’s end of stream, so later reads return EOF without polling again.
  • Writes go only through poll_send (SendStreamUnframed). h3-quinn’s send stream panics if send_data is mixed with poll_send, so QuicIo never touches the framed API.
  • poll_flush is a no-op; poll_shutdown calls poll_finish, a clean half-close. Dropping the stream unfinished would reset it, which the peer reads as an abort.
protocols/src/hysteria/server/inbound.rs
pub struct Hy2StreamCore<T> {
user: UserEntry<T>,
sniff: bool,
source: IpAddr,
timing: Timing,
prefix: SniffPrefix,
state: State<T>,
}
impl<T> Hy2StreamCore<T> {
pub const BUF_SIZE: usize = 8 * 1024;
pub fn new(user: UserEntry<T>, sniff: bool, source: IpAddr) -> Self;
pub fn is_established(&self) -> bool;
}
impl<T: Send + Sync + 'static> ProxyCoreDecode for Hy2StreamCore<T> {
type Key = Single;
type Target = Flow<T>;
type Error = io::Error;
type TransportAddr = ();
const STAGING_RESERVE: usize = 2048;
// handle, held
}
enum State<T> {
Request,
Sniff(Flow<T>),
Relay {
relay: Passthrough<Single>,
reply: bool,
},
Done,
}

BUF_SIZE fits a request with the longest address and padding; STAGING_RESERVE fits a TCPResponse with the longest padding. The generic sans-I/O contract (Event, Effect, the staging area) is on Server core.

protocols/src/hysteria/server/datagrams.rs
pub const MAX_SESSIONS: usize = 256;
pub const SWEEP_INTERVAL: Duration = Duration::from_secs(1);
pub struct QuicDatagrams {
conn: quinn::Connection,
pending: Option<DatagramFuture>,
}
impl QuicDatagrams {
pub fn new(conn: quinn::Connection) -> Self;
}
impl DatagramLink for QuicDatagrams {
type Addr = ();
// poll_send_to, poll_recv_from
}
pub struct Hy2UdpCore<T> {
user: UserEntry<T>,
source: IpAddr,
idle_timeout: Duration,
max_datagram: usize,
circuit_permits: Arc<Semaphore>,
sessions: BTreeMap<u32, Session>,
now: u64,
armed: bool,
held: Vec<u8>,
}
impl<T> Hy2UdpCore<T> {
pub const BUF_SIZE: usize = 16 * 1024;
pub fn new(
user: UserEntry<T>,
source: IpAddr,
idle_timeout: Duration,
max_datagram: usize,
circuit_permits: Arc<Semaphore>,
) -> Self;
}
impl<T: Send + Sync + 'static> ProxyCoreDecode for Hy2UdpCore<T> {
type Key = u32;
type Target = Flow<T>;
type Error = io::Error;
type TransportAddr = ();
const STAGING_RESERVE: usize = 4096;
const MAX_DATAGRAM: usize = MAX_UDP_SIZE;
// handle, held
}
protocols/src/hysteria/server/authenticator.rs
pub struct UserEntry<T> {
pub label: CompactString,
pub data: Arc<T>,
}
pub enum Authenticator<T> {
Shared {
password: Box<[u8]>,
entry: UserEntry<T>,
},
UserPass(Vec<UserPassEntry<T>>),
Passwords(Vec<PasswordEntry<T>>),
}
impl<T> Authenticator<T> {
pub fn shared(
password: &str,
label: impl Into<CompactString>,
data: Arc<T>,
) -> io::Result<Self>;
pub fn user_pass(
users: impl IntoIterator<Item = (String, String, CompactString, Arc<T>)>,
) -> io::Result<Self>;
pub fn passwords(
users: impl IntoIterator<Item = (String, CompactString, Arc<T>)>,
) -> io::Result<Self>;
pub fn authenticate(&self, credential: &str) -> Option<&UserEntry<T>>;
}
protocols/src/hysteria/server/masquerade.rs
pub struct Masquerade {
status: StatusCode,
body: Bytes,
content_type: CompactString,
}
impl Masquerade {
pub fn new(status: u16, body: impl Into<Bytes>, content_type: &str) -> io::Result<Self>;
pub fn response(&self) -> Response<()>;
pub fn body(&self) -> Bytes;
}

UserEntry implements Clone by hand so that T need not be Clone; the payload only ever lives behind the Arc.

A listener starts in two phases, so that an owner applying a change can fail before it commits to it:

  1. open(socket) builds everything run needs that can fail. It stores the keystream for obfs into the switch, refusing a key that is too short, creates a closed RecvGate, and calls endpoint::from_socket(socket, None, switch, gate). The endpoint has no server config, so it admits nobody; its gate is closed, so it reads nothing, and clients’ packets wait in the kernel as they would for a socket nobody serves yet. The result is an OpenedEndpoint. It is not yet the inbound’s endpoint, so the setters do not reach it; dropped unserved, it closes, and the inbound is as it was.
  2. run(opened, make_connector, token) installs the QUIC config and records the endpoint in EndpointState, both under the lock, then opens the gate and serves until the endpoint closes, or until token is cancelled and every connection live then has ended. It returns nothing.

Every task below the accept loop is owned by a JoinSet one level up, so dropping an owner takes everything below it with it.

flowchart TB
  run["Hy2Inbound::run: accept loop"]
  conn["connection task: serve_connection"]
  h3["http3 task: h3 server over Hy2H3Conn"]
  cls["classifier task"]
  udp["datagram task: Hy2UdpCore runtime"]
  stream["proxy stream task: Hy2StreamCore runtime"]
  run -->|"JoinSet, holds its Admitted place"| conn
  conn -->|JoinSet| h3
  conn -->|JoinSet| cls
  conn -->|"JoinSet, only if udp is Some"| udp
  cls -->|"JoinSet, holds circuit permit"| stream
  h3 -.->|"classify_tx: new bidi streams"| cls
  cls -.->|"h3_ready: replayed HTTP/3 streams"| h3
  h3 -.->|"authed oneshot: UserEntry"| udp
Task Spawned by Owned by Ends when
accept loop caller (supervisor/src/serve.rs → run_hysteria_inbound) caller endpoint.accept() returns None, or token is cancelled and every connection has ended
connection accept loop, after taking an Admitted place connections: JoinSet<()> in run the QUIC handshake fails; all its child tasks have ended; its closed token is cancelled; or its keyed token is cancelled
http3 serve_connection tasks: JoinSet<()> h3 setup fails, or h3.accept() returns Ok(None) or an error
classifier serve_connection tasks the classify_tx sender is dropped (the Hy2H3Conn is gone), or the h3_ready receiver is gone
datagram runtime serve_connection, when config.udp is Some tasks the authentication oneshot is dropped unsent, or the runtime ends (read_datagram fails when the connection closes)
proxy stream runtime classifier, after taking a circuit permit serving: JoinSet<()> in classifier the runtime future completes

The http3 task holds the h3::server::Connection, which holds the Hy2H3Conn. When it ends, the classify_tx sender goes with it, the classifier’s incoming.recv() returns None, and dropping the classifier’s serving set aborts every proxy stream of that connection.

serve_connection selects on three things:

  • tasks.join_next() draining: the connection has ended on its own;
  • closed, the token make_connector returned: the owner closes this one connection with DISCONNECT_CODE (0x107, HTTP/3’s H3_EXCESSIVE_LOAD) and the reason disconnected by the server;
  • keyed, the obfuscation token current when the connection arrived: the connection is closed with DISCONNECT_CODE and the reason obfuscation changed.

Either close takes every task with it when tasks drops. 0x107 is what upstream sends a client its traffic logger turns away, the path its user kick takes, so a client told this knows it was disconnected on purpose rather than by a fault.

struct Admitted(Arc<AtomicUsize>);
impl Admitted {
fn take(live: &Arc<AtomicUsize>, max: usize) -> Option<Self>;
}

run keeps a count of live connections and a JoinSet of their tasks. The loop select!s, biased, over three things in this order: the cancellation token (so a cancellation is seen before any client that raced it), connections.join_next() (so finished connections are reaped before new ones pile on), and the next Incoming from endpoint.accept().

For each Incoming, run reads max_connections and calls Admitted::take, which increments the count only while it is below the limit (a try_update); dropping an Admitted decrements it. A count checked against a limit read at each arrival, rather than a semaphore sized once, is what lets the limit change under live connections. An admitted connection loads the current ServerConfig, and under the endpoint lock the current TLS configuration (EndpointState::quic) and keyed token, and spawns its task. The task holds the Admitted place and, before the handshake, builds a congestion controller factory of its own, Negotiated::new(config.congestion), and the configuration it is accepted with, endpoint::for_connection(&base, &config.quic, factory). If that fails it logs hysteria2: refusing a connection: <error> at warn and calls incoming.refuse(). Otherwise it calls incoming.accept_with(quic), awaits the QUIC handshake, calls make_connector(remote_ip, ConnectionBytes), and runs serve_connection with the factory’s CongestionSwitch. The place therefore covers the QUIC handshake and the whole connection. A failed handshake is logged at debug (hysteria2: a handshake failed: …) and ends the task. A factory of its own is what lets the rate agreed at /auth move this one connection, and keep it on that rate if it migrates.

A connection that finds no place, or that arrives after token was cancelled, is refused, not ignored: Incoming::refuse tells the client at once, instead of letting it retransmit its handshake into silence. The refusal is logged at debug as hysteria2: refusing a connection; the listener is full or stopping.

make_connector is called once per connection, as soon as its QUIC handshake completes. The connector it returns is cloned for each of that connection’s proxy streams and for its datagram channel.

sequenceDiagram
  participant C as client
  participant Q as Hy2H3Conn
  participant K as classifier
  participant H as h3 server
  participant S as stream task
  C->>Q: open bidi stream 1: HEADERS POST /auth
  Q->>K: classify_tx.try_send(stream 1)
  K->>K: classify: first varint is 0x01, not 0x401
  K->>Q: h3_ready.send(stream 1 with replayed bytes)
  Q->>H: poll_accept_bidi returns stream 1
  H->>H: answer: authenticator matches, AuthState set, Rate::apply
  H->>C: 233, Hysteria-UDP, Hysteria-CC-RX, padding
  C->>Q: open bidi stream 2: 0x401 TCPRequest
  Q->>K: classify_tx.try_send(stream 2)
  K->>K: classify: 0x401 and AuthState has a user
  K->>S: spawn runtime over QuicIo(stream 2, rest), with circuit permit and a connector clone
  S->>C: TCPResponse, then relay

The HTTP/3 side runs h3::server::Connection::new(transport) and loops over accept(). For each request it calls answer, which decides on method, path and host only:

Request Connection state Response
POST, path AUTH_PATH (/auth), host AUTH_HOST (hysteria), credential matches not authenticated 233 with Hysteria-UDP, Hysteria-CC-RX, Hysteria-Padding; AuthState records the user, and the server picks its send rate from the client’s Hysteria-CC-RX
the same request again, with any credential authenticated 233 again, without checking the credential; the stored identity does not change
the same request, credential does not match not authenticated the masquerade
anything else any the masquerade

The success response is built by accepted: status STATUS_AUTH_OK (233), Hysteria-UDP set to true or false from config.udp.is_some(), Hysteria-CC-RX from negotiate::server_rx_header (see Rate negotiation), and Hysteria-Padding drawn from AUTH_RESPONSE_PADDING (256 to 2047 alphanumerics). The credential is read from the Hysteria-Auth header; a value that is not a visible-ASCII header string is read as the empty string, which no authenticator accepts because every constructor refuses an empty credential.

answer asks is_authenticated before it reads a credential, which is how a repeated /auth gets 233 without a check. authenticate stores the user only if none is stored yet, and user reads it back. The first time AuthState holds a user, http3 sends a clone of the UserEntry down the authed oneshot, which is what lets the datagram task build its runtime. The send happens before the response is written. Until then the datagram task only waits on the oneshot, so no datagram is read for a connection that has not authenticated, as upstream starts its session manager only after a credential is accepted.

A rejected credential gets exactly the response a wrong URL gets. That is the censorship-resistance property the protocol rests on: without a credential the server is an ordinary HTTP/3 web server.

Each end tells the other, in Hysteria-CC-RX, the rate it can receive at in bytes per second. From that figure and its own up, each end picks a fixed rate to send at with Brutal, or stays on ordinary congestion control; the rules differ by direction, as the tables below show. A server can also answer auto, which makes both ends ignore the figures. The rules are a port of upstream’s core/client/client.go and core/server/server.go, in protocols/src/hysteria/negotiate.rs, which both ends use.

What the server answers. negotiate::server_rx_header(&config.bandwidth, config.ignore_client_bandwidth):

ignore_client_bandwidth Server down Hysteria-CC-RX
true anything auto
false set down in bytes per second
false not set 0: no limit

A repeated /auth on an authenticated connection gets the same answer.

What the server sends at. On the request that authenticates the connection, answer reads the client’s Hysteria-CC-RX with negotiate::parse_client_rx: the trimmed value as a u64, where a missing value, one that is not a visible-ASCII header string, or one that does not parse counts as 0, “unknown”, so the server never sends at a rate nobody asked for. Rate::apply then asks negotiate::server_tx(client_rx, &config.bandwidth, config.ignore_client_bandwidth):

  • ignoring client bandwidth: no fixed rate;
  • the client sent 0: no fixed rate;
  • otherwise Brutal at the smaller of the server’s up and the client’s rate, or at the client’s rate when the server has no up.

With a rate, Rate::apply calls switch.use_brutal(negotiate::brutal(rate, &config.bandwidth)) on the connection’s CongestionSwitch, with loss compensation on unless disable_loss_compensation is set, and conn.set_send_window(negotiate::send_window(rate)): half a second of the rate, never below quinn’s default of 10,000,000 bytes, because quinn holds back what a connection has unacknowledged beyond its send window. It logs hysteria2: sending to <addr> at <rate> at debug. Without a rate the connection stays on config.congestion. A repeated /auth changes nothing, since answer returns before it reads a credential.

The two directions are not symmetric, in upstream or here. The client’s half is negotiate::client_tx on Hysteria 2: client:

Sender The peer said 0 The peer named a rate
client with up Brutal at up Brutal at the smaller of the two
client without up fallback fallback
server with up fallback Brutal at the smaller of the two
server without up fallback Brutal at the client’s rate

A server’s auto leaves the client on its fallback controller too. A client without up never uses Brutal, while a server without up sends at whatever rate the client says it can take. How Brutal paces, and how the switch moves a live connection off its fallback controller, is on Congestion control.

A Hysteria 2 server is an HTTP/3 server that also carries proxy traffic on the same connection’s bidirectional streams. The two are told apart by the first QUIC varint of the stream: FRAME_TYPE_TCP_REQUEST (0x401) is not an HTTP/3 frame type. Upstream’s HTTP/3 server has a “proxy stream hijacker” hook for this; h3 has none, so the shim puts the split one layer lower, in the transport h3 runs on.

classify appends whole poll_data chunks to a BytesMut (initial capacity MAX_VARINT_BYTES, 8) until the width announced by the first byte’s top two bits is covered, then splits:

  • frame_type_bytes: the varint’s own bytes, exactly as received;
  • rest: every byte read past the varint, which is the start of the body;
  • kind: ProxyRequest for 0x401, otherwise Http3(value).

If the peer finishes the stream before naming it, classify returns a StreamErrorIncoming (hysteria2: stream ended before its frame type).

Why the varint has to be replayed. A QUIC receive stream cannot be peeked; reading consumes. A stream that turns out to be HTTP/3 is therefore handed to h3 as Hy2BidiStream::new(classified.replay(), stream), a PrefixedBidi whose receive half yields the replayed bytes before delegating. replay returns frame_type_bytes followed by rest, in wire order. When h3 splits the stream, PrefixedBidi::split moves the prefix into a PrefixedRecv, because only the receive half can replay it. h3 cannot tell the difference. A proxy stream does not need the frame type again, since Hy2StreamCore parses the request body, so it is wrapped as Hy2BidiStream::unprefixed(stream) and rest goes to QuicIo as its prefix.

Why classification is not done in poll_accept_bidi. That is a Poll function and cannot await the varint. So the waiting moves into a separate classifier task, bounded by a queue and a timeout, and poll_accept_bidi only moves streams:

  1. It drains every stream quinn has accepted into classify_tx with try_send. The call never awaits, because poll_accept_bidi cannot block.
  2. A stream that does not fit in the queue is reset with discard(…, Code::H3_EXCESSIVE_LOAD), both halves (reset on the send side and stop_sending on the receive side). Dropping it instead would leave the peer writing into a stream nobody reads. This reset bounds the work waiting for classification.
  3. It then polls h3_ready_rx and returns the next stream the classifier handed back. If the classifier is gone, it returns ConnectionErrorIncoming::InternalError("hysteria2: stream classifier stopped").

Both sources are polled before Pending is returned, so both wakers are armed; waking on only one would stall until the other happened to fire. Unidirectional streams (HTTP/3 control and QPACK) belong to h3 alone and pass through poll_accept_recv unclassified. Streams the server opens itself go through Hy2Opener, which wraps them with an empty prefix only so the type matches what h3 accepts.

The classifier task receives streams from classify_rx one at a time and runs classify on each under tokio::time::timeout(CLASSIFY_TIMEOUT, …):

Outcome Action
0x401 and auth.user() is Some take a circuit permit, spawn a Hy2StreamCore runtime over a clone of the connection’s connector into serving
0x401 but no circuit permit left discard(…, Code::H3_REQUEST_REJECTED), logged at debug as hysteria2: refusing a stream; the listener is at its circuit limit
anything else, or 0x401 before authentication send Hy2BidiStream::new(replay, stream) to h3_ready; if h3 has gone, the classifier stops
classify returned an error logged at debug (hysteria2: could not classify a stream: …), the stream is dropped
CLASSIFY_TIMEOUT passed discard(…, Code::H3_REQUEST_CANCELLED), logged at debug as hysteria2: a stream never named itself; resetting

A proxy stream that arrives before authentication is handed to HTTP/3 with its bytes replayed, as upstream does. h3 sees a frame type it does not know, and the stream is neither answered nor relayed, which is what a real web server would do with it.

A compile-time item at the end of shim.rs, const _: () = { assert_transport::<Bytes, Hy2H3Conn<Bytes>>(); }, proves h3 accepts the transport. quic::Connection requires its OpenStreams associated type to agree with its own SendStream and BidiStream, so Hy2Opener and Hy2H3Conn must name exactly the same pair. h3 is a 0.0.x crate; when its traits move, this assertion fails first and says so plainly.

The wrappers are generic over the inner stream for the same private-constructor reason: it lets protocols/tests/unit/hysteria/server/shim.rs exercise them against a fake receive stream instead of a live QUIC connection.

Each setter changes one part of a listener without rebinding its socket. Every one but set_obfs applies to connections that arrive afterwards and leaves every live connection as it was.

Setter What it changes Reaches
set_connection_config(config) The per-connection settings: authenticator, masquerade, sniffing, UDP, the circuit budget, the rates, ignore_client_bandwidth, the fallback controller and the QUIC transport parameters. Connections that arrive afterwards. A live connection keeps the config it arrived under: its masquerade, its UDP setting, its transport parameters and send rate and, if it has yet to present a credential, the user table that credential will be checked against.
set_authenticator(table) The user table, stored into the current connection config’s ArcSwap. Connections authenticated afterwards under that config (see below). A caller that also calls set_connection_config must not race the two: a table stored into a config just replaced is seen only by the connections that config still serves.
set_quic(quic) TLS material, for example a renewed certificate. A running endpoint takes it at once through Endpoint::set_server_config, and each connection accepted afterwards is built from it by for_connection, which replaces its transport parameters with the connection config’s quic. New handshakes. A live connection keeps what it negotiated.
set_max_connections(max) The connection limit, read at each arrival. Arrivals. Lowering it below the number already live closes none of them; new ones are refused until enough have ended.
set_obfs(obfs) The obfuscation of a running endpoint: the key is stored into the socket’s switch, and keyed is cancelled and replaced. Every packet, in both directions, from the moment it returns. Every live connection was negotiated under the old obfuscation, so each is closed with obfuscation changed, while the endpoint stays bound and keeps accepting.

set_obfs switching to the obfuscation already in use changes nothing and closes nothing. A key too short to be one is refused with the Salamander key error, and nothing changes. A client whose connection is closed by a switch cannot read that close, since it goes out under the new key, and finds out by its idle timeout, as it would from any server whose key it no longer holds.

From gentlest to hardest, a listener or a connection is stopped like this: cancelling the token a connection’s connector came with closes that one connection; cancelling run’s token stops admitting and lets the live connections finish; shutdown closes the endpoint and every connection on it; dropping run’s future drops every connection at once.

The client writes a TCPRequest and waits for a TCPResponse before sending payload. All varints are QUIC varints (RFC 9000 section 16), not protobuf varints.

TCPRequest, client to server:

Field Size Meaning
frame type varint 0x401 (FRAME_TYPE_TCP_REQUEST), two bytes on the wire; consumed by the classifier
address length varint 1 to MAX_ADDRESS_LENGTH (2048)
address bytes host:port, UTF-8
padding length varint at most MAX_PADDING_LENGTH (4096)
padding bytes ignored

TCPResponse, server to client:

Field Size Meaning
status u8 STATUS_OK (0x00) or STATUS_ERROR (0x01)
message length varint 0 to MAX_MESSAGE_LENGTH (2048)
message bytes Connected on success
padding length varint the server draws from TCP_RESPONSE_PADDING, 128 to 1023 bytes
padding bytes alphanumerics, ignored by the client

parse_tcp_request_body range-checks each length before it is used and returns Ok(None) while the buffer is short, so the core can wait for more bytes without allocating for an attacker-chosen length. An address that is not UTF-8, empty, or longer than 2048 bytes, and a padding length over 4096, are ProtocolError::Malformed and end the stream.

stateDiagram-v2
  [*] --> Request
  Request --> Relay: parsed, no sniff, Open with reply = true
  Request --> Sniff: parsed, sniff and IP target, stage Connected
  Request --> Done: no port or bad address, stage refusal and Finish
  Request --> Done: TransportEof, Finish
  Sniff --> Relay: verdict, SNIFF_TIMEOUT or TransportEof, Open with held bytes and reply = false
  Relay --> Relay: Connected, stage Connected if reply
  Relay --> Done: ConnectFailed, refusal if reply, then ShutdownTransport and Finish
  Done --> [*]

Request. on_transport calls parse_tcp_request_body. The address is parsed with parse_authority(&address, 0): the default port is zero rather than a guess, and a destination whose port is still zero is refused with a TCPResponse of status 0x01 and message bad address, followed by Effect::ShutdownTransport and Effect::Finish. A request that names no port can therefore never be routed by accident. Otherwise the core builds a Flow with network DialNetwork::Tcp, the client address as source, and a NetworkUser whose authorization is UsernamePassword { username: user.label, password: Default::default() }. The flow carries the label and the payload, never the credential.

Sniff. When sniff is set and worth_sniffing says the destination is a bare IP, the core stages Connected at once and enters Phase::Sniff. Payload bytes then go into the SniffPrefix (bounded by the sniff budget) until the collector gives a verdict, the sniff deadline passes, or the client half-closes. open_sniffed moves the flow out of the state, attaches prefix.result() as flow.sniffed, opens it with reply = false, and pushes Effect::ForwardHeld for the collected bytes. See Sniffing.

Relay. open first enters Phase::Relay, which pushes SetDeadline(RELAY_IDLE_TIMEOUT), then pushes Effect::Open { key: Single, target }, forwards any held bytes with Effect::ForwardHeld, and sets State::Relay. The deadline goes first because a forward queued after the open waits out the connect, and so would a deadline queued after that forward, which would leave the sniff window’s 300 ms deadline armed to end the flow as idle mid-connect (protocols/src/core/mod.rs → Timing::enter). From here Passthrough<Single> does the work: transport bytes are forwarded verbatim, outbound bytes are staged verbatim, and each end of stream half-closes the other side (Effect::Shutdown or Effect::ShutdownTransport), finishing once both have ended. prefix.clear() runs at the next byte event, after the runtime has applied the forward that referenced the held bytes.

  • Event::Connected stages Connected only if reply is still true, and clears it, so a stream never gets two responses.
  • Event::ConnectFailed stages a refusal only if reply is true. On the sniff path the client was already told Connected, so the core ends the stream instead with ShutdownTransport and Finish.
  • Event::OutboundError calls on_outbound_gone, which shuts the transport and finishes.

Deadlines come from Timing in protocols/src/core/mod.rs, which gives the runtime’s single timer a meaning per phase: HANDSHAKE_TIMEOUT (10 s) while a started request is incomplete, SNIFF_TIMEOUT (300 ms) while sniffing, and RELAY_IDLE_TIMEOUT (300 s) while relaying, re-armed on every byte event. An expired handshake returns handshake_timed_out() (client did not complete its request in time); an expired sniff window opens the flow with what was collected; an idle relay finishes.

Why a CONNECT may be answered before the target is up

Section titled “Why a CONNECT may be answered before the target is up”

A client blocks reading the TCPResponse before it sends any payload, and sniffing means reading payload. If the server waited for the target before answering a request it wants to sniff, the client would wait for the server and the server for the client until the sniff deadline expired.

So the rule, stated in the module docs of inbound.rs, is:

  • a request that will be sniffed (sniffing enabled and an IP target) is answered Connected at once, and the flow opens once the first bytes have been inspected or the sniff window closes;
  • every other request is answered only when the runtime reports Event::Connected, that is, when the target really is up, and with a refusal when it is not.

The unit test a_request_opens_and_is_answered_once_connected asserts that nothing is staged before Connected; sniffing_an_ip_target_answers_early_and_opens_with_the_host asserts the early answer and that no second response follows.

Each QUIC datagram carries one UDPMessage or one fragment of one:

Field Size Meaning
session id u32, big-endian the association, chosen by the client
packet id u16, big-endian ties the fragments of one packet together; the server sends 0 when unfragmented
fragment id u8 index of this fragment, from 0
fragment count u8 number of fragments; 1 means not split
address length varint 1 to MAX_ADDRESS_LENGTH (2048)
address bytes host:port, UTF-8
payload bytes the rest of the datagram; must not be empty

QuicDatagrams is the connection’s datagram channel as a DatagramLink with Addr = (): a QUIC connection has exactly one peer. poll_send_to calls conn.send_datagram and maps errors through hysteria::quic::datagram_error. poll_recv_from keeps one boxed read_datagram future in pending across polls, copies the datagram into the caller’s buffer, and maps a connection error to ErrorKind::BrokenPipe, which ends the runtime when the connection closes.

The runtime is built with ProxyServerRuntime::over_datagrams(QuicDatagrams::new(conn), core, connector), over the connection’s connector, and a buffer of Hy2UdpCore::BUF_SIZE (16 KiB), enough for a reassembled packet plus its fragments’ headers. See Server runtime for the datagram transport mode.

flowchart TB
  pkt["TransportDatagram"] --> parse{"parse_udp_message_at ok?"}
  parse -- no --> drop1["drop"]
  parse -- yes --> known{"session id known?"}
  known -- yes --> frag
  known -- no --> cap{"fewer than MAX_SESSIONS?"}
  cap -- no --> drop2["drop"]
  cap -- yes --> permit{"circuit permit?"}
  permit -- no --> drop3["drop"]
  permit -- yes --> port{"address has a port?"}
  port -- no --> drop4["drop"]
  port -- yes --> open["Open key = session id, insert Session"]
  open --> frag{"frag_count at most 1?"}
  frag -- yes --> send["SendTo range of the datagram"]
  frag -- no --> defrag["Defragger::feed"]
  defrag -- complete --> held["copy into held, SendToHeld"]

Hy2UdpCore keeps a BTreeMap<u32, Session>. A Session holds the sweep tick of its last activity, a Defragger, and an OwnedSemaphorePermit from the listener’s circuit_permits, so a UDP association counts against the same circuit budget as a proxy stream and releases its permit when the session is removed.

  • Opening. The first packet of an unknown session id opens it with Effect::Open { key: id, target }, where the target is a Flow with DialNetwork::Udp built from that packet’s address. The cap (MAX_SESSIONS, 256 per connection) is checked before the permit is taken.
  • Sending. Every packet is sent to its own address, not the address that opened the session: Effect::SendTo { key, to, range } forwards the payload by range out of the received datagram without copying. A packet whose address has no port, or whose payload is empty, is dropped.
  • Reassembly. A fragmented packet goes through the session’s Defragger. It holds one packet’s fragments at a time (a fragment of a different packet discards the one in progress), drops a fragment index past the count and repeated fragments, and caps the reassembled size at MAX_UDP_SIZE (4096): a fragment that would take it past the cap discards the packet in progress. Each fragment is copied out of the datagram and joined to its header with UdpHeader::with_payload before Defragger::feed takes it. The finished payload is copied into held and sent with Effect::SendToHeld.
  • Unparseable datagrams are dropped and logged at trace level; the whole datagram is consumed either way.
  • Failures. ConnectFailed and OutboundError for a session remove it, releasing its permit. SendFailed and TransportSendFailed drop one packet and keep the session.

The protocol has no message to close an association, so sessions retire on idleness only, as upstream’s do.

The core has its own clock: now counts sweep ticks. The first packet or reply arms Effect::SetDeadline(Some(SWEEP_INTERVAL)). Each Event::Deadline increments now, removes every session with now - last >= idle (where idle is idle_timeout in whole seconds, at least 1), pushes Effect::Close { key } for each, and re-arms the deadline. Activity in either direction sets last = now. A session id that was swept can be reused, and its next packet opens a fresh association.

on_reply wraps each reply from an association in a UDPMessage with the session id, the reply’s source as format_authority(from), and frag_count = 1. Empty replies and replies over MAX_UDP_SIZE are dropped.

The size limit is max_datagram, read once when the datagram runtime starts: conn.max_datagram_size(), falling back to MAX_DATAGRAM_FRAME_SIZE (1200). A message that fits is staged whole with fx.put_to((), …). A larger one gets a random non-zero packet_id (zero is reserved for the unfragmented case) and is split by UdpMessage::fragment into pieces that each fit; if the header alone leaves no room, or the split would need more than 255 fragments, the reply is dropped. STAGING_RESERVE (4096) covers the fragment headers of a maximal reply. The fragmentation code is the same UdpMessage::fragment the client uses, and a_large_datagram_is_fragmented_in_both_directions exercises it against the upstream client.

Authenticator decides whom a Hysteria-Auth string belongs to. The protocol carries one opaque string, so a multi-user server needs a convention, and there are two in use:

Variant Constructor Wire credential Built for
Shared shared(password, label, data) the password one password for everyone
UserPass user_pass(users) user:pass, split on the first colon; the username is lower-cased on both sides clients configured for an upstream server
Passwords passwords(users) the whole string, one opaque credential per user panel-driven nodes, where the credential identifies the user by itself

Construction fails closed:

Refusal Message
empty shared password hysteria2: the password must not be empty
user_pass entry with an empty name or password hysteria2: a user needs both a name and a password
username containing : (it could never be presented) hysteria2: a username cannot contain ':' — it separates the two on the wire
two usernames equal after lower-casing hysteria2: two users share a name once lower-cased
passwords entry with an empty credential hysteria2: a user needs a credential
two users with the same credential hysteria2: two users share one credential
empty table hysteria2: the user table is empty

authenticate compares with helpers::crypto::ct_eq, the crate’s subtle-backed comparison, and scans every entry of a table without returning early, recording the match in a local. For UserPass the name and password comparisons are combined with a non-short-circuit &. The scan is linear; that is affordable because Hysteria 2 authenticates once per QUIC connection, not once per proxied stream.

ServerConfig::authenticator is an ArcSwap<Authenticator<T>>, and answer loads it for each credential check. Hy2Inbound::set_authenticator stores a new table into the current connection config:

  • the listener, its socket and every live connection are untouched;
  • a connection authenticated before the swap keeps the UserEntry its AuthState recorded, because AuthState is a OnceLock that the swap cannot reach;
  • only connections authenticated after the swap see the new table.

Rebuilding the listener instead would rebind the UDP port and drop every connected client. The supervisor swaps tables this way for every front end: supervisor/src/system/listener.rs → Listener::store_users calls set_authenticator when an inbound’s users change, and an etemenanki-app reload is an apply like any other. Because a connection that is already in keeps its identity, retiring a user cannot go through the table alone. In the supervisor each Hysteria 2 connection is one session bound to the user’s principal, and the inbound’s user-removal policy decides what happens to a removed user’s live sessions; the default, UserRemovalPolicy::Close, cancels the session’s token, which closes the QUIC connection with disconnected by the server. How sessions bind and how removal reaches them is on Users, principals and sessions.

The supervisor builds the table in supervisor/src/build/inbound.rs → user_table, from the spec’s shared_password and user_auth:

Spec Table Wire credential
shared_password set Authenticator::shared(password, "", Principal::anonymous()); the empty label is this crate’s spelling of an unlabelled user the password
user_auth = Account Authenticator::user_pass, one entry per admitted account, labelled by the user’s principal user:pass
user_auth = Password Authenticator::passwords, one entry per admitted password, labelled by the user’s principal the password

etemenanki-app always lowers user_auth = Account. katana chooses from its credential setting (src/lower/inbound.rs → lower_hysteria): "" or "uuid" gives Password, with each user’s panel UUID as the credential, because the panel’s user list carries no password to put after a colon; "user_pass" gives Account, upstream’s convention, with the user’s traffic label as the username. Anything else is refused with unknown hysteria credential kind "<value>" (expected "uuid" or "user_pass"). A helium node cannot set credential (see From the spec to a listener), so its users always present their UUID.

Masquerade is the fixed response every request gets that is not a good credential: status, Content-Type, Content-Length, then the body, then finish.

  • Masquerade::default() is Go’s http.NotFound, byte for byte: 404, text/plain; charset=utf-8, body 404 page not found\n. That is what an upstream server with no masquerade configured answers, so a probe cannot tell the two apart by their 404.
  • Masquerade::new refuses STATUS_AUTH_OK (233), because serving it to an unauthenticated request would tell that request it had authenticated: hysteria2: 233 is the authentication success status and cannot be used for the masquerade. It also refuses a value that is not an HTTP status code (hysteria2: <n> is not an HTTP status code); anything the http crate accepts (100 to 999) is the operator’s choice.

In etemenanki-app, and in katana’s [node.hysteria.masquerade] table, setting any of status, body or content_type gives a masquerade whose other fields take the answer an unconfigured Go server gives (404, 404 page not found\n, text/plain; charset=utf-8); setting none uses Masquerade::default(). A helium panel describes the masquerade itself, with all three fields, or leaves it out, which also gives Masquerade::default(). The supervisor builds it with Masquerade::new in supervisor/src/build/inbound.rs → hy2_handler, and validate_inbound refuses a masquerade that Masquerade::new would refuse.

Every front end runs the listener through etemenanki-supervisor.

The front end lowers its configuration into a Hysteria2InboundSpec on a UDP bind:

  • etemenanki-app: app/src/lower.rs → lower_inbound accepts hysteria2, hysteria and hy2 (hysteria2_answers_to_its_aliases). It refuses a [stream] block and a Unix listen address (inbound <tag>: hysteria2 listens on UDP and cannot use a unix socket). lower_hysteria2_inbound requires cert_file and key_file (inbound <tag>: hysteria2 needs both cert_file and key_file) and reads both. A user is keyed by its email, or by its user name when it has none. Obfuscation goes through lower_obfs, as on the client. udp_idle_timeout defaults to 60 seconds and is refused when udp is off (inbound <tag>: udp_idle_timeout is set but udp is not enabled). max_connections and max_circuits default to DEFAULT_MAX_CONNECTIONS and DEFAULT_MAX_CIRCUITS. bandwidth, congestion and quic go through lower_bandwidth, lower_congestion and lower_quic, as on the client (see How the front ends build it), with quic over QuicOptions::server(): quic.max_incoming_streams is accepted here, and quic.keep_alive_period is refused with inbound <tag>: quic.keep_alive_period is a client setting; a server does not ping. ignore_client_bandwidth left unset follows the rates: on while bandwidth names neither up nor down, so a server given no rates answers auto as servers did before rates existed, and off, upstream’s default, once a rate is given.
  • katana: src/lower/inbound.rs → lower_hysteria builds the same spec from the node, helium-node-api’s Hysteria2 (Node in src/api/mod.rs), and the two keys of the local [node.hysteria] block that are this host’s alone (src/config.rs → HysteriaConfig), credential and congestion, with shared_password: None, the default limits and the user_auth above. The node says the obfuscation, the rates, ignore_client_bandwidth, the UDP relay and the masquerade. A helium panel describes all of them, and helium-node-api holds them to its rules as the answer is read: a Salamander password of at least 4 bytes, an idle timeout between 2 and 600 seconds, a masquerade status from 100 to 999 other than 233. A UniProxy (newV2board) panel says only the obfuscation (obfs, obfs-password) and the rates, so src/api/hysteria.rs → uniproxy completes its node from [node.hysteria], and hysteria::local builds a node described locally ([node.hysteria].port set) from the block alone. Both hold the obfuscation to one set of rules: a password without obfs is refused with obfs_password is set but obfs is not; did you mean obfs = "salamander"?, a short one with obfs_password must be at least 4 bytes for salamander, and any other obfs with unknown obfs "<x>" (expected "salamander"). Both take the UDP relay and the masquerade from [node.hysteria]: no relay unless udp is on, an idle timeout left out is 60 seconds, one outside 2 to 600 seconds is refused with udp_idle_timeout must be between 2 and 600 seconds, and one set while udp is off with udp_idle_timeout is set but udp is not enabled. The rates are the panel’s, in whole Mbit/s (from a UniProxy panel, a fraction is rounded, and a figure below 1 or one that is not a number is none), each overridden by up_mbps or down_mbps in [node.hysteria]; 0 means no cap. ignore_client_bandwidth is the local setting, else the panel’s, else true; a helium panel always sends it, true unless the node’s config there turns it off. Every node is then held to helium-node-api’s rules, and lower_hysteria holds its masquerade to what Masquerade::new accepts (masquerade_spec). congestion is "cubic" (the default), "bbr" or "reno"; anything else is refused with unknown hysteria congestion "<x>" (expected "cubic", "bbr" or "reno"), and katana --test judges it on every node, before any panel is asked (src/lower/mod.rs → test_spec). On a helium node, congestion is the only key of [node.hysteria] that may be set. Its panel describes the rest, so the helium client (src/api/helium.rs → refuse_local_protocol) refuses every other key by name at build, --test and reload, for example [node.hysteria] up_mbps is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose); neither the rates nor the obfuscation, UDP relay, masquerade or credential can be set locally there. Loss compensation stays on, and quic is always QuicOptions::server(). A Hysteria 2 node gets no handoff socket, even with [node.controller].handoff_dir set: lower_inbound gives one only to a node on a TCP bind.

supervisor/src/build/validate.rs → validate_inbound then refuses:

Condition Error text after inbound <tag>:
a shared password and a user set a shared password and a user set cannot both be set; a credential would have two answers
neither hysteria2 needs a shared password or a user set
an empty shared password the shared password must not be empty
udp_idle_timeout outside 2 to 600 seconds udp_idle_timeout must be between 2 and 600 seconds
max_connections or max_circuits of 0 max_connections and max_circuits must be at least 1
a handoff socket beside the UDP bind only a stream inbound on a tcp listener takes a handoff socket
a Salamander key under 4 bytes salamander obfs key must be at least 4 bytes
a receive window below 16,384 bytes (QuicOptions::MIN_RECEIVE_WINDOW) or above what a QUIC varint holds stream_receive_window must be at least 16384 bytes, or the same for conn_receive_window
an idle timeout that is not a whole number of seconds from 4 to 120 max_idle_timeout must be a whole number of seconds between 4 and 120
a keep-alive period that is not a whole number of seconds from 2 to 60 keep_alive_period must be a whole number of seconds between 2 and 60
max_incoming_streams of 0 max_incoming_streams must be at least 1
a masquerade Masquerade::new refuses its error, for example the 233 refusal

Below 2 s a busy association would be swept between packets; above 600 s a dead one holds its outbound socket for ten minutes. The QUIC ranges are upstream’s (hy2_quic, shared with the client). validate_admission refuses two users whose Hysteria 2 usernames are equal ignoring case, a username holding : or an account without a name or password (user <name>: a hysteria2 account needs a name without ':' and a password), and an empty user password (user <name>: a hysteria2 password must not be empty).

hy2_handler builds a Hy2Handler: the connection config, made with ServerConfig::new(table, masquerade, circuit semaphore) (imported as Hy2ConnectionConfig) and then given sniff, udp, bandwidth, ignore_client_bandwidth, congestion and quic from the spec (supervisor/src/topology/spec_plan/inbound.rs → Hysteria2InboundSpec); the quinn TLS config from endpoint::server_config; the obfuscation; and max_connections. When an apply rebuilds a running listener’s handler and max_circuits is unchanged, the running semaphore is passed in and kept (supervisor/src/supervisor.rs → same_circuits), so the listener keeps one circuit budget across the swap; a changed size starts a new one.

supervisor/src/system/listener.rs runs the two-phase start across an apply’s prepare and commit:

  1. Bind. In prepare, bind binds a std::net::UdpSocket for a BindSpec::Udp (Bound::Udp).
  2. Pair. Pending::pair checks the obfuscation key (check_obfs), builds the Hy2Inbound and calls open on the socket. Any failure here fails the apply before it commits.
  3. Start. At commit, Listener::start spawns run_hysteria_inbound, which calls run on the opened endpoint.

A later apply that changes the inbound but keeps its bind swaps the handler into the running listener (Listener::swap): it calls set_obfs only if the obfuscation changed, then set_connection_config, set_quic and set_max_connections, and stores the inbound’s current tag for connections that arrive afterwards. The endpoint and its socket are kept, and no connection is dropped except by an obfuscation change. The plan marks that change as disruptive (supervisor/src/topology/spec_plan/plan.rs → Step::Disrupt with the reason the hysteria2 obfuscation changed; connected clients cannot follow the new key), so it needs ApplyOptions::allow_disruptive. etemenanki-app refuses it with a restart hint; katana allows it, and then closes every session of the node, as it does after any change to the node but those the supervisor applies to the connections that arrive after it (katana src/manager/node.rs → disruptive_part). For a Hysteria 2 node those are the rates (up_mbps, down_mbps, ignore_client_bandwidth) and the UDP idle timeout. Every other change to the node closes every session: the obfuscation, the port, turning the UDP relay on or off, and the masquerade, so a connection held open across a masquerade change does not go on answering the old way. katana also closes every session after any edit to [node.hysteria]. In the supervisor, a masquerade change swaps without disruption, and so does a change to the rates, ignore_client_bandwidth, the fallback controller or the QUIC settings: it reaches connections that arrive afterwards, and live ones keep the rate and transport parameters they started with. See Planning and applying a change.

supervisor/src/serve.rs → run_hysteria_inbound gives run a make_connector closure. For each connection it calls Shared::connector(tag, Some(ip), Wire::quic(bytes), &stop), which opens a session, and returns the session’s connector and its token. Each QUIC connection is therefore one session, and its usage is the connection’s wire bytes (supervisor/src/entity/usage.rs → Wire::quic); see Per-user usage accounting. A connection that finishes its handshake after the listener was stopped gets no session: the closure returns a plain connector with a token already cancelled, so the connection is closed at once and no session escapes the close of a removed inbound.

When run returns, run_hysteria_inbound calls shutdown. At process shutdown past its grace, once the supervisor’s root token is cancelled, it runs run and shutdown together, so the endpoint is closed under the draining run without waiting for the drain: a client still in its QUIC handshake has no session a root cancel could reach.

Invariant Enforced by Pinned by
No flow is opened for a connection that has not authenticated. The classifier takes the proxy branch only on (true, Some(user)); everything else goes to HTTP/3. The datagram task waits on the authed oneshot before it builds a runtime. a_proxy_stream_before_authentication_is_never_relayed (protocols/tests/pipeline/hysteria.rs); a_connection_starts_unauthenticated (protocols/tests/unit/hysteria/server/shim.rs)
A connection’s identity is set once and never changes. AuthState is a OnceLock; a repeated /auth is answered 233 without re-authenticating. authenticating_records_who, a_second_authentication_cannot_change_the_user (shim.rs unit tests)
A rejected credential is indistinguishable from a wrong URL. answer returns the same Masquerade response and body for both. No test compares the two responses. a_wrong_credential_is_refused (pipeline) and a_wrong_credential_never_gets_a_proxy (app/tests/integration/e2e_hysteria_inbound.rs) pin the refusal itself.
The masquerade never uses the success status. Masquerade::new refuses 233; validate_inbound refuses the spec. the_authentication_success_status_is_refused (protocols/tests/unit/hysteria/server/masquerade.rs); a_masquerade_may_not_answer_with_the_success_status (supervisor/tests/unit/validate.rs)
Classification loses no byte. Classified::replay and PrefixedBidi/PrefixedRecv for HTTP/3; QuicIo’s prefix for proxy streams. a_varint_split_across_chunks_is_still_read, body_bytes_in_the_same_chunk_are_handed_back, replay_puts_the_bytes_back_in_wire_order, classify_then_replay_reconstitutes_an_http3_stream, a_prefixed_stream_reads_as_if_nothing_had_been_consumed (shim.rs unit tests)
Only 0x401 is a proxy stream. classify compares the whole varint with FRAME_TYPE_TCP_REQUEST. a_proxy_stream_is_recognised, anything_else_is_left_to_http3, a_neighbouring_frame_type_is_left_to_http3 (shim.rs unit tests)
A stream that ends unnamed does not leave the classifier waiting. classify returns an error on end of stream. a_stream_that_ends_unnamed_is_an_error (shim.rs unit tests)
Work awaiting classification is bounded. classify_tx capacity MAX_CLASSIFYING_STREAMS, try_send plus discard(H3_EXCESSIVE_LOAD) on overflow; CLASSIFY_TIMEOUT plus discard(H3_REQUEST_CANCELLED). No dedicated test.
The connection limit covers the whole connection. The Admitted place moves into the connection task and is given back when the task ends. No dedicated test.
A changed setting reaches only the connections that arrive after it; an obfuscation change closes the rest. Each connection loads the config and the keyed token once, at arrival; set_obfs cancels keyed. a_new_connection_config_reaches_only_connections_that_arrive_after_it, switching_the_obfuscation_closes_the_old_clients_and_admits_new_ones, a_too_short_obfuscation_key_is_refused_and_changes_nothing (pipeline)
The owner can close one connection alone. The token make_connector returns, watched by serve_connection. a_connections_close_token_closes_that_connection_alone (pipeline)
Stopping drains. Cancelling run’s token refuses new clients and waits for the live ones. cancelling_run_stops_admitting_and_waits_for_the_live_connections (pipeline)
Each connection is one session, billed by its QUIC bytes. run_hysteria_inbound opens a session with Wire::quic per connection. a_hysteria2_session_bills_its_quic_connections_bytes, a_hysteria2_user_set_admits_by_password (supervisor/tests/tracking.rs)
An obfuscation change is disruptive; a masquerade change is not. swap_disruption in the plan. a_hysteria2_obfs_change_swaps_and_disrupts, a_hysteria2_masquerade_change_swaps_without_disrupting (supervisor/tests/unit/plan.rs); a_hysteria2_obfuscation_change_needs_allow_disruptive (supervisor/tests/hot_swap.rs)
The circuit limit covers a circuit’s whole life. The stream permit moves into the spawned runtime task; the session permit lives in Session until the session is removed. UDP sessions: the_circuit_limit_refuses_new_sessions (protocols/tests/unit/hysteria/server/datagrams.rs). Proxy streams: no dedicated test.
A request without a port is never routed. parse_authority(…, 0) and a check for port zero, in both cores. a_request_without_a_port_is_refused (protocols/tests/unit/hysteria/server/inbound.rs); unroutable_packets_are_dropped (datagrams.rs unit tests)
A non-sniffed request is answered only once the target is up, and a stream gets at most one response. reply flag in State::Relay, cleared on Connected. a_request_opens_and_is_answered_once_connected, sniffing_an_ip_target_answers_early_and_opens_with_the_host (inbound.rs unit tests)
A failed connect is answered, not left hanging. Event::ConnectFailed stages a refusal and finishes. a_failed_connect_is_refused_and_finished (unit); a_failed_connect_is_answered_with_a_refusal (pipeline)
Swapping the user table leaves live connections alone. ArcSwap loaded per credential check; identity stored in AuthState. the_user_table_can_be_replaced_under_a_live_inbound (pipeline)
Credential tables are unambiguous. Refusals in user_pass and passwords. names_that_collide_once_lower_cased_are_refused, two_users_sharing_one_credential_are_refused, the_two_table_kinds_do_not_accept_each_others_credentials, a_prefix_of_a_credential_is_refused (authenticator.rs unit tests)
Reassembly memory per session is bounded. Defragger holds one packet and caps it at MAX_UDP_SIZE. fragments_reassemble_into_the_original, a_fragment_index_past_the_count_is_dropped, a_repeated_fragment_does_not_complete_the_datagram (protocols/tests/unit/hysteria/protocol.rs); fragments_from_the_client_are_reassembled_into_a_held_send (datagrams.rs unit tests)
The server answers its down, 0 or auto, and sends at the client’s rate capped by its up, never at a fixed rate when it ignores client bandwidth or the client declared nothing. negotiate::server_rx_header, parse_client_rx and server_tx; Rate::apply on the request that authenticates. a_server_sends_at_the_clients_rx_capped_by_its_up, the_server_answers_its_down_or_auto, an_unreadable_client_rx_is_unknown (protocols/tests/unit/hysteria/negotiate.rs); each_end_sends_at_the_rate_the_two_agreed, ignoring_client_bandwidth_leaves_both_ends_on_congestion_control, a_client_that_declares_nothing_gets_no_fixed_rate_either_way (protocols/tests/pipeline/hysteria_options.rs); a_real_client_and_our_inbound_send_at_the_rates_they_agreed (app/tests/integration/e2e_hysteria_options.rs)
An agreed rate moves only its own connection. One Negotiated factory per accepted connection, through endpoint::for_connection and Incoming::accept_with. No dedicated test; every rate test above runs one connection per server.
A fixed rate holds through loss, sending or receiving. Brutal’s loss compensation on the sender, on unless disable_loss_compensation; on the receiver, the patched quinn-proto’s reassembly cap, which follows the receive window (The quinn patches). a_fixed_rate_holds_through_a_lossy_path (pipeline: this server sending through 3% loss); a_real_client_keeps_its_rate_into_our_inbound_through_loss (e2e_hysteria_options.rs: upstream’s client sending to this inbound through 3% loss)
A server given no rates keeps answering auto. ServerConfig::new sets ignore_client_bandwidth: true; etemenanki-app turns it off only once a rate is given, katana only when told. a_hysteria2_server_given_no_rates_keeps_ignoring_client_bandwidth (app/tests/unit/lower.rs)
A reload that keeps the bind keeps the endpoint and its live clients. Listener::swap reconfigures the running endpoint instead of rebinding. a_reload_keeps_the_inbound_serving_on_its_udp_port (e2e_hysteria_inbound.rs)
Shutdown does not wait out a stalled handshake. run_hysteria_inbound joins run with shutdown once the root token is cancelled. shutdown_does_not_wait_out_a_stalled_hysteria2_handshake (supervisor/tests/hot_swap.rs)
h3 accepts the shim’s transport. const _ block calling assert_transport::<Bytes, Hy2H3Conn<Bytes>>(). Compilation.
h3-quinn’s send stream is never driven through both APIs. QuicIo::poll_write uses only poll_send. Structural; exercised by every proxy-stream test.
Where What happens
open fails (a key too short, or from_socket fails) The error fails Pending::pair during the apply’s prepare; nothing was committed and the socket is dropped.
No connection place, or the listener is stopping incoming.refuse(), logged at debug as hysteria2: refusing a connection; the listener is full or stopping.
QUIC handshake fails The connection task logs hysteria2: a handshake failed: … at debug and ends, giving back its place.
The owner cancels a connection’s token The connection is closed with DISCONNECT_CODE and disconnected by the server.
The obfuscation changes Every connection that arrived under the old one is closed with DISCONNECT_CODE and obfuscation changed.
h3 setup fails Logged at debug (hysteria2 http/3 setup failed: …); the http3 task ends, the Hy2H3Conn is dropped, so the classifier ends and every proxy stream of the connection is aborted.
resolve_request fails, or writing a response fails That request is skipped (a failed resolve_request is logged at debug as hysteria2: could not read a request: …); the connection keeps serving.
Classifier queue full The new stream is reset on both halves with H3_EXCESSIVE_LOAD.
Stream ends before its frame type Logged at debug; the stream is dropped.
Stream sends no frame type within CLASSIFY_TIMEOUT Reset on both halves with H3_REQUEST_CANCELLED.
No circuit permit for a proxy stream Reset on both halves with H3_REQUEST_REJECTED.
No circuit permit, or session cap reached, for a new UDP session The datagram is dropped, logged at trace.
No port in a UDP packet’s address The datagram is dropped without a log line; a permit taken for a new session is released.
Proxy stream runtime fails Logged at debug (hysteria2: proxy stream failed: …); its permit is released when the task ends.
Datagram runtime ends Logged at debug (hysteria2: datagram runtime ended: …); TCP streams on the connection continue.

Cancellation runs top-down. Cancelling run’s token stops admitting: every client that arrives afterwards is refused, and run returns once the connections live at the cancel have ended, been closed through their own tokens, or been closed by shutdown. Dropping run’s future instead drops its connections set, which aborts every connection task and, through their JoinSets, every stream and datagram runtime. Aborted tasks give back their places and permits as they drop.

Dropping a quinn endpoint does not release its UDP port straight away. The socket belongs to quinn’s endpoint driver task, which drops it only on a poll that finds no live connections and no Endpoint handle left; dropping the last handle merely wakes it. A caller that rebinds immediately after wait_idle loses that race every time. Hy2Inbound::shutdown therefore waits on the port itself:

  1. Take the endpoint out of the slot. A second call finds None and returns.
  2. endpoint.close(CLOSE_CODE, b"") with application error code 0x100, which closes every connection.
  3. Wait up to DRAIN_TIMEOUT (3 s) for endpoint.wait_idle().
  4. Drop the endpoint handle.
  5. Try std::net::UdpSocket::bind(local) every RELEASE_POLL (20 ms), for up to RELEASE_TIMEOUT (3 s). If the port is still busy after that, log a warning (hysteria2: <addr> did not come free within 3s) and return.

Closing the endpoint closes every connection on it, so a run still waiting on its connections returns too. In etemenanki-supervisor, run_hysteria_inbound calls shutdown after run returns, for example after an apply removed the inbound and stopped its listener; at process shutdown it runs the two together (see Serving). A reload that keeps an inbound’s bind keeps its endpoint and never rebinds the port.

Constant File Value Bounds
DEFAULT_MAX_CONNECTIONS server/config.rs 262 144 concurrent QUIC connections per listener (app key max_connections)
DEFAULT_MAX_CIRCUITS server/config.rs 4 194 304 proxy streams plus UDP sessions across the listener (app key max_circuits)
QuicOptions::DEFAULT_MAX_INCOMING_STREAMS config.rs 65 536 default concurrent bidirectional streams per connection (app key quic.max_incoming_streams)
QuicOptions::DEFAULT_STREAM_RECEIVE_WINDOW config.rs 8 MiB default per-stream flow-control window
QuicOptions::DEFAULT_CONN_RECEIVE_WINDOW config.rs 20 MiB default per-connection flow-control window
QuicOptions::DEFAULT_MAX_IDLE_TIMEOUT config.rs 30 s default QUIC idle timeout
QuicOptions::MIN_RECEIVE_WINDOW config.rs 16 384 smallest receive window validation accepts
Send window with a fixed rate negotiate.rs → send_window half a second of the rate, at least 10 000 000 bytes what quinn lets a connection have unacknowledged
MAX_CLASSIFYING_STREAMS server/inbound.rs 64 capacity of classify_tx and of h3_ready
CLASSIFY_TIMEOUT server/inbound.rs 10 s time for a stream to send its frame type
MAX_VARINT_BYTES server/shim.rs 8 bytes the classifier needs at most
DRAIN_TIMEOUT server/inbound.rs 3 s wait for wait_idle on shutdown
RELEASE_TIMEOUT, RELEASE_POLL server/inbound.rs 3 s, 20 ms wait for the port on shutdown
CLOSE_CODE server/inbound.rs 0x100 QUIC application close code on shutdown
DISCONNECT_CODE server/inbound.rs 0x107 QUIC application close code when the owner closes one connection or the obfuscation changes
Hy2StreamCore::BUF_SIZE server/inbound.rs 8 KiB cap on each runtime buffer of a proxy stream; the buffers start smaller and grow
Hy2StreamCore::STAGING_RESERVE server/inbound.rs 2048 room for one TCPResponse
Hy2UdpCore::BUF_SIZE server/datagrams.rs 16 KiB cap on each runtime buffer of a datagram channel
Hy2UdpCore::STAGING_RESERVE server/datagrams.rs 4096 fragment headers of one reply
MAX_SESSIONS server/datagrams.rs 256 UDP associations per connection
SWEEP_INTERVAL server/datagrams.rs 1 s idle sweep tick
MAX_UDP_SIZE protocol.rs 4096 reassembled packet and reply payload
MAX_DATAGRAM_FRAME_SIZE protocol.rs 1200 fallback datagram size when quinn reports none
MAX_ADDRESS_LENGTH protocol.rs 2048 address in TCPRequest and UDPMessage
MAX_PADDING_LENGTH protocol.rs 4096 padding on any frame
HANDSHAKE_TIMEOUT, SNIFF_TIMEOUT, RELAY_IDLE_TIMEOUT core/mod.rs, sniff/mod.rs 10 s, 300 ms, 300 s per-phase deadlines of Hy2StreamCore

The supervisor refuses 0 for max_connections and max_circuits, a udp_idle_timeout outside 2 to 600 seconds, and QUIC settings outside upstream’s ranges (see From the spec to a listener). etemenanki-app defaults both limits to the constants above, and katana always uses them, with QuicOptions::server() unchanged. See Limits, timeouts and memory for how these compare with the TCP inbounds.

Layer File What it covers
Unit, shim protocols/tests/unit/hysteria/server/shim.rs Classification (a_proxy_stream_is_recognised, anything_else_is_left_to_http3, a_neighbouring_frame_type_is_left_to_http3, split varints, body bytes in the same chunk, unnamed streams), prefix replay, stop_sending delegation, and AuthState. Uses a fake receive stream, which is why the wrappers are generic.
Unit, obfuscation protocols/tests/unit/hysteria/obfs.rs a_switched_key_reaches_the_next_packet_both_ways, a_closed_gate_reads_nothing_and_opening_it_wakes_the_receiver: the switch and the gate the listener relies on. The rest of the file is on the client page.
Unit, stream core protocols/tests/unit/hysteria/server/inbound.rs Hy2StreamCore under CoreHarness: open and answer on Connected, refusal on ConnectFailed, no-port refusal, early answer with sniffing, an_unfinished_handshake_times_out, transport_eof_finishes_or_shuts_the_outbound.
Unit, datagram core protocols/tests/unit/hysteria/server/datagrams.rs the_first_packet_of_a_session_opens_it_and_sends, a_reply_is_wrapped_for_its_session_and_split_when_too_big, reassembly into SendToHeld, an_idle_session_is_closed_by_the_sweep, the circuit limit, unroutable packets.
Unit, credentials protocols/tests/unit/hysteria/server/authenticator.rs All three tables: splitting on the first colon, case-insensitive names, prefixes refused, build-time refusals, the two multi-user kinds rejecting each other’s credentials.
Unit, masquerade protocols/tests/unit/hysteria/server/masquerade.rs the_default_is_gos_own_not_found, the 233 refusal, invalid status codes, a_configured_response_is_served_whole.
Unit, wire protocols/tests/unit/hysteria/protocol.rs TCPRequest, TCPResponse and UDPMessage encoding, parsing, fragmentation and Defragger.
Unit, rates protocols/tests/unit/hysteria/negotiate.rs The rate rules against upstream’s: a_server_sends_at_the_clients_rx_capped_by_its_up, the_server_answers_its_down_or_auto, an_unreadable_client_rx_is_unknown, loss_compensation_and_send_window, and the client’s two.
Pipeline, tuning protocols/tests/pipeline/hysteria_options.rs This inbound against this crate’s client, rates measured at the receiving end: each_end_sends_at_the_rate_the_two_agreed, ignoring_client_bandwidth_leaves_both_ends_on_congestion_control, a_client_that_declares_nothing_gets_no_fixed_rate_either_way, a_client_hops_across_a_forwarded_port_range_with_obfuscation, a_fixed_rate_holds_through_a_lossy_path. The forwarded port range is protocols/tests/support/udp_range.rs → PortRange; see the client page.
Pipeline protocols/tests/pipeline/hysteria.rs The real inbound on loopback against this crate’s Hy2Connector and a bare Hy2Conn: TCP over two streams of one connection, UDP including 4096-byte payloads fragmented both ways, Salamander, a server without UDP (a_server_without_udp_refuses_associations), wrong credentials, refused targets, the live table swap, and a raw-QUIC proxy stream before authentication. Reconfiguration: a_new_connection_config_reaches_only_connections_that_arrive_after_it, a_connections_close_token_closes_that_connection_alone, cancelling_run_stops_admitting_and_waits_for_the_live_connections, switching_the_obfuscation_closes_the_old_clients_and_admits_new_ones, a_too_short_obfuscation_key_is_refused_and_changes_nothing.
Supervisor validation supervisor/tests/unit/validate.rs hysteria2_takes_a_shared_password_or_a_user_set_but_not_both, a_hysteria2_udp_idle_timeout_is_between_2_and_600_seconds, hysteria2_serves_at_least_one_connection_and_one_circuit, a_masquerade_may_not_answer_with_the_success_status, hysteria2_usernames_collide_case_insensitively, a_hysteria2_username_may_not_hold_a_colon, a_hysteria2_password_may_not_be_empty, a_salamander_key_is_at_least_4_bytes_on_either_side, hysteria2_quic_settings_stay_within_upstreams_limits.
Supervisor plan supervisor/tests/unit/plan.rs a_hysteria2_obfs_change_swaps_and_disrupts, a_hysteria2_masquerade_change_swaps_without_disrupting.
Supervisor, live supervisor/tests/hot_swap.rs, supervisor/tests/tracking.rs a_hysteria2_obfuscation_change_needs_allow_disruptive, shutdown_does_not_wait_out_a_stalled_hysteria2_handshake; a_hysteria2_session_bills_its_quic_connections_bytes, a_hysteria2_user_set_admits_by_password.
App lowering app/tests/unit/lower.rs hysteria2_answers_to_its_aliases; hysteria2_takes_upstreams_bandwidth_quic_and_hopping_settings (an inbound given rates follows upstream’s default and stops ignoring client bandwidth, max_incoming_streams is kept, keep-alive stays off); a_hysteria2_server_given_no_rates_keeps_ignoring_client_bandwidth; hysteria2_tuning_mistakes_are_refused, which includes the server’s keep-alive refusal.
katana lowering katana tests/unit/lower/inbound.rs, tests/unit/lower/spec.rs, tests/unit/api/helium.rs, tests/unit/api/newv2board.rs, tests/unit/manager/node.rs hysteria_refuses_an_unknown_congestion_control, beside the credential, obfuscation, UDP and masquerade refusals and a_panels_masquerade_the_kernel_cannot_answer_with_is_refused; the_nodes_hysteria_udp_and_masquerade_reach_the_spec and a_helium_nodes_check_judges_its_congestion_control; every_protocol_helium_writes_is_read and local_keys_the_panel_describes_are_refused; a_hysteria_node_is_completed_with_the_local_block; only_a_disruptive_change_drops_every_connection.
Interop app/tests/integration/e2e_hysteria_inbound.rs The upstream Go client, built from the vendored tree, against the app’s inbound: TCP, UDP, a_large_datagram_is_fragmented_in_both_directions, obfuscated_traffic_interoperates, a_user_pass_credential_authenticates, a wrong credential, and a_reload_keeps_the_inbound_serving_on_its_udp_port, where a reload with changed settings keeps the socket and a live client connection.
Interop, tuning app/tests/integration/e2e_hysteria_options.rs The upstream client against the app’s inbound over a path with 15 ms of delay each way: a_real_client_and_our_inbound_send_at_the_rates_they_agreed, a_real_client_keeps_its_rate_into_our_inbound_through_loss (3% loss on the way to the server), a_real_client_hops_across_a_forwarded_range_into_our_inbound (a 5 s hop interval over 4 forwarded ports, through Salamander). The same file runs this crate’s client against an upstream server, on the client page.