Skip to content

Server core

Source files: 53 · checked against Etemenanki 46c12e4
  • Etemenanki/concepts/src/core.rs
  • Etemenanki/concepts/src/lib.rs
  • Etemenanki/concepts/src/buffer.rs
  • Etemenanki/concepts/src/runtime.rs
  • Etemenanki/concepts/src/wake.rs
  • Etemenanki/concepts/src/link.rs
  • Etemenanki/concepts/src/sniff.rs
  • Etemenanki/concepts/tests/runtime.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/core/harness.rs
  • Etemenanki/protocols/tests/unit/core/mod.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/error.rs
  • Etemenanki/protocols/src/helpers/address.rs
  • Etemenanki/protocols/src/helpers/crypto.rs
  • Etemenanki/protocols/src/mux/demux.rs
  • Etemenanki/protocols/src/mux/frame.rs
  • Etemenanki/protocols/tests/unit/mux/demux.rs
  • Etemenanki/protocols/src/ss_aead.rs
  • Etemenanki/protocols/tests/unit/ss_aead.rs
  • Etemenanki/protocols/src/vmess/framing.rs
  • Etemenanki/protocols/src/vmess/core.rs
  • Etemenanki/protocols/src/vmess/aead.rs
  • Etemenanki/protocols/tests/unit/vmess/core.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/protocols/src/sniff/collector.rs
  • Etemenanki/protocols/src/http/core.rs
  • Etemenanki/protocols/src/http/protocol.rs
  • Etemenanki/protocols/src/ss_legacy/core.rs
  • Etemenanki/protocols/src/ss_legacy/aead.rs
  • Etemenanki/protocols/src/ss_2022/core.rs
  • Etemenanki/protocols/src/ss_2022/crypto.rs
  • Etemenanki/protocols/src/trojan/core.rs
  • Etemenanki/protocols/src/trojan/protocol.rs
  • Etemenanki/protocols/src/vless/core.rs
  • Etemenanki/protocols/src/vless/addons.rs
  • Etemenanki/protocols/src/vless/vision/framer.rs
  • Etemenanki/protocols/src/anytls/core.rs
  • Etemenanki/protocols/src/anytls/frame.rs
  • Etemenanki/protocols/src/anytls/padding.rs
  • Etemenanki/protocols/src/sss/core.rs
  • Etemenanki/protocols/src/sss/protocol.rs
  • Etemenanki/protocols/src/sss/server.rs
  • Etemenanki/protocols/src/hysteria/protocol.rs
  • Etemenanki/protocols/src/hysteria/server/inbound.rs
  • Etemenanki/protocols/src/hysteria/server/datagrams.rs
  • Etemenanki/protocols/src/tun/udp.rs
  • Etemenanki/protocols/src/tun/inbound.rs
  • Etemenanki/protocols/src/socks/server.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/guard.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/inbound/mod.rs

Every server-side protocol in Etemenanki except SOCKS is a core: a plain Rust value that implements ProxyCoreDecode from concepts/src/core.rs and does no I/O of its own. It owns no socket, spawns no task and never sees a task Context. The per-connection runtime, ProxyServerRuntime in concepts/src/runtime.rs, owns the I/O: it reads bytes, hands them to the core one Event at a time, and carries out the Effects the core pushes back. A core maps bytes and events to bytes and effects, so a test can drive it with hand-built input and assert on the output without opening a socket.

SOCKS is the exception. Its UDP side lives on a second socket that the control connection only keeps alive, which one stream of events cannot express, so SocksInbound in protocols/src/socks/server.rs runs the handshake and then either the CONNECT relay or the UDP ASSOCIATE relay as one task, outside this contract. SOCKS describes it, including which datagrams an association accepts.

This page is the contract between a core and the runtime: the trait, every event and effect, the Effects sink, and the rules that make in-place decryption, held buffers, keys, deadlines and datagrams safe. Read it before writing a new core or changing the delivery logic in concepts/src/runtime.rs. How the runtime schedules its work, wakes outbounds and applies backpressure is on Per-connection runtime. The client-side traits in the same file (ProxyCoreEncodeHandshake, ProxyCoreEncode, ProxyCoreEncodeDatagram, with Opened, OpenedFrom, Handshake, Reply and NoCodec) are on Client runtime.

A core decides; the runtime acts.

The core The runtime (ProxyServerRuntime)
Parses the client’s wire bytes, decrypting in place Reads the transport into a read buffer that grows up to BUF_SIZE
Decides where each flow goes and mints a key for it (Effect::Open) Dials the target through its Connector and keeps one slot per key
Names which byte ranges go to which outbound (Effect::Forward, Effect::SendTo) Writes those ranges without copying them
Seals reply bytes into the staging area Writes the staging area to the transport
Keeps its own timers and arms the earliest one (Effect::SetDeadline) Owns the single tokio timer and delivers Event::Deadline
Says when the connection is over (Effect::Finish) Stops reading, writes out staging, and resolves to the Traffic totals once staging is empty

The runtime passes a core only events and the Effects sink, and gives it its deadlines as Event::Deadline. VMessCore and Ss2022Core also take, in their constructor, the clock their request timestamp check uses. The constructors also take the user tables the cores authenticate against:

Constructor Timestamp-check clock (constructor) Users and shared state
VMessCore::new(validator, now, sniff, source) now: fn() -> i64, the clock the auth id’s timestamp is checked against; serve_connection in supervisor/src/serve.rs passes now_unix from protocols/src/vmess/aead.rs Arc<AccountValidator<T>>; the builder with_hint(Option<UserHint>) names a user to try first, which the supervisor sets on a gRPC connection to the user its last authenticated stream matched
Ss2022Core::new(config, validator, sniff, source, now) now: fn() -> u64, the clock the request timestamp is checked against; Ss2022Core::with_system_clock passes now_unix from protocols/src/ss_2022/crypto.rs, and serve_connection builds the core with with_system_clock Arc<Ss2022ServerConfig<T>>, Option<Arc<Validator<T>>>
ShadowsocksCore::new(inner, sniff, source) — Arc<Resolved<T>>
TrojanCore::new, VlessCore::new — Arc<Validator<T>>
HttpCore::new(config, sniff, source) — Arc<HttpServerConfig<T>>
AnyTlsCore::new(validator, padding, sniff, source) — Arc<Validator<T>> (AnyTLS’s own), plus the Arc<PaddingScheme> pushed to clients
SssCore::new(validator, max_datagram, sniff, source) — Arc<Validator<T>> (sss’s own), plus max_datagram: u16, the most data one datagram record carries
Hy2StreamCore::new(user, sniff, source) — UserEntry<T>, the user the QUIC connection authenticated as
Hy2UdpCore::new(user, source, idle_timeout, max_datagram, circuit_permits) — UserEntry<T>, plus the listener’s circuit_permits semaphore
PassthroughCore::new(flow), PassthroughCore::sniffing(flow) — the Flow<T> it relays
TunUdpCore::new(user, source) — Arc<T>, the TUN inbound’s user payload

Hy2UdpCore has a clock of its own that no constructor supplies: it counts sweep ticks (now: u64), one for every SWEEP_INTERVAL deadline it arms and receives.

Who runs each core at 46c12e4:

Core Driven by One runtime per
HttpCore, TrojanCore, VlessCore, VMessCore, ShadowsocksCore, Ss2022Core, AnyTlsCore drive in supervisor/src/serve.rs, in stream mode, called from serve_connection with a closure that builds the core byte stream the inbound’s transport yields: the connection the listener accepted or a relay handed over, or on a gRPC carrier each HTTP/2 stream, which is a session of its own
SssCore (protocols/src/sss/core.rs) drive, called from serve_sss in supervisor/src/serve.rs once sss’s gate has admitted the stream admitted sss stream, over its decoded side
Hy2StreamCore (protocols/src/hysteria/server/inbound.rs) the Hysteria 2 listener proxy stream of a QUIC connection
Hy2UdpCore (protocols/src/hysteria/server/datagrams.rs) the Hysteria 2 listener, over QuicDatagrams QUIC connection’s datagram channel
PassthroughCore (protocols/src/core/mod.rs) serve_stream in protocols/src/tun/inbound.rs TCP flow of a TUN device
TunUdpCore (protocols/src/tun/udp.rs) the TUN inbound, over TunUdpLink client source’s UDP flows

Two protocols put something in front of their core:

  • sss reads each stream’s request header through its pre-authentication gate, sss::accept in protocols/src/sss/server.rs, before any runtime exists. An admitted stream gets a runtime sized for its command (SssCore::TCP_BUF_SIZE or SssCore::UDP_BUF_SIZE) over the side its transform chains decode, and the core reads the header again from there. A refused stream gets no runtime: it is drained or handed to a fallback. See sss.
  • VLESS with the XTLS Vision flow. VlessCore decodes the request’s flow addon (VlessFlow in protocols/src/vless/addons.rs) but serves only plain VLESS: a request from a known user whose flow is not VlessFlow::None fails with vless flow (xtls vision) is not served by this core (Unsupported). The user lookup comes first, so an unknown id fails with PermissionDenied whatever flow it asks for, as the credential contract in protocols/src/core/mod.rs requires. Vision is served by a stream adapter that the supervisor wraps around the REALITY stream of an inbound whose flow is Vision, before the core sees it. The adapter strips the flow addon from the request header and removes Vision’s framing, so the core reads plain VLESS through it. See XTLS Vision.

The supervisor instantiates every core with the user payload T = Principal. supervisor/src/topology/flow.rs defines pub type Flow = etemenanki_protocols::flow::Flow<Principal>, so each flow carries the principal its inbound admitted it as (Users, principals and sessions). The protocols crate’s own tests use (). katana v4 serves its nodes through etemenanki-supervisor and implements no core of its own.

concepts/src/lib.rs declares the crate’s nine modules (buffer, client, core, link, net, relay, runtime, sniff, wake) and states the shape they serve: one ProxyServerRuntime per proxied connection owns the client’s transport, every outbound it opens and the core, and an outbound routed through an upstream proxy is a ProxyClientRuntime that runs inside the same task. The whole server contract lives in concepts/src/core.rs. The building blocks the in-tree cores compose live in protocols/src/core/mod.rs (see Building blocks).

concepts/src/core.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Single;
pub trait ProxyCoreDecode {
type Key: Copy + Ord + Send + Sync + 'static;
type Target;
type Error;
type TransportAddr: Clone + Send + Sync + 'static;
const STAGING_RESERVE: usize;
const MAX_DATAGRAM: usize = 4096;
fn handle(
&mut self,
event: Event<'_, Self>,
effects: &mut Effects<'_, Self>,
) -> Result<usize, Self::Error>;
fn held(&self) -> &[u8] {
&[]
}
}
Item Meaning
Key Names one outbound. The core mints keys with Effect::Open, and every outbound-side event carries the key it came from. A core with exactly one outbound uses the unit struct Single. The runtime keeps its slots in a BTreeMap<Core::Key, _>, hence Ord. Send + Sync + 'static is what KeyWaker<K> (concepts/src/wake.rs) needs to implement std::task::Wake, since each outbound is polled with a waker that records its key.
Target What the runtime’s Connector dials (Connector::connect(&mut self, target) -> Self::Future, concepts/src/link.rs). For every in-tree server core it is Flow<T>.
Error Returned from handle; the runtime wraps it as RuntimeError::Core and ends the connection. Every in-tree core uses io::Error.
TransportAddr The peer address of a datagram transport packet: what Event::TransportDatagram arrives from and Effects::stage_to sends to. It must equal the transport link’s own address type: the runtime’s impls require Trans: Transport<Addr = Core::TransportAddr>, and over_datagrams takes a D: DatagramLink<Addr = Core::TransportAddr>. It is Clone because the runtime clones each packet’s peer out of the PacketList when it sends the packet. TunUdpCore declares SocketAddr: its TunUdpLink addresses each packet by the far end the client addressed. Hy2UdpCore declares (), because a QUIC connection’s datagrams have exactly one peer, and so does every byte-stream core.
STAGING_RESERVE The most bytes the core stages toward the transport while handling one event, beyond the payload of that event. See The staging reserve.
MAX_DATAGRAM The largest datagram delivered whole, from a datagram outbound or a datagram transport. A longer packet is truncated the way a kernel recv truncates. Default 4096.
handle Advance the state machine by one event. Returns how many leading bytes of a byte-carrying event were consumed.
held Bytes the core keeps on its own account and forwards by range with ForwardHeld or SendToHeld. Empty by default. See The held buffer.

The runtime’s impls also require Conn::Datagram: DatagramLink<Addr = Destination>: a datagram outbound is always addressed by a Destination from concepts/src/net.rs, whatever the transport side uses.

concepts/src/core.rs
pub enum Event<'a, C: ProxyCoreDecode + ?Sized> {
Transport(&'a mut [u8]),
TransportDatagram {
from: C::TransportAddr,
data: &'a mut [u8],
},
TransportSendFailed {
to: C::TransportAddr,
error: io::Error,
},
TransportEof,
Outbound { key: C::Key, data: &'a mut [u8] },
Datagram {
key: C::Key,
from: Destination,
data: &'a mut [u8],
},
SendFailed {
key: C::Key,
to: Destination,
error: io::Error,
},
OutboundEof { key: C::Key },
Connected { key: C::Key },
ConnectFailed { key: C::Key, error: io::Error },
OutboundError { key: C::Key, error: io::Error },
Deadline,
}

Event implements Debug by hand, bounded on C::Key: Debug and C::TransportAddr: Debug. It prints the length of each byte slice, never its contents, together with the keys, the peer addresses (from, to) and the error values.

Event When the runtime delivers it What handle must return
Transport(data) A byte-stream transport produced bytes. data is the whole unparsed region of the read buffer, including any tail the core left on the previous call. Bytes consumed from the front, 0..=data.len(). The rest is offered again.
TransportDatagram { from, data } A datagram transport produced one whole packet. Never delivered over a stream transport. Exactly data.len().
TransportSendFailed { to, error } A packet staged toward peer to was refused by the link and dropped. Not fatal: the core decides whether to forget the peer. 0 by convention; the count is not checked.
TransportEof The stream transport’s read side ended. A datagram transport never delivers it. 0 by convention.
Outbound { key, data } Stream outbound key produced bytes, read into the scratch buffer. Exactly data.len(): there is no per-outbound buffer to keep a remainder in.
Datagram { key, from, data } Datagram outbound key produced one packet. from is the packet’s source; a link that resolves domains reports the address it received from, as an IP. Exactly data.len().
SendFailed { key, to, error } An Effect::SendTo or SendToHeld on datagram outbound key was refused by the link. The packet is dropped and the key stays live. 0 by convention.
OutboundEof { key } Stream outbound key’s read side ended. 0 by convention.
Connected { key } The dial started by Effect::Open for key completed. 0 by convention.
ConnectFailed { key, error } The dial failed. The key is already gone. 0 by convention.
OutboundError { key, error } Outbound key failed while being read, written, flushed or shut down, or a write returned zero bytes (WriteZero). The key is already gone. 0 by convention.
Deadline The deadline armed by Effect::SetDeadline passed. It is now disarmed. 0 by convention.

The runtime checks the consume rules in three places: feed_transport (more than the slice), poll_transport_recv_packet (anything but the whole packet) and after_scratch (anything but the whole outbound payload). A violation ends the connection with RuntimeError::BadConsume. For the events that carry no bytes, the runtime ignores the returned count.

concepts/src/core.rs
pub enum Effect<C: ProxyCoreDecode + ?Sized> {
Forward { key: C::Key, range: Range<usize> },
SendTo {
key: C::Key,
to: Destination,
range: Range<usize>,
},
ForwardHeld { key: C::Key, range: Range<usize> },
SendToHeld {
key: C::Key,
to: Destination,
range: Range<usize>,
},
Open { key: C::Key, target: C::Target },
Shutdown { key: C::Key },
Close { key: C::Key },
ShutdownTransport,
SetDeadline(Option<Duration>),
Finish,
}

Effect has a hand-written Debug as well, bounded on C::Key: Debug and C::Target: Debug. ProxyServerRuntime::drive_effects applies the queued effects; Push order and pinned buffers says which ordering a core can rely on.

Effect What applying it does Completes when
Forward Writes range of the event’s slice to stream outbound key, then calls poll_flush. A short write advances range.start and writes the rest. A write of zero bytes removes the outbound and delivers OutboundError with WriteZero; any other write or flush error does the same with that error. An empty range is dropped without looking at the key. Every byte of the range is written. A flush that returns Pending is finished the next time the key is serviced (Slot::need_flush).
SendTo Sends range of the event’s slice as one datagram to to through datagram outbound key (DatagramLink::poll_send_to). An empty range is sent as an empty datagram. The packet has been handed to the link in one poll_send_to. A refusal drops the packet, keeps the key and delivers SendFailed.
ForwardHeld As Forward, but range indexes held(), resolved when the bytes are written. As Forward.
SendToHeld As SendTo, but range indexes held(). As SendTo.
Open Checks that key has no slot (DuplicateKey otherwise), calls connector.connect(target), stores the boxed dial future as LinkState::Connecting in a new slot with a fresh KeyWaker from ReadyQueue::waker(key), and schedules the key so the runtime polls the dial. The dial runs on after the effect. Its result arrives as Connected or ConnectFailed, and forwards to the key pushed in the same batch are written once it has connected.
Shutdown Half-closes the write side of stream outbound key with poll_shutdown. It marks the write side closed and removes the slot if the read side had already ended. A shutdown error removes the outbound and delivers OutboundError. poll_shutdown has returned Ready. On a datagram outbound it needs no I/O.
Close Removes the slot for key in both directions, including a dial still in flight. No event follows. Close of a key with no slot does nothing. No I/O.
ShutdownTransport Sets a flag. Over a byte stream, the runtime half-closes the transport’s write side once staging is written and flushed. Over a datagram transport, it marks the write side closed once the staged packets are sent. No I/O; the half-close follows as described.
SetDeadline(after) Some(d) arms the single timer for d from now, replacing any earlier deadline. None disarms it. No I/O.
Finish Marks the connection over. The runtime stops reading the transport and the outbounds, keeps writing staging, and resolves once staging is empty and a requested ShutdownTransport is done. It does not wait for effects the core pushed after Finish. No I/O.
concepts/src/core.rs
pub const INLINE_EFFECTS: usize = 4;
pub type EffectList<C> = SmallVec<[Effect<C>; INLINE_EFFECTS]>;
pub type PacketList<A> = VecDeque<(usize, A)>;
pub struct Effects<'a, C: ProxyCoreDecode + ?Sized> {
list: &'a mut EffectList<C>,
staging: Staging<'a>,
/// `Some` under a datagram transport.
packets: Option<&'a mut PacketList<C::TransportAddr>>,
}
impl<'a, C: ProxyCoreDecode + ?Sized> Effects<'a, C> {
pub fn new(list: &'a mut EffectList<C>, staging: Staging<'a>) -> Self;
pub fn with_packets(
list: &'a mut EffectList<C>,
staging: Staging<'a>,
packets: &'a mut PacketList<C::TransportAddr>,
) -> Self;
pub fn push(&mut self, effect: Effect<C>);
pub fn staging(&mut self) -> &mut Staging<'a>;
pub fn stage(&mut self, bytes: &[u8]) -> Option<()>;
pub fn transport_is_datagram(&self) -> bool;
pub fn stage_to(&mut self, to: C::TransportAddr, len: usize) -> Option<&mut [u8]>;
pub fn put_to(&mut self, to: C::TransportAddr, bytes: &[u8]) -> Option<()>;
pub fn list(&self) -> &[Effect<C>];
}
Method Use
new / with_packets The runtime builds the sink once per call to handle: new over a byte-stream transport, with_packets over a datagram transport.
push Append an effect. The list belongs to the runtime and is reused across calls; it holds INLINE_EFFECTS (4) effects inline before it spills to the heap, because a handshake typically pushes three: SetDeadline, Open and Forward.
staging The transport-bound Staging area. Staging::reserve(len) claims len bytes at the tail and returns them for filling, which is how a frame is sealed in place with no intermediate Vec. Staging::room says how much is free.
stage Copy bytes toward a byte-stream transport (Staging::put). None when the room is too small; for an event that came with its reserve, that means the core exceeded its STAGING_RESERVE.
transport_is_datagram true when the sink was built with with_packets, so staged bytes need a peer.
stage_to Claim len bytes as one packet toward to and return them for filling. It pushes (len, to) onto the PacketList. None if there is not enough room, or if the transport is a byte stream.
put_to Copy bytes as one packet toward to; stage_to plus a copy.
list The effects pushed so far, for a core that inspects its own output in tests.

Staging is the append-only view of the runtime’s transport-bound WriteBuffer<BUF_SIZE> that the sink wraps:

concepts/src/buffer.rs
pub struct Staging<'a> {
data: &'a mut Vec<u8>,
end: &'a mut usize,
limit: usize,
}
impl Staging<'_> {
pub fn room(&self) -> usize;
pub fn reserve(&mut self, len: usize) -> Option<&mut [u8]>;
pub fn put(&mut self, bytes: &[u8]) -> Option<()>;
}

reserve claims len bytes at the tail and counts them as staged at once; the core fills them in place. room counts against limit, the buffer’s BUF_SIZE, not against what is allocated: when a reservation runs past the current storage, reserve grows the Vec to the larger of the reservation’s end, twice the current length and 2 KiB, never past limit. put is reserve plus a copy, and Effects::stage is put. Staging never commits part of a request: a reserve that does not fit returns None and stages nothing (staging_refuses_over_reservation_without_partial_commit in concepts/src/buffer.rs). The sealing code in the cores keeps the same rule one level up: ChunkEncoder::seal_record in protocols/src/ss_aead.rs stages nothing and leaves its nonce untouched when a record does not fit (a_refused_seal_stages_nothing_and_keeps_the_counter).

WriteBuffer keeps [start .. end) as the bytes staged and not yet written. It holds no storage until the first stage (write_buffer_holds_nothing_until_a_stage). Before it hands out a Staging, WriteBuffer::staging calls WriteBuffer::room, which slides the pending bytes to the front when the free tail is used up (start != 0 && end == N); that slide is the only copy the staging buffer makes on its own (write_buffer_slides_pending_when_full). advance_start resets both offsets to zero once everything is written. The rest of the WriteBuffer and ReadBuffer API is on Per-connection runtime.

The runtime builds the sink with Effects::new. The core appends with stage or staging().reserve(..). poll_transport_write writes the whole pending region of the WriteBuffer to the transport; a write of zero bytes ends the connection with RuntimeError::Transport (WriteZero).

protocols/src/flow.rs
pub struct Flow<T> {
pub destination: Destination,
pub user: NetworkUser<T>,
pub sniffed: Option<SniffedBehavior>,
pub source: Option<IpAddr>,
}
impl<T> Flow<T> {
pub fn new(destination: Destination, user: NetworkUser<T>, source: Option<IpAddr>) -> Self;
pub fn toward(&self, destination: Destination) -> Self;
}

Flow<T> is the Target of every core in etemenanki-protocols. destination is where the request goes; for a UDP flow it is the first packet’s, and later packets carry their own address in Effect::SendTo. user is the NetworkUser<T> the core built for the user it admitted; its user_data is an Arc<T>. sniffed is what sniffing recovered, a SniffedBehavior { protocol, domain } from concepts/src/sniff.rs, when the inbound sniffs and the destination named only an IP. source is the client’s address when the inbound knows it. Flow::new starts with nothing sniffed. Flow::toward builds a sub-flow toward another destination that shares the carrier’s user and source, with sniffed reset. Clone is written out by hand so that cloning does not require T: Clone: the payload is only ever behind an Arc.

The in-tree cores do not inherit from a base type. They compose three small helpers from protocols/src/core/mod.rs, are generic over the user payload T, fail with io::Error, and expose an inherent is_established() so the caller can tell a client that never completed its request from one that is being served. supervisor/src/serve.rs reaches that method through its Established trait, which it implements for the eight cores drive serves: through the established! macro, and by hand for VMessCore.

protocols/src/core/mod.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase { Handshake, Sniff, Relay, Closing }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Expired { Handshake, Sniff, Idle }
pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
pub const RELAY_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
#[derive(Debug, Clone, Copy)]
pub struct Timing {
phase: Phase,
armed: bool,
}
impl Default for Timing { /* Timing::new() */ }
impl Timing {
pub fn new() -> Self;
pub fn phase(&self) -> Phase;
pub fn is_established(&self) -> bool;
pub fn touch<C: ProxyCoreDecode>(&mut self, fx: &mut Effects<'_, C>);
pub fn enter<C: ProxyCoreDecode>(&mut self, phase: Phase, fx: &mut Effects<'_, C>);
pub fn expired<C: ProxyCoreDecode>(&mut self, fx: &mut Effects<'_, C>) -> Expired;
}
pub fn handshake_timed_out() -> io::Error;
stateDiagram-v2
  [*] --> Handshake
  Handshake --> Sniff: enter Sniff
  Handshake --> Relay: enter Relay
  Sniff --> Relay: enter Relay
  Relay --> Closing: idle deadline, Finish pushed
Phase Deadline armed On Deadline, expired returns
Handshake HANDSHAKE_TIMEOUT (10 s), armed once by the first touch Expired::Handshake; the core returns handshake_timed_out(), an io::ErrorKind::TimedOut error with the text client did not complete its request in time
Sniff SNIFF_TIMEOUT (300 ms), armed by enter(Phase::Sniff); touch does nothing here Expired::Sniff; the core opens the flow with what it collected
Relay, Closing RELAY_IDLE_TIMEOUT (300 s), armed by enter and re-armed by touch on every byte event Expired::Idle; Timing has already pushed Effect::Finish and moved to Closing

is_established() is true in Relay and Closing, so established means the request is parsed and the flow is open or opening, not that the outbound has connected. A core that opens a stream flow enters Phase::Relay before it pushes Open (see Push order and pinned buffers). Every call to enter or touch that arms pushes one SetDeadline; expired clears the armed flag. Re-arming on every byte event is what makes the relay limit an idle limit rather than a lifetime. Phase::Closing is entered only by expired on an idle deadline: no core calls enter(Phase::Closing).

Timing::new arms nothing, and the first touch arms HANDSHAKE_TIMEOUT. drive in supervisor/src/serve.rs also runs its runtime in the showing_progress stream mode and wraps each step it takes before is_established() turns true in tokio::time::timeout(HANDSHAKE_TIMEOUT, runtime.next()). That limit applies to each step, not to the handshake as a whole. A step that times out fails the connection with inbound handshake timed out after 10s (TimedOut).

drive also reports how the handshake ended to the supervisor’s guard (supervisor/src/guard.rs → Report). The module docs of protocols/src/core/mod.rs state the contract it relies on: 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 step that ends in RuntimeError::Core with kind PermissionDenied before is_established() turns true calls report.failed(), and reaching an established core calls report.succeeded(runtime.core().user_hint()). user_hint comes from the supervisor’s Established trait and is None for every core but VMessCore, whose user_hint() names the user its auth id matched once it has matched. drive takes the core as a closure (make_core: impl FnOnce() -> Core) and builds it inside, because an async fn keeps its arguments in its future and the runtime built from a core in hand would hold a second copy. Listeners and the serve loop describes drive in full.

protocols/src/core/mod.rs
#[derive(Debug, Default)]
pub struct SniffPrefix {
collector: Collector,
}
impl SniffPrefix {
pub fn new() -> Self;
pub fn push(&mut self, plain: &[u8]) -> (usize, Verdict);
pub fn held(&self) -> &[u8];
pub fn found(&self) -> Option<&SniffedBehavior>;
pub fn result(&self) -> Option<SniffedBehavior>;
pub fn clear(&mut self);
pub fn is_empty(&self) -> bool;
}

SniffPrefix wraps the sniff Collector from protocols/src/sniff/collector.rs, the clock-free half of sniffing: it carries no deadline, because the core arms the runtime’s deadline itself. A Collector owns no memory until the first non-empty push, which reserves the whole SNIFF_LIMIT in one allocation, so filling the budget never reallocates; every core builds one when a connection is accepted, but only a flow that reaches its sniff phase fills it. push(plain) takes at most Collector::remaining() bytes, what is left of the SNIFF_LIMIT (4 KiB) budget, appends them, runs the sniffers again if nothing has been found yet (sniff, TLS first, then HTTP), and returns (taken, Verdict):

Verdict Meaning
Found A sniffer recognised the bytes; nothing more is needed. The collector keeps the result, so a later push that takes bytes returns Found again.
More Nothing recognised yet and the budget is not spent. An empty plain with budget left also returns More.
Exhausted The budget is spent without a match. With the budget spent, a push takes 0 bytes and returns Exhausted.

The core consumes exactly taken. held() exposes the collected bytes for the ForwardHeld. found() borrows the recovered SniffedBehavior; result() returns a clone of it for the flow and leaves the bytes in place for the forward. clear() drops the collected bytes and frees their buffer, by replacing the collector with a new one; a core calls it at the top of the next byte event, which the held-buffer rule makes safe. is_empty() is true while nothing is collected. worth_sniffing in protocols/src/sniff/mod.rs limits sniffing to destinations that name an IP (Remote::IpAddr): a domain already routes by name, and waiting would cost such a flow up to SNIFF_TIMEOUT. Sniffing covers the rest of the collector, the TLS and HTTP sniffers and plausible_domain.

Passthrough<K> (#[derive(Debug, Clone, Copy)]) is the relay tail of a protocol with one stream outbound. It holds the key and two end-of-stream flags, and pushes the matching half-close:

Method Effects pushed
new(key), key(), is_done() none; is_done is true once both halves have ended
on_transport(data, fx) Forward { key, range: 0..data.len() }; returns data.len()
on_outbound(data, fx) none; stages data verbatim, or fails with staging_full()
on_outbound_eof(fx) ShutdownTransport, then Finish if the transport already ended
on_transport_eof(fx) Shutdown { key }, then Finish if the outbound already ended
on_outbound_gone(fx) ShutdownTransport, Finish (after ConnectFailed or OutboundError); marks both halves ended, and the staged bytes still drain

PassthroughCore<T> relays a flow whose destination is known before the first byte. The TUN inbound uses it, because the IP stack has already said where the client is going. It declares Key = Single, Target = Flow<T>, Error = io::Error, TransportAddr = (), STAGING_RESERVE = 0 and BUF_SIZE = 8 * 1024.

protocols/src/core/mod.rs
pub struct PassthroughCore<T> {
pending: Option<Flow<T>>,
sniff: bool,
prefix: SniffPrefix,
relay: Passthrough<Single>,
timing: Timing,
}
impl<T> PassthroughCore<T> {
pub const BUF_SIZE: usize = 8 * 1024;
pub fn new(flow: Flow<T>) -> Self;
pub fn sniffing(flow: Flow<T>) -> Self;
pub fn is_established(&self) -> bool;
}

sniffing sets the sniff flag only when worth_sniffing(&flow.destination) holds. The private open takes the pending flow, fills in sniffed from the prefix, enters Phase::Relay (which pushes SetDeadline), then pushes Open and a ForwardHeld of the prefix if it holds any bytes. Traced through passthrough_core_opens_on_the_first_bytes_and_relays_verbatim and a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host:

  1. First bytes, no sniffing. Transport(b"hello") is the first event, and it opens the flow. The effects are SetDeadline(Some(RELAY_IDLE_TIMEOUT)) from enter(Phase::Relay), Open { key: Single, target }, a second SetDeadline from touch, and Forward { range: 0..5 }. The call returns 5.

  2. Downlink. Outbound { data: b"world" } pushes SetDeadline(Some(RELAY_IDLE_TIMEOUT)) and stages world verbatim.

  3. Both halves close. TransportEof pushes Shutdown { key: Single }; OutboundEof then pushes ShutdownTransport and Finish.

  4. Sniffing instead. Built with PassthroughCore::sniffing and an IP destination, the first Transport(b"GET / HTTP/1.1\r\nHo") only pushes SetDeadline(Some(SNIFF_TIMEOUT)) and consumes all 18 bytes into SniffPrefix.

  5. Host found. The next Transport(b"st: example.com\r\n\r\nbody") completes the Host header. The core pushes SetDeadline(Some(RELAY_IDLE_TIMEOUT)), Open with sniffed.domain == "example.com", and ForwardHeld { range: 0..41 } (all collected bytes, body included).

  6. Held buffer released. Under a runtime, no held effect is still queued when the following Transport(b"more") arrives. The core re-arms the idle deadline, clears the prefix, and forwards 0..4 from the event slice. The harness applies nothing, so the test checks the Forward of 0..4 and that held() is empty afterwards.

If the sniff deadline fires first, Expired::Sniff opens the flow the same way, SetDeadline, then Open with sniffed: None, then a ForwardHeld of what was collected (a_sniffing_passthrough_core_opens_on_the_sniff_deadline). A domain destination skips sniffing entirely (a_sniffing_passthrough_core_with_a_domain_target_opens_at_once). TransportEof also opens a flow that is still pending, with whatever the prefix collected, and then pushes Shutdown for it. ConnectFailed or OutboundError drops the pending flow and calls on_outbound_gone, and Expired::Handshake returns handshake_timed_out(). The datagram events are ignored with a count of 0.

Every core that sniffs does so only when its inbound enables sniffing, which the caller passes as the sniff constructor argument, or for PassthroughCore by building it with sniffing instead of new.

Core held() returns Sniffs Established when
HttpCore the rewritten origin-form head of a plain request, otherwise the sniff prefix a CONNECT to an IP, after it has already answered 200, because the client sends nothing before that reply Timing in Relay
ShadowsocksCore the payload that followed the address (with the sniff prefix in front when the budget ran out mid-payload), otherwise the sniff prefix an IP destination Timing in Relay
Ss2022Core the sniff prefix an IP destination Timing in Relay
TrojanCore, VlessCore the sniff prefix, or Demux::held() on a mux carrier (empty for these unencrypted carriers, which leave a partial frame in the read buffer) a TCP request to an IP destination; mux sub-flows from their New payload Timing in Relay
VMessCore the sniff prefix, or Demux::held() on a mux carrier: frames split across VMess chunks as Trojan and VLESS Timing in Relay
AnyTlsCore UDP-over-TCP packets reassembled across frames, for SendToHeld a TCP stream to an IP, from the data that arrived with its address in the same event; the stream opens at once Timing in Relay, entered once the password and padding0 are read
SssCore the sniff prefix a TCP request to an IP destination Timing in Relay
Hy2StreamCore the sniff prefix an IP destination, after staging the TCPResponse, because the client sends nothing before it Timing in Relay
Hy2UdpCore the last reassembled packet, for SendToHeld never always
PassthroughCore the sniff prefix when built with sniffing and the destination is an IP Timing in Relay
TunUdpCore nothing never after the first packet opened the association

One runtime drives exactly one core. It calls handle synchronously from inside its own poll, so a core never runs concurrently with itself and its own per-connection state needs no synchronisation.

sequenceDiagram
  participant T as Transport
  participant R as ProxyServerRuntime
  participant C as Core
  participant O as Outbound
  T->>R: bytes into the read buffer
  R->>C: handle(Event::Transport(unparsed))
  C-->>R: consumed, Open(k) + Forward(k, range)
  R->>R: validate ranges, queue the effects
  R->>O: Open applied: connector.connect(target)
  Note over R: Forward(k) is written once k has connected
  O-->>R: dial completes
  R->>C: handle(Event::Connected(k))
  R->>O: Forward applied: write range
  O-->>R: reply bytes into scratch
  R->>C: handle(Event::Outbound(k, data))
  C-->>R: sealed reply in staging
  R->>T: write staging

Every delivery goes through the same three steps, whatever the event:

  1. ProxyServerRuntime::deliver builds the sink over the staging buffer and calls handle. Under a datagram transport it also checks that everything staged was framed into packets.
  2. enqueue validates each ranged effect. An event-slice range (Forward, SendTo) must satisfy range.start <= range.end <= len of the slice and is rebased onto the buffer it indexes; a held range must fit held().len(). Each effect is tagged with its Source (Transport, Scratch or Held) and appended to the queue.
  3. drive_effects applies the queued effects.

Effects a core pushes while answering a notification (Connected, Deadline, OutboundError and the rest) go through the same checks. A notification carries no bytes, so enqueue checks its event-slice ranges against an empty slice: a Forward or SendTo pushed from a notification must have an empty range, or the connection ends with RangeOutOfBounds. Held ranges are checked against held() as usual.

flowchart TB
  ev["Event ready"] --> deliver["deliver: core.handle(event, effects)"]
  deliver --> peer{"datagram transport: every staged byte in a packet?"}
  peer -- no --> swp["RuntimeError::StagedWithoutPeer"]
  peer -- yes --> check{"consume count valid?"}
  check -- no --> bad["RuntimeError::BadConsume"]
  check -- yes --> enq["enqueue: check ranges, rebase, tag source buffer"]
  enq --> oob{"range in bounds?"}
  oob -- no --> rng["RuntimeError::RangeOutOfBounds"]
  oob -- yes --> drive["drive_effects: apply queued effects"]
  drive --> wait["return to the scheduler"]

concepts/tests/runtime.rs drives a toy multiplexing protocol, TinyMux, whose frames are [kind][key][len:u16][payload] with an XOR “cipher” (XOR = 0x55, HDR = 4, kinds OPEN = 1, DATA = 2, CLOSE = 3, FIN = 4, CONNECTED = 5, CONNECT_FAILED = 6, EOF = 7). It declares Key = u8, Target = String, Error = String, TransportAddr = () and STAGING_RESERVE = HDR + 64. Its transport arm is the canonical parse loop:

concepts/tests/runtime.rs (excerpt)
Event::Transport(buf) => {
let mut consumed = 0;
loop {
let rest = &mut buf[consumed..];
if rest.len() < HDR {
break;
}
let (k, key) = (rest[0], rest[1]);
let len = u16::from_be_bytes([rest[2], rest[3]]) as usize;
if rest.len() < HDR + len {
break;
}
let payload = &mut rest[HDR..HDR + len];
for b in payload.iter_mut() {
*b ^= XOR;
}
let (start, end) = (consumed + HDR, consumed + HDR + len);
match k {
kind::OPEN => { /* insert key, push Effect::Open */ }
kind::DATA => fx.push(Effect::Forward { key, range: start..end }),
kind::CLOSE => fx.push(Effect::Shutdown { key }),
kind::FIN => { /* ShutdownTransport, Finish */ }
other => return Err(format!("bad frame kind {other}")),
}
consumed = end;
}
/* optional idle SetDeadline */
Ok(consumed)
}

core_is_driven_without_any_io drives it with no runtime at all:

  1. Input. The test builds OPEN 9 "somewhere", DATA 9 "hi" and the first 5 bytes of DATA 9 "split", and calls handle(Event::Transport(&mut input), &mut fx) over an Effects::new sink on a WriteBuffer::<256>.

  2. Parse frame by frame. The core decodes the two complete frames and stops at the incomplete third one. It returns HDR + 9 + HDR + 2, the offset where the split frame starts. A runtime would keep those 5 bytes and offer them again, prefixed to the next read.

  3. Effects. The list holds Open { key: 9, target: "somewhere" } then Forward { key: 9, range: 17..19 }. The range is relative to the slice the core was given; the runtime rebases it onto the read buffer when it queues the effect.

  4. In place. input[17..19] now reads hi: the payload was decrypted where it lay, and the forward writes it with no copy.

  5. Connected. handle(Event::Connected { key: 9 }) stages the frame [5, 9, 0, 0] (kind::CONNECTED). No effect is needed.

  6. Downlink. handle(Event::Outbound { key: 9, data: b"pong" }) seals a DATA frame into staging with fx.staging().reserve(HDR + len) and returns 4, the whole payload.

The same core then runs under a real ProxyServerRuntime over tokio::io::duplex pipes:

  • relays_two_keys_and_completes_on_fin opens two keys, relays hello and world up and back from two down, and after FIN checks the totals: outbound_tx = 10, outbound_rx = 13, and transport byte counts that include every frame header. The client then reads end of stream, because FIN pushed ShutdownTransport before Finish.
  • half_close_propagates_both_ways_and_finishes closes the client’s write side after DATA 1 "last words". The core answers TransportEof with a Shutdown per open key; the far end reads the payload then end of stream, replies bye and closes, and the last frame the client sees is EOF.
  • connect_failure_reaches_the_core_as_an_event opens the target "fail", which the test dialer refuses, and checks that the client receives CONNECT_FAILED carrying the dial error text refused by test.

Event::Transport hands the core the whole unparsed region [start .. end) of the ReadBuffer. The core returns how much of its front it consumed, and feed_transport advances start by that count. The unconsumed rest is offered again: on its own after a call that made progress, or prefixed to newly read bytes after a call that consumed nothing. A core parses frame by frame, stops at the first incomplete frame and returns the offset of its start.

  • Mechanism: ReadBuffer keeps its three regions in place: [0 .. start) parsed, and possibly still referenced by a queued forward; [start .. end) read and not yet parsed; [end .. data.len()) free, where the storage data starts at min(2048, N) bytes and never exceeds N. When the free tail is used up, the runtime calls ReadBuffer::make_room, which moves the unparsed tail to the front and doubles the storage while it is below N; ReadBuffer::compact only moves the tail (a reset when everything is parsed), and doubles only when the move frees nothing. The runtime moves bytes only when no queued effect still references bytes before start.
  • Tests: core_is_driven_without_any_io (the split frame stays unconsumed) in concepts/tests/runtime.rs; read_buffer_compacts_unparsed_tail_to_front, make_room_moves_the_tail_and_grows_below_n and read_buffer_starts_small_and_doubles_up_to_n in concepts/src/buffer.rs.

A core never decrypts what it does not consume

Section titled “A core never decrypts what it does not consume”

The slice is &mut, so a frame can be decrypted in place and forwarded by range. The consequence: if a frame’s header is decrypted in place but its body has not arrived, the same bytes come back on the next call already transformed, and a naive parser decrypts them twice. A core therefore keeps the decoded length, and any cipher state that advanced (a nonce counter, a SHAKE mask), and skips the header on the next call.

Shadowsocks AEAD and Shadowsocks 2022 share the decoder that does this, ChunkDecoder in protocols/src/ss_aead.rs, used by ShadowsocksCore, Ss2022Core and the two client codecs:

protocols/src/ss_aead.rs
pub const TAG_LEN: usize = 16;
pub const RECORD_HEADER_LEN: usize = 2 + TAG_LEN;
pub const RECORD_OVERHEAD: usize = RECORD_HEADER_LEN + TAG_LEN;
pub enum RecordStep {
NeedMore,
Data { consumed: usize, plain: Range<usize> },
}
pub struct ChunkDecoder {
aead: Aead,
max_payload: usize,
pending_len: Option<usize>,
}
impl ChunkDecoder {
pub fn new(aead: Aead, max_payload: usize) -> Self;
pub fn open_chunk(&mut self, chunk: &mut [u8]) -> io::Result<usize>;
pub fn open_record(&mut self, wire: &mut [u8]) -> io::Result<RecordStep>;
}

open_record works in three steps:

  1. No length pending. It needs RECORD_HEADER_LEN (18) bytes, or it returns NeedMore. It copies them into a local array and opens the sealed two-byte length there, so the wire bytes stay as they were. Aead::open advances the nonce counter, a little-endian counter inside Aead that starts at zero and is stepped by increment_le (protocols/src/helpers/crypto.rs) after every seal and open. A length above max_payload is refused with an InvalidData error that gives both numbers in hex, for example shadowsocks: record length 0x4000 exceeds 0x3fff. Otherwise the length is stored in pending_len.
  2. Payload incomplete. Until 18 + len + 16 bytes are present it returns NeedMore. The caller consumes nothing, the same bytes come back with more appended, and the stored length is used without opening it again.
  3. Payload complete. The payload is opened in place against its tag (the nonce advances again), pending_len is cleared, and it returns Data { consumed: RECORD_OVERHEAD + len, plain: 18..18 + len }. A zero-length record is an ordinary record with an empty plain.

max_payload is MAX_PAYLOAD (0x3FFF, protocols/src/ss_legacy/aead.rs) for ShadowsocksCore and MAX_PACKET_SIZE (0xFFFF, protocols/src/ss_2022/crypto.rs) for Ss2022Core. A tag that does not verify fails with shadowsocks: invalid AEAD tag (InvalidData). open_chunk opens a bare plain || tag chunk in place, which is how Shadowsocks 2022 carries its headers; a chunk shorter than its tag fails with truncated input: AEAD chunk shorter than its tag (UnexpectedEof, see Parse errors). Aead::opens_length tries a key on a record’s sealed length without changing the bytes or the nonce, which is how a legacy multi-user server tries each user’s key on the first record.

The sealing side is ChunkEncoder (new(aead, max_payload), seal_chunk, seal_record). Header chunks and records of one direction advance a single nonce counter (bare_chunks_and_records_share_one_counter). seal_record refuses a payload above max_payload with shadowsocks: record payload over the limit (InvalidInput), and a record that does not fit the room with shadowsocks: staging room below the frame, both before it touches the counter. Aead::new keys one of four Ciphers: Aes128Gcm with a 16-byte key, and Aes256Gcm, ChaCha20Poly1305 and XChaCha20Poly1305 with 32-byte keys; the nonce is 12 bytes, or 24 for XChaCha20Poly1305. A key of the wrong length is refused with shadowsocks: AEAD key of the wrong length (InvalidInput), and a seal that fails inside the cipher is shadowsocks: AEAD seal failed. Protocol crate foundations covers the record stream in full.

VMess has its own ChunkDecoder in protocols/src/vmess/framing.rs. ChunkDecoder::open decodes the two size bytes from a copy through ChunkStream::decode_header, which advances the SHAKE keystream exactly once, and keeps the resulting ChunkHeader { size, padding } in pending until the body arrives. It returns ChunkStep::NeedMore, ChunkStep::Data { consumed, plain } or ChunkStep::End { consumed } for the terminator chunk, whose size is exactly the tag plus its padding (ChunkHeader::is_terminator); the terminator is returned once all its bytes are present and is not opened. A decoded size below the tag plus padding fails with vmess: chunk size below overhead, and a body whose tag does not verify with vmess: body chunk open failed. VMess: wire format and core describes the chunk stream.

  • Tests: a_record_presented_again_is_never_decrypted_twice in protocols/tests/unit/ss_aead.rs offers the first 20 bytes of a record (length plus two payload bytes), then 30, then all of it, and gets NeedMore, NeedMore, then the plaintext; the next record still opens, which it would not if the length had been opened twice. a_trial_key_neither_changes_the_bytes_nor_advances pins opens_length, a_declared_length_over_the_limit_is_refused pins the max_payload check, records_round_trip_under_every_cipher seals and opens under all four ciphers, and a_key_of_the_wrong_length_is_refused pins Aead::new. a_chunk_split_across_reads_decodes_its_header_once in protocols/tests/unit/vmess/core.rs feeds a VMess request cut 10 bytes before its end, then the rest, and finds the whole payload forwarded.

BUF_SIZE is a const generic of ProxyServerRuntime and caps each of its three buffers: transport read, transport staging and outbound scratch. None is allocated at that size up front: the read buffer starts at 2 KiB and doubles as reads fill it, the staging buffer is empty until the first stage, and the scratch buffer is allocated at the first outbound read (see Per-connection runtime). A frame larger than the first read buffer therefore still goes through whole, as long as it fits BUF_SIZE. When the unparsed region fills all BUF_SIZE bytes and the core still consumes nothing, the runtime fails with RuntimeError::FrameTooLarge. BUF_SIZE is therefore sized to the largest frame the protocol admits: an AEAD record plus its overhead, a full HTTP head, a UDP frame behind its length. Each in-tree core publishes the value its runtime needs as an associated BUF_SIZE constant (see Limits), and every caller instantiates the runtime with it, for example drive::<{ VMessCore::<Principal>::BUF_SIZE }, _, _> in supervisor/src/serve.rs.

  • Mechanism: when the read buffer has no free tail left, poll_transport_read checks ReadBuffer::is_saturated (start == 0 && end == N) before it calls make_room. A saturated buffer is one that neither moving nor growing can free, so the runtime returns FrameTooLarge.
  • Tests: frame_larger_than_the_buffer_is_an_error (a 500-byte OPEN payload into BUF_SIZE = 128), a_frame_past_the_grown_buffer_is_still_an_error (a 9,000-byte OPEN payload into BUF_SIZE = 8192) and a_frame_past_the_first_read_buffer_is_relayed_whole_both_ways (a 10,000-byte frame up and 12,000 bytes down through BUF_SIZE = 16384) in concepts/tests/runtime.rs; read_buffer_saturation_means_frame_too_large in concepts/src/buffer.rs.

ProxyServerRuntime::build also asserts BUF_SIZE > Core::STAGING_RESERVE and panics with BUF_SIZE must exceed the core's STAGING_RESERVE or nothing is ever read. A runtime whose buffer does not exceed the reserve would never read an outbound, because a stream read needs STAGING_RESERVE + 1 bytes of staging room; below the reserve, the transport would never be read either.

Effects that name the same key take effect in the order the core pushed them. Two uses in the tree:

  • Effect::Open documents that forwards to the new key may be pushed in the same batch; they are written once the dial completes. PassthroughCore relies on this when it pushes Open together with its first Forward or ForwardHeld.
  • Passthrough::on_transport_eof pushes Shutdown { key } and, if the outbound already ended, Finish. The Shutdown takes effect after the forwards to that key pushed before it, and the Finish after the Shutdown.

The whole queue applies strictly in order: a forward to a key that is still connecting holds every effect queued behind it, whatever it names, until the connect completes. So HttpCore, ShadowsocksCore, Ss2022Core, TrojanCore, VlessCore, VMessCore, SssCore, Hy2StreamCore and PassthroughCore call Timing::enter(Phase::Relay) before they push Open, and AnyTlsCore enters Relay once the session is established, before any stream opens: a SetDeadline queued after the first forward would wait out the connect too, leaving the previous phase’s deadline armed, and the sniff window’s 300 ms would fire mid-connect and end the flow as idle (Timing::enter docs). TunUdpCore pushes Open and then enters Relay, before its first SendTo.

A queued ranged effect references bytes in one of three buffers (Queued::pins): the read buffer (Source::Transport), the outbound scratch buffer (Source::Scratch) or the core’s held buffer (Source::Held). The runtime never moves or overwrites bytes that a queued effect references before it has applied that effect, so a core may forward a range of an event’s slice and return at once. How the runtime keeps that promise is on Per-connection runtime.

A core may forward bytes that are not in the event’s slice: bytes it keeps itself and exposes through held(). Uses in the tree:

  • Sniffing. Copy a flow’s first bytes into the held buffer and consume them, arm SetDeadline, and keep collecting until a TLS SNI or HTTP Host is found, the budget is spent, or the deadline fires. Then push Open with the sniffed target followed by a ForwardHeld of everything collected. SniffPrefix does this for every in-tree core that sniffs a connection’s own flow. mux.cool sub-flows are the exception: Demux sniffs only the payload its New frame carried and opens the sub-flow at once, because a sub-flow is routed the moment it opens. AnyTLS streams are the same: AnyTlsCore sniffs only the data that came with a stream’s address, because holding the session’s uplink for one stream’s sniff would stall the others.
  • A rewritten request, such as a plain-HTTP proxy’s origin-form head (HttpCore::rewritten), that must reach the outbound but never existed on the wire.
  • A frame reassembled across chunks, such as a mux frame that spans VMess chunks (Demux::feed_chunks), a Hysteria 2 UDP packet reassembled from fragments, which Hy2UdpCore sends with SendToHeld, or a UDP-over-TCP packet split across AnyTLS frames, which AnyTlsCore sends the same way.

The rule that makes this safe: a held range is resolved when its effect is applied, not when it is pushed. At the start of every byte event (Transport, TransportDatagram, Outbound, Datagram, OutboundEof, TransportEof), no queued effect references the held buffer, so the core may clear or overwrite it. In the other handlers (Connected, ConnectFailed, OutboundError, SendFailed, TransportSendFailed, Deadline) a held effect may still be queued, so a core may only append to the held buffer there. A Vec that reallocates on append is fine, because a held range is re-resolved against the current slice on every write attempt.

Demux::feed_chunks shows why this matters. It takes every chunk one byte event opened in a single call, because each held forward it pushes reads the held buffer after the event, so the frames completed earlier in the event must stay in place. Demux::trim_held drops the completed frames at the start of the next byte event.

Event Raised from Staging room checked first
Transport poll_transport_read, feed_transport STAGING_RESERVE, once at the top of each read pass
TransportDatagram poll_transport_recv_packet STAGING_RESERVE
TransportEof poll_transport_read STAGING_RESERVE
Outbound, OutboundEof service_key STAGING_RESERVE + 1
Datagram service_key STAGING_RESERVE + datagram_limit()
Connected, ConnectFailed service_key, while the key is connecting STAGING_RESERVE + 1
OutboundError service_key (read or flush error) or drive_effects (write or shutdown error) only for a read error, which needs the read’s own room check to pass first
SendFailed drive_effects not checked
TransportSendFailed poll_transport_send_packets not checked
Deadline poll_deadline not checked

The held buffer is the core’s to size: the runtime does not cap it. A core bounds it by what the protocol admits, as SniffPrefix does with SNIFF_LIMIT.

  • Mechanism: held ranges are validated against held().len() when queued (enqueue) and resolved again with held().get(range) when applied (drive_effects); out of range is RuntimeError::RangeOutOfBounds at either point. Queued::pins(Source::Held) and ProxyServerRuntime::held_free implement the byte-event rule on the runtime side.
  • Tests: held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites in concepts/tests/runtime.rs: the Sniffing test core collects an 8-byte name in two pieces (targ + etXY), opens targetXY through a dialer that completes only when the test releases a tokio::sync::oneshot, and clears its held buffer at the start of every later transport event; the far end reads targetXY and the rest, and outbound_tx is 21. a_held_range_past_the_buffer_is_rejected pushes ForwardHeld { range: 0..9 } over 8 held bytes and gets RangeOutOfBounds. vmess_keeps_every_frame_one_read_completes in protocols/tests/unit/mux/demux.rs seals three VMess chunks in one read, two mux frames straddle chunk boundaries, and both are forwarded from the held buffer; a_frame_straddling_chunks_is_held_and_forwarded_from_the_held_buffer checks that the held bytes stay until the next byte event.

STAGING_RESERVE is the most a core stages in one call beyond the payload it is given: a reply header, or one frame’s overhead times the number of frames one outbound read may be split into. The runtime polls a stream outbound only when staging has STAGING_RESERVE + 1 bytes free, and reads at most room - STAGING_RESERVE bytes (capped at BUF_SIZE) into scratch. An Outbound event of n bytes therefore always comes with at least STAGING_RESERVE + n bytes of room, so sealing it never fails and Staging::reserve can be unwrapped, or mapped to the staging_full() error (staging room below the core's declared reserve) as Passthrough::on_outbound does.

A transport event only has the reserve checked, once, before the read. feed_transport then calls the core again on the unparsed tail as long as it makes progress, without checking again. Transport bytes are expected to be forwarded, not staged. A reply a core stages from a transport event has to fit its reserve: HttpCore stages its 407 or 400 refusal, or the early 200 of a sniffed CONNECT, from the transport event that completes the request head, and each fits its 256-byte reserve. Because the reserve is checked once per read pass, a core that could stage more than the reserve from transport events in one pass must check Staging::room first and consume less if its reply does not fit.

Deadline, SendFailed, TransportSendFailed and the other notifications raised while effects are applied are delivered without a staging-room check (see the table above), so a core must tolerate stage failing in those handlers.

  • Mechanism: the room_short check in service_key and the staging.room() < Core::STAGING_RESERVE check in poll_transport_read.
  • Tests: datagram_outbound_is_never_truncated_by_staging_backpressure in concepts/tests/runtime.rs sends ten 1000-byte UDP replies while the client reads nothing, then reads all ten whole; write_buffer_slides_pending_when_full in concepts/src/buffer.rs.

A key is live from Effect::Open until its outbound is gone. The runtime removes the slot on any of these:

stateDiagram-v2
  [*] --> Connecting: Effect Open applied
  Connecting --> Live: dial ok, Event Connected
  Connecting --> [*]: dial failed, Event ConnectFailed
  Live --> WriteClosed: Effect Shutdown applied
  Live --> ReadClosed: Event OutboundEof
  WriteClosed --> [*]: Event OutboundEof
  ReadClosed --> [*]: Effect Shutdown applied
  Live --> [*]: Effect Close, or Event OutboundError

Close also works while the key is connecting and drops the dial future. An I/O error in any state after the connect removes the key and delivers OutboundError.

Case Result Checked in
Open on a live key RuntimeError::DuplicateKey drive_effects, when the Open is applied
Forward, SendTo, their held variants or Shutdown for a key with no slot RuntimeError::UnknownKey. A Forward or ForwardHeld with an empty range is dropped before the key is looked up, and Close of an unknown key does nothing. drive_effects
Forward or ForwardHeld on a datagram outbound, SendTo or SendToHeld on a stream outbound RuntimeError::WrongLinkKind. Shutdown works on both kinds. drive_effects
A key lost to a failure: a failed dial, or a read, write, flush or shutdown error forget_key drops every queued Forward, SendTo, held variant, Shutdown and Close still aimed at it, because a forward queued for a dial that failed has nowhere to go. The core is told once, through ConnectFailed or OutboundError. service_key (dial, read, flush); fail_outbound from drive_effects (write, shutdown)
A datagram outbound refuses a send The packet is dropped and the key kept; the core hears SendFailed. Only a failed receive removes a datagram key, since that is the socket or connection itself being gone. report_send_failure from drive_effects
Shutdown on a datagram outbound Needs no I/O and marks the write side closed; no OutboundEof follows. drive_effects
A key the core removes itself: Close, or a Shutdown applied after the read side ended Gone with no event. Queued effects that still name it are not dropped, so a Forward or Shutdown for it applied afterwards ends the connection with UnknownKey. drive_effects

Hy2UdpCore retires quiet sessions with Close from its sweep deadline. TunUdpCore, which serves one association per runtime, ends the whole runtime with Finish instead: on its idle deadline, on ConnectFailed or OutboundError, and on TransportEof.

A protocol whose peer may reuse a session id right after closing it must either Close the old key before reopening, or tag keys with a generation. The mux.cool demultiplexer does the second. AnyTLS needs neither: a SYN must carry a stream id above the last one or the session ends, so AnyTlsCore’s key, StreamKey(u32), the stream’s wire id, is never reused within a session. Trojan, VLESS and VMess key their outbounds with FlowKey, and so does SssCore, which only ever uses FlowKey::Direct:

protocols/src/core/mod.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FlowKey {
/// The connection's own flow.
Direct,
/// One mux.cool sub-flow.
Sub(SubKey),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SubKey {
pub id: u16,
pub generation: u32,
}

Demux (protocols/src/mux/demux.rs) keeps one generation: u32 per carrier and increments it with wrapping_add(1) for every New frame it accepts. A New whose id is still in its session table, or one that would exceed MAX_SESSIONS (256), is declined with an End frame instead, so a live id is never opened twice. An End from the peer frees the id in the session table at once. When the peer ends a stream session and opens the same id again, the new outbound gets a fresh SubKey, so it never reuses a live outbound key. Downlink bytes that arrive for a retired key are framed to nobody: Demux::on_outbound looks the key up with session_id, which matches the generation too, and finds nothing. mux.cool and XUDP describes the demultiplexer in full.

  • Tests: stream_sessions_open_forward_and_end_with_fresh_generations in protocols/tests/unit/mux/demux.rs (ids 1 and 2 get generations 1 and 2, session 1 is ended and reopened as generation 3, and on_outbound for the retired key produces no frame); unknown_or_excess_sessions_are_declined_with_end (a Keep for an unknown id, and the 257th New, are answered with End); connect_failure_reaches_the_core_as_an_event and a_refused_datagram_send_keeps_the_key_alive in concepts/tests/runtime.rs. No test drives DuplicateKey, UnknownKey, WrongLinkKind or BadConsume.

There is exactly one timer per connection. A protocol with several timeouts (a handshake limit, an idle limit per session, a keep-alive) keeps its own ordered map of expiries, arms the earliest with SetDeadline, and re-arms on every Deadline. A Deadline event means the timer fired and is now disarmed; arming again replaces any earlier deadline.

The runtime arms against tokio::time::Instant, not std::time::Instant, so a paused tokio clock in tests is honoured. VMessCore and Ss2022Core check request timestamps against the now function their constructor takes (see Responsibilities), so a test can fix the clock of that check.

  • Mechanism: ProxyServerRuntime::set_deadline (tokio::time::sleep_until the first time, Sleep::reset on the existing timer afterwards, with deadline_armed tracking whether it counts) and poll_deadline, which step polls before it applies effects or does any I/O, so a connection that is always ready for I/O cannot starve its handshake or idle deadline.
  • Tests: deadline_event_lets_the_core_time_out (a paused clock jumps to TinyMux’s 5 s idle deadline, and the core finishes) and deadline_is_armed_against_the_tokio_clock (the clock is advanced an hour before the runtime starts; the 5 s idle deadline must not fire within 4 s, and must fire within the next 10 s) in concepts/tests/runtime.rs.

Datagrams follow the socket rule on both sides: one packet per read into an empty buffer, consumed whole, and a packet longer than the limit truncated the way a kernel recv truncates. Before a transport datagram read, the runtime grows the read buffer to the read limit (ReadBuffer::grow_to), so a packet past the first 2 KiB arrives whole (a_datagram_past_the_first_read_buffer_is_delivered_whole).

Datagram outbound Datagram transport
Arrives as Event::Datagram { key, from, data } Event::TransportDatagram { from, data }
Sent with Effect::SendTo / SendToHeld Effects::stage_to / put_to
Read limit datagram_limit() = min(MAX_DATAGRAM, BUF_SIZE - STAGING_RESERVE) min(MAX_DATAGRAM, BUF_SIZE)
Read only when staging has STAGING_RESERVE + datagram_limit() free STAGING_RESERVE free
A refused send packet dropped, key kept, Event::SendFailed packet dropped, runtime carries on, Event::TransportSendFailed
Addressed by Destination, which may name a domain TransportAddr, whatever the transport link addresses by

Because a datagram outbound is read only with room for a whole packet plus the reserve, a client that stops reading stops the downlink at the outbound socket instead of losing packet tails. A protocol whose packets exceed an MTU raises MAX_DATAGRAM and sizes BUF_SIZE to match. A core passes on the address the wire named. A plain socket link such as UdpOutbound (concepts/src/link.rs) refuses a domain with Unsupported (a plain UDP outbound cannot resolve a domain), which the core hears as SendFailed; the supervisor’s resolving links look the name up (see Outbounds, UDP fan-out and balancers). In the other direction, TunUdpCore drops a reply whose source names a domain, since a packet on the device can carry only an IP, and logs tun: dropping a reply from <source>: a packet cannot carry a domain at debug, with the source in Debug form.

A core over a datagram transport decides how packets map to keys. Hy2UdpCore demultiplexes by the session id inside each packet: one key per session, Open on first sight, and idle sessions closed from its sweep deadline. The TinyHub test core keys by the packet’s peer instead, also opening a key on first sight. TunUdpCore keys everything as Single: it opens one association on the first packet and sends every packet through it with SendTo, addressed by the far end the client named. There is no end of stream on the transport side, so Effect::Finish is the only way such a runtime completes normally; a RuntimeError, or dropping the runtime, also ends it. A packet the transport refuses is dropped rather than failing the connection, because one peer’s unreachable address must not take the others down, and a refused packet is not counted in transport_tx.

  • Tests: datagrams_round_trip_through_a_real_udp_socket (TinyUdp, a [len:u16][port:u16][payload] protocol over a duplex, against a UDP echo on 127.0.0.1), datagram_transport_demultiplexes_peers_and_frames_replies (TinyHub, one UDP socket serving two peers, each reply going only to its own peer), staging_without_a_peer_under_a_datagram_transport_is_an_error, stage_to_is_refused_under_a_stream_transport, a_refused_transport_packet_is_reported_not_fatal (an IPv6 peer through an IPv4 hub socket) and single_peer_datagram_transport_demuxes_sessions_and_reports_refusals (TinyQuic, a single-peer link that refuses packets above 64 bytes, carrying two sessions), all in concepts/tests/runtime.rs.

A core fails the connection by returning Err from handle. Outbound failures are not fatal to the runtime: they reach the core as events and the core decides. Everything else that ends a connection early is a RuntimeError:

concepts/src/runtime.rs
pub enum RuntimeError<E> {
Transport(io::Error),
Core(E),
UnknownKey,
DuplicateKey,
RangeOutOfBounds,
BadConsume,
FrameTooLarge,
WrongLinkKind,
StagedWithoutPeer,
}
Variant Cause Display text
Transport The transport read failed, a datagram link reported a stream read (datagram transport delivered a stream read, InvalidData), or a byte-stream transport’s write, flush or shutdown failed or wrote zero bytes. A packet a datagram transport refuses is Event::TransportSendFailed, not this error. transport: <error>
Core handle returned Err proxy core: <error>
UnknownKey A forward, send or shutdown for a key with no slot effect targets an unknown outbound key
DuplicateKey Open on a live key open reuses a live outbound key
RangeOutOfBounds A range outside the event slice or the held buffer forward range outside the event slice or held buffer
BadConsume Consumed more than given, or less than a whole outbound payload or transport datagram core consumed an impossible byte count
FrameTooLarge The unparsed region fills BUF_SIZE and the core wants more protocol frame exceeds the read buffer
WrongLinkKind A stream effect on a datagram outbound, or the reverse stream effect on a datagram outbound or vice versa
StagedWithoutPeer Bytes staged toward a datagram transport outside a packet bytes staged toward a datagram transport without a peer

RuntimeError implements std::error::Error (for E: Debug + Display) and From<io::Error>, which maps to Transport. UnknownKey, DuplicateKey, RangeOutOfBounds, BadConsume, WrongLinkKind and StagedWithoutPeer are core bugs, not peer behaviour: a core is expected to turn malformed wire input into its own Error, not into an out-of-range effect. FrameTooLarge means either a peer sent a frame longer than the buffer or BUF_SIZE is too small for the protocol. The shared helpers produce two Core texts of their own: client did not complete its request in time (handshake_timed_out) and staging room below the core's declared reserve (staging_full, which Hy2UdpCore calls through a private wrapper of the same name); the Shadowsocks sealing path uses shadowsocks: staging room below the frame for the same case.

The cores return io::Error, but much of the parsing below them classifies failures as ProtocolError from protocols/src/error.rs and converts with ? through From<ProtocolError> for io::Error. The variant decides both the text prefix and the io::ErrorKind:

Variant Display io::ErrorKind
Truncated(&'static str) truncated input: <what> UnexpectedEof
Overflow(&'static str) integer overflow: <what> InvalidData
Malformed(&'static str) malformed: <what> InvalidData
Unauthenticated(&'static str) authentication failed: <what> PermissionDenied
Crypto(&'static str) cryptographic operation failed: <what> Other
Unsupported(&'static str) unsupported: <what> InvalidData
Io(io::Error) the inner error’s text the inner error, returned unchanged
Other(anyhow::Error) the inner error’s text Other

That is where truncated input: AEAD chunk shorter than its tag and its UnexpectedEof kind come from: ChunkDecoder::open_chunk returns ProtocolError::Truncated("AEAD chunk shorter than its tag").

ShadowsocksCore and Ss2022Core do not end a connection when its request fails to authenticate. They move to State::Rejected(error), consume every later transport byte, and return the stored error only when the client closes (TransportEof) or the handshake deadline passes; on Expired::Handshake they return it instead of handshake_timed_out(). The module docs of protocols/src/ss_legacy/core.rs give the reason: the moment of the close then does not tell a prober how many bytes the server needed to decide. ShadowsocksCore stores shadowsocks: no matching user (PermissionDenied) when no user’s key opens the first record; Ss2022Core stores the error of the step that failed, for example shadowsocks-2022: unknown identity (PermissionDenied, from protocols/src/ss_2022/core.rs → denied). Shadowsocks and Shadowsocks 2022 describe the checks. sss settles the same question before its core exists: its gate drains a stream that fails before authentication, or hands it to a fallback, and only an admitted stream reaches SssCore (sss).

drive in supervisor/src/serve.rs turns a RuntimeError into io::Error::other(e.to_string()), so the text above is what reaches the log. serve_connection logs every connection that ends in an error at debug, target etemenanki_supervisor::serve:

<protocol> connection from <source> ended: <error>

<protocol> is StreamProtocol::name from supervisor/src/topology/inbound/mod.rs (socks, http, trojan, vless, vmess, shadowsocks, shadowsocks-2022, anytls or sss) and <source> is the client address in Debug form, for example Some(192.0.2.10). A core that timed out its handshake therefore logs vmess connection from Some(192.0.2.10) ended: proxy core: client did not complete its request in time.

Cancellation is the runtime’s: dropping the ProxyServerRuntime future or stream drops the transport and every outbound with it, including dials in flight. A core has no Drop obligations towards the I/O.

Constant Value Where
ProxyCoreDecode::MAX_DATAGRAM default 4096 concepts/src/core.rs
INLINE_EFFECTS 4 concepts/src/core.rs
HARNESS_STAGING 64 * 1024 protocols/src/core/harness.rs
HANDSHAKE_TIMEOUT 10 s protocols/src/core/mod.rs
RELAY_IDLE_TIMEOUT 300 s protocols/src/core/mod.rs
SNIFF_TIMEOUT 300 ms protocols/src/sniff/mod.rs
SNIFF_LIMIT 4 * 1024 protocols/src/sniff/mod.rs
TAG_LEN, RECORD_HEADER_LEN, RECORD_OVERHEAD 16, 18, 34 bytes protocols/src/ss_aead.rs
mux MAX_SESSIONS 256 sub-flows per carrier protocols/src/mux/demux.rs
mux MAX_DATA_LEN 8 * 1024 protocols/src/mux/frame.rs
mux FRAME_OVERHEAD_MAX 2 + MIN_META_LEN + 1 + AddressCodec::MAX_LEN + 2 = 268 (MIN_META_LEN = 4 in protocols/src/mux/frame.rs, AddressCodec::MAX_LEN = 259 in protocols/src/helpers/address.rs) protocols/src/mux/frame.rs
AnyTLS MAX_STREAMS 256 streams per session protocols/src/anytls/core.rs
Hysteria 2 UDP MAX_SESSIONS 256 associations per connection protocols/src/hysteria/server/datagrams.rs
Hysteria 2 UDP SWEEP_INTERVAL 1 s protocols/src/hysteria/server/datagrams.rs

The code gives the reasons for the two sniffing limits. SNIFF_TIMEOUT is mandatory because in a server-speaks-first protocol (SMTP, SSH, MySQL) the client sends nothing at that point, and without a deadline the flow would wait forever for bytes to sniff. SNIFF_LIMIT spans frames rather than capping one read, because a ClientHello with a long extension list can exceed one frame, and it keeps a peer from streaming arbitrarily much before the flow is routed.

The in-tree cores and the constants they declare:

Core Key TransportAddr STAGING_RESERVE MAX_DATAGRAM BUF_SIZE
PassthroughCore (protocols/src/core/mod.rs) Single () 0 default 8 * 1024
HttpCore (protocols/src/http/core.rs) Single () 256 (a status line and its headers) default MAX_HEAD (64 * 1024, protocols/src/http/protocol.rs)
ShadowsocksCore (protocols/src/ss_legacy/core.rs) Single () 32 + 2 * RECORD_OVERHEAD + 28 = 128 (the response salt plus the overhead of the two records one read splits into) default 20 * 1024
Ss2022Core (protocols/src/ss_2022/core.rs) Single () 32 + 1 + 8 + 32 + 2 + 2 * TAG_LEN + RECORD_OVERHEAD + 115 = 256 (the response header or one record’s overhead) default MAX_RECORD_LEN = 0xFFFF + RECORD_OVERHEAD = 65,569
TrojanCore (protocols/src/trojan/core.rs) FlowKey () PACKET_HEADER_MAX.next_multiple_of(16) + downlink_overhead(Self::BUF_SIZE) = 272 + 536 = 808 MAX_LENGTH (8192) 16 * 1024
VlessCore (protocols/src/vless/core.rs) FlowKey () 272 + downlink_overhead(Self::BUF_SIZE) = 808 8192 16 * 1024
VMessCore (protocols/src/vmess/core.rs) FlowKey () 4096 8192 32 * 1024
AnyTlsCore (protocols/src/anytls/core.rs) StreamKey () 2 * HEADER_LEN + MAX_SCHEME_LEN + SERVER_SETTINGS.len() = 14 + 2048 + 3 = 2,065 (the padding scheme and ServerSettings that answer the client’s Settings) MAX_UDP_PAYLOAD (8 * 1024) 16 * 1024
SssCore (protocols/src/sss/core.rs) FlowKey () PACKET_HEADER_MAX = 262 (one datagram record’s header, protocols/src/sss/protocol.rs) MAX_DATAGRAM (u16::MAX, 65,535) TCP_BUF_SIZE (16 * 1024) for a TCP stream, UDP_BUF_SIZE (66 * 1024) for a UDP one
Hy2StreamCore (protocols/src/hysteria/server/inbound.rs) Single () 2048 (a TCPResponse with the longest padding) default 8 * 1024
Hy2UdpCore (protocols/src/hysteria/server/datagrams.rs) u32 () 4096 MAX_UDP_SIZE (4096, protocols/src/hysteria/protocol.rs) 16 * 1024
TunUdpCore (protocols/src/tun/udp.rs) Single SocketAddr 4096 4096 8 * 1024

Trojan, VLESS and VMess carry mux.cool sub-flows under FlowKey. downlink_overhead(read_size) in protocols/src/mux/demux.rs is read_size.div_ceil(MAX_DATA_LEN) * FRAME_OVERHEAD_MAX: one Keep header for every 8 KiB piece of an outbound read, so a 16 KiB read adds 2 * 268 = 536 bytes. Trojan’s PACKET_HEADER_MAX is AddressCodec::MAX_LEN + 2 + 2 = 263 (address, length, CRLF), rounded up to 272. The Ss2022Core buffer holds a record carrying MAX_PACKET_SIZE whole, because ss-rust and sing seal a whole read of up to that size into one record. With these values, datagram_limit() is 8192 for Trojan, VLESS, VMess and AnyTLS, 65,535 for an sss UDP stream, and 4096 for Hy2UdpCore and TunUdpCore.

Test File Pins
core_is_driven_without_any_io concepts/tests/runtime.rs A core runs on hand-built events; split frames stay unconsumed; in-place decryption
relays_two_keys_and_completes_on_fin concepts/tests/runtime.rs Two keys relayed over one transport; Finish completes with Traffic totals; ShutdownTransport ends the client’s read side
connect_failure_reaches_the_core_as_an_event concepts/tests/runtime.rs ConnectFailed delivery
half_close_propagates_both_ways_and_finishes concepts/tests/runtime.rs Shutdown, OutboundEof, ShutdownTransport
deadline_event_lets_the_core_time_out, deadline_is_armed_against_the_tokio_clock concepts/tests/runtime.rs The single deadline and the tokio clock
frame_larger_than_the_buffer_is_an_error, a_frame_past_the_grown_buffer_is_still_an_error concepts/tests/runtime.rs FrameTooLarge, also once the read buffer has grown to BUF_SIZE
a_frame_past_the_first_read_buffer_is_relayed_whole_both_ways, a_datagram_past_the_first_read_buffer_is_delivered_whole concepts/tests/runtime.rs Frames and datagrams larger than the first 2 KiB buffer go through whole
held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites, a_held_range_past_the_buffer_is_rejected concepts/tests/runtime.rs Forwards pushed with their Open are written after the connect; the held-buffer rule; RangeOutOfBounds
datagrams_round_trip_through_a_real_udp_socket, datagram_outbound_is_never_truncated_by_staging_backpressure concepts/tests/runtime.rs Datagram outbounds; room for a whole packet before a read
datagram_transport_demultiplexes_peers_and_frames_replies, staging_without_a_peer_under_a_datagram_transport_is_an_error, stage_to_is_refused_under_a_stream_transport concepts/tests/runtime.rs Datagram transports and StagedWithoutPeer
a_refused_datagram_send_keeps_the_key_alive, a_refused_transport_packet_is_reported_not_fatal, single_peer_datagram_transport_demuxes_sessions_and_reports_refusals concepts/tests/runtime.rs SendFailed and TransportSendFailed are not fatal
stream_mode_reports_each_unit_of_work concepts/tests/runtime.rs Per-step Traffic deltas; non-payload steps are zero deltas
read_buffer_compacts_unparsed_tail_to_front, read_buffer_saturation_means_frame_too_large, write_buffer_slides_pending_when_full, staging_refuses_over_reservation_without_partial_commit concepts/src/buffer.rs ReadBuffer compaction and saturation, WriteBuffer sliding, all-or-nothing Staging::reserve
read_buffer_starts_small_and_doubles_up_to_n, make_room_moves_the_tail_and_grows_below_n, compact_frees_room_in_any_buffer_short_of_saturated, a_small_n_is_allocated_whole, grow_to_makes_room_for_a_whole_datagram_up_to_n, write_buffer_holds_nothing_until_a_stage, staging_grows_to_n_and_no_further concepts/src/buffer.rs Buffers start at 2 KiB (or N if smaller) or empty, double on demand, and never grow past N
timing_arms_handshake_once_then_idle_per_byte_event, timing_reports_handshake_and_sniff_expiry_to_the_core protocols/tests/unit/core/mod.rs Timing
sniff_prefix_finds_a_host_across_pushes_and_keeps_the_bytes, sniff_prefix_takes_no_more_than_its_budget protocols/tests/unit/core/mod.rs SniffPrefix and SNIFF_LIMIT
passthrough_half_closes_each_side_and_finishes_on_the_second protocols/tests/unit/core/mod.rs Passthrough
passthrough_core_opens_on_the_first_bytes_and_relays_verbatim, passthrough_core_finishes_when_the_outbound_fails_or_idles (through with_sink); a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host, a_sniffing_passthrough_core_opens_on_the_sniff_deadline, a_sniffing_passthrough_core_with_a_domain_target_opens_at_once (through CoreHarness) protocols/tests/unit/core/mod.rs PassthroughCore: opening, relaying, half-close, failure, idle expiry and sniffing
stream_sessions_open_forward_and_end_with_fresh_generations, unknown_or_excess_sessions_are_declined_with_end protocols/tests/unit/mux/demux.rs Generation-tagged SubKeys; declined sessions
a_frame_straddling_chunks_is_held_and_forwarded_from_the_held_buffer, vmess_keeps_every_frame_one_read_completes protocols/tests/unit/mux/demux.rs Mux frames split across VMess chunks are forwarded from the held buffer
a_record_presented_again_is_never_decrypted_twice, a_declared_length_over_the_limit_is_refused, a_trial_key_neither_changes_the_bytes_nor_advances, a_refused_seal_stages_nothing_and_keeps_the_counter, records_round_trip_under_every_cipher, bare_chunks_and_records_share_one_counter, a_key_of_the_wrong_length_is_refused protocols/tests/unit/ss_aead.rs Never decrypting a record length twice; the length limit; trial keys; all-or-nothing sealing; every cipher; one nonce counter per direction; key length
a_chunk_split_across_reads_decodes_its_header_once protocols/tests/unit/vmess/core.rs Never decrypting a chunk header twice (VMess)
a_core_hands_on_the_user_it_matched protocols/tests/unit/vmess/core.rs VMessCore::user_hint is None until the auth id matches; a hinted core still finds its user; a hint is not a match when the auth id is refused

Run them with:

Terminal window
cargo test -p etemenanki-concepts
cargo test -p etemenanki-protocols --lib core::tests
cargo test -p etemenanki-protocols --lib mux::demux::tests
cargo test -p etemenanki-protocols --lib ss_aead::tests

The core::tests filter also picks up each protocol core’s own core::tests module, including vmess::core::tests. The Hysteria 2 and TUN cores are behind the hysteria and tun features of etemenanki-protocols (TUN on Unix and Windows); add --features hysteria,tun to include their tests.

CoreHarness in protocols/src/core/harness.rs is a hand-driven stand-in for the runtime. It owns the core, an EffectList, a WriteBuffer<HARNESS_STAGING> (HARNESS_STAGING = 64 * 1024) and, for datagram cores, a PacketList. It does no I/O.

protocols/src/core/harness.rs
pub const HARNESS_STAGING: usize = 64 * 1024;
pub struct CoreHarness<C: ProxyCoreDecode> {
pub core: C,
effects: EffectList<C>,
staging: WriteBuffer<HARNESS_STAGING>,
packets: Option<PacketList<C::TransportAddr>>,
}
impl<C: ProxyCoreDecode> CoreHarness<C> {
pub fn new(core: C) -> Self;
pub fn over_datagrams(core: C) -> Self;
pub fn event(&mut self, event: Event<'_, C>) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn transport(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn feed(&mut self, data: &mut [u8]) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn outbound(
&mut self,
key: C::Key,
data: &mut [u8],
) -> Result<(usize, Vec<Effect<C>>), C::Error>;
pub fn staged(&mut self) -> Vec<u8>;
pub fn staged_packets(&mut self) -> Vec<(Vec<u8>, C::TransportAddr)>;
pub fn held(&self, range: std::ops::Range<usize>) -> Vec<u8>;
}
Method What it does
new / over_datagrams A harness for a byte-stream core, or one whose sink is built with with_packets so stage_to works.
event Deliver any event once; returns the consumed count and the effects pushed, drained from the list.
transport event(Event::Transport(data)).
feed Deliver transport bytes the way the runtime does: call again on the unconsumed tail while the core makes progress. Forward and SendTo ranges in the result are rebased to be absolute in data; held ranges are left alone. Returns the total consumed.
outbound event(Event::Outbound { key, data }).
staged Take everything staged toward the transport so far. Staging accumulates across calls until staged takes it.
staged_packets Take the staged packets with their peers, in order. Empty for a byte-stream harness.
held The core’s held bytes under range, as a forward would resolve them; empty if the range is out of bounds.

A typical unit test, from protocols/tests/unit/core/mod.rs:

protocols/tests/unit/core/mod.rs
let mut h = CoreHarness::new(PassthroughCore::sniffing(flow()));
let mut opaque = [0x16u8, 0x03, 0x01];
h.transport(&mut opaque).unwrap();
let (_, fx) = h.event(Event::Deadline).unwrap();
assert!(matches!(&fx[0], Effect::Open { target, .. } if target.sniffed.is_none()));
assert!(matches!(&fx[1], Effect::ForwardHeld { range, .. } if *range == (0..3)));
assert!(h.core.is_established());

protocols/tests/unit/core/mod.rs also uses a smaller pattern: a with_sink function that builds Effects::new over a WriteBuffer::<256>, runs a closure, and returns the pushed effects and the staged bytes. It tests the helpers that are not whole cores (Timing, Passthrough), and the two non-sniffing PassthroughCore tests call handle through it directly.