Skip to content

mux.cool and XUDP

Source files: 46 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/protocols/src/mux/mod.rs
  • Etemenanki/protocols/src/mux/frame.rs
  • Etemenanki/protocols/src/mux/demux.rs
  • Etemenanki/protocols/src/core/mod.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/lib.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/protocols/src/error.rs
  • Etemenanki/protocols/src/helpers/address.rs
  • Etemenanki/protocols/src/helpers/parse.rs
  • Etemenanki/protocols/src/trojan/core.rs
  • Etemenanki/protocols/src/trojan/protocol.rs
  • Etemenanki/protocols/src/vless/core.rs
  • Etemenanki/protocols/src/vless/protocol.rs
  • Etemenanki/protocols/src/vless/codec.rs
  • Etemenanki/protocols/src/vmess/core.rs
  • Etemenanki/protocols/src/vmess/protocol.rs
  • Etemenanki/protocols/src/vmess/framing.rs
  • Etemenanki/concepts/src/core.rs
  • Etemenanki/concepts/src/runtime.rs
  • Etemenanki/concepts/src/buffer.rs
  • Etemenanki/supervisor/src/connector.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/topology/plane.rs
  • Etemenanki/supervisor/src/topology/router.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/outbound/udp_fanout.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/entity/session.rs
  • Etemenanki/supervisor/src/track/mod.rs
  • Etemenanki/app/src/config.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/protocols/tests/unit/mux/frame.rs
  • Etemenanki/protocols/tests/unit/mux/demux.rs
  • Etemenanki/protocols/tests/unit/vless/protocol.rs
  • Etemenanki/protocols/tests/unit/vless/codec.rs
  • Etemenanki/concepts/tests/runtime.rs
  • Etemenanki/supervisor/tests/tracking.rs
  • Etemenanki/supervisor/tests/hot_swap.rs
  • Etemenanki/supervisor/tests/support/mod.rs
  • Etemenanki/app/tests/integration/e2e_xray_mux.rs
  • Etemenanki/app/tests/support/mod.rs
  • katana/src/rule.rs
  • katana/src/lower/inbound.rs
  • katana/tests/integration/xray_interop.rs
  • katana/tests/support/mod.rs

mux.cool is Xray’s multiplexing layer. One proxy connection, the carrier, holds many sessions, and each session is a TCP stream or a UDP association. Every piece of session data travels in a small frame that names its session. XUDP is the UDP extension: each packet of a UDP session may name its own peer, so one session can talk to many addresses. The module etemenanki_protocols::mux (etemenanki-protocols 6.2.1) ports the server side of Xray’s common/mux, plus the one XUDP session a VLESS client under XTLS Vision sends. Its core is a sans-I/O demultiplexer, Demux, which the Trojan, VLESS and VMess server cores switch to once a request turns out to be a carrier. Each session the demultiplexer opens is a sub-flow: a flow of its own, which the supervisor (etemenanki-supervisor, the kernel crate that serves every inbound and routes every flow) admits, routes and tracks separately.

This page is for contributors who change protocols/src/mux/ or the carrier paths of those three cores, and for anyone following a sub-flow into the supervisor. It covers how each protocol signals a carrier, the frame layout, the session table and its key generations, how uplink frames become runtime effects without copying, how a frame that straddles VMess chunks is held, how downlink bytes are framed and reserved for, what the supervisor does with each sub-flow, and the tests that pin each rule. Nothing about mux is configurable: every Trojan, VLESS and VMess inbound accepts a carrier, and no setting turns that off. The only inbound setting the demultiplexer reads is sniffing (InboundSpec::sniff). The carrier authenticates against the inbound’s user set like any request, and the inbound tag reaches every sub-flow through the connector’s FlowContext. The user guide pages for VLESS, VMess and Trojan describe the inbound settings.

no multiplexing client The crate demultiplexes carriers it receives. It never multiplexes its own outbound traffic: no client puts several flows on one connection. The module docs give the reason: a mux client would only ever be talking to another instance of this same server. The one client use is XUDP’s single UDP session: a VLESS outbound under Vision sends a UDP flow’s packets that way, as Xray’s client does (The XUDP client under Vision). The module is always compiled; no Cargo feature gates mux (protocols/src/lib.rs).

Concern Where What it does
Carrier address protocols/src/mux/mod.rs → MUX_ADDRESS, mux_destination, MUX_PORT, is_mux_destination The pseudo-destination v1.mux.cool, and the check Trojan uses to detect a carrier
Frame codec protocols/src/mux/frame.rs → parse_meta, parse_frame, encode_keep, encode_end and their staging variants encode_keep_into, encode_end_into, plus the crate-private encode_new_udp_into Parses and builds frames, and enforces the metadata and data length caps
XUDP client protocols/src/vless/codec.rs → VlessDatagram::with_flow with VlessFlow::Vision Sends one UDP flow of a Vision outbound as an XUDP session over its own connection
Session table protocols/src/mux/demux.rs → Demux Maps wire session ids to outbound keys, opens and retires sub-flows, and declines excess or unknown sessions
Uplink dispatch Demux::feed, Demux::feed_chunks Turns frames into Effect::Open, Forward, ForwardHeld, SendTo, SendToHeld and Shutdown
Downlink framing Demux::on_outbound, on_datagram, on_outbound_gone Frames outbound bytes and packets as Keep frames, and a finished sub-flow as End
Carrier end Demux::on_transport_eof Closes every live sub-flow when the carrier’s uplink ends, without framing anything
Outbound keys protocols/src/core/mod.rs → FlowKey, SubKey The key type the three carrier cores give the runtime
Sub-flow template protocols/src/flow.rs → Flow::toward Copies the carrier’s user and source into each sub-flow
Carrier detection and staging TrojanCore, VlessCore, VMessCore Enter the Mux state, feed the demultiplexer, and stage or seal its output inside a declared staging reserve
Per-sub-flow admission, routing and tracking supervisor/src/connector.rs → AppConnector::connect Admits each sub-flow on the carrier’s session, routes it on the current plane, and meters it as a flow of its own
Per-packet routing of a UDP sub-flow supervisor/src/topology/outbound/udp_fanout.rs → FanOutLink Routes each packet of a UDP sub-flow on its own destination

What the module leaves to others:

  • Admission, routing and tracking. Each sub-flow reaches the program’s connector as its own Flow through Effect::Open. Both etemenanki-app and katana 6 serve Trojan, VLESS and VMess inbounds through the supervisor. Its AppConnector::connect admits the sub-flow on the carrier’s session (Session::admit), routes it on the plane current at that moment (Plane::route), and meters it as a tracked flow of its own (Tracker::meter_stream), which can be killed alone. A UDP sub-flow becomes a FanOutLink, whose sub-links are each a tracked flow. katana’s destination audit rules are routes (src/rule.rs), so each sub-flow meets them like any other flow. Sub-flows in the supervisor has the details.
  • I/O and backpressure. The per-connection runtime applies the effects, resolves each forward’s range when it applies it, and guarantees staging room before it delivers an event (The server runtime).
  • Carrier crypto and transport. VMess opens and seals its chunk stream itself. Trojan and VLESS rely on the transport under them (TLS, WebSocket, gRPC, and for VLESS also REALITY) for confidentiality (TCP and TLS, WebSocket and gRPC).

The three protocols signal multiplexing in two ways. VLESS and VMess have a mux command. Trojan has none, so a client signals it by address.

Carrier Signal Carrier Flow::destination Staged at once
VLESS Command byte CMD_MUX (0x03). The header ends at the command byte, with no address: version, 16-byte user id, addons length, the addons, command; 19 bytes when the addons are empty, as a plain client sends them, and 37 with the Vision addons, as a Vision client sends its XUDP carrier mux_destination(): TCP, v1.mux.cool, port 0 RESPONSE_HEADER ([0, 0])
VMess Command 0x03 in the sealed request header, with no address: the plaintext is the fixed 38-byte head, the padding and the 4-byte FNV-1a checksum, so a MUX header without padding sits exactly at the parser’s 42-byte floor mux_destination() The sealed response header, through VMessCore::reply
Trojan A CONNECT (CMD_TCP_CONNECT, 0x01) whose address satisfies is_mux_destination The address as sent, for example v1.mux.cool port 9527 from Xray Nothing, because Trojan never replies
protocols/src/mux/mod.rs
pub const MUX_ADDRESS: &str = "v1.mux.cool";
pub fn mux_destination() -> Destination // TCP, Remote::Domain("v1.mux.cool"), port 0
pub const MUX_PORT: u16 = 9527;
pub fn is_mux_destination(dest: &Destination) -> bool
pub use demux::Demux;
pub use frame::{FrameMeta, SessionStatus};

MUX_ADDRESS is never dialed: each sub-flow the carrier decodes brings its own destination. Its doc comment calls it what a log line or a route rule would see for the carrier itself; in this crate the carrier’s Flow is only a template (below) and never reaches a connector, so no route rule is evaluated for it. is_mux_destination matches a Remote::Domain equal to MUX_ADDRESS ignoring ASCII case. It never looks at the port, as Xray’s mux.Server.Dispatch compares only the address. MUX_PORT is Xray’s muxCoolPort, kept for reference: no code reads it. Only TrojanCore calls the check, on a CONNECT request. A SOCKS, HTTP, Shadowsocks, Shadowsocks 2022 or Hysteria 2 request to v1.mux.cool is dialed like any other domain. The VLESS parser (protocols/src/vless/protocol.rs → parse_request_header) substitutes mux_destination() for the missing address and reports 19 bytes consumed, so the first mux frame stays unread. The VMess parser (protocols/src/vmess/protocol.rs → parse_request_header) substitutes it with a zero-width address, so the header’s exact-length check counts no address bytes. In both protocols Command::network maps Mux to DialNetwork::Tcp, because the carrier itself is a stream.

The carrier authenticates exactly like a single-flow request: Trojan by the password hash (trojan: invalid user), VLESS by the user id (invalid vless request user id), VMess by the auth id (vmess: unknown user or invalid auth id, or a skew or replay refusal; see VMess: keys and authentication). A failed check ends the connection before any sub-flow exists. Each of these is a PermissionDenied error, which the supervisor’s drive reports to its guard as a refused credential.

The three cores take the same inputs a single-flow connection needs, and nothing mux-specific:

protocols/src/{trojan,vless,vmess}/core.rs
TrojanCore::new(validator: Arc<Validator<T>>, sniff: bool, source: Option<IpAddr>) -> Self
VlessCore::new(validator: Arc<Validator<T>>, sniff: bool, source: Option<IpAddr>) -> Self
VMessCore::new(validator: Arc<AccountValidator<T>>, now: fn() -> i64, sniff: bool, source: Option<IpAddr>) -> Self

now is the clock VMess checks the auth id’s timestamp against; the supervisor passes now_unix. In the supervisor, serve_connection (supervisor/src/serve.rs) hands drive a closure that builds the core with the inbound’s sniff and the connector’s source(); drive calls it once, when it builds the runtime. source() is the socket’s peer, or the client a PROXY protocol v2 header named when the inbound reads one, or, for a socket a relay on the same host handed over, the client the header sent with it named, or, over WebSocket on an inbound with real_ip, the client a proxy in the trusted networks names in the upgrade’s header.

On a carrier, the core builds its Flow as usual (user, source, destination) and passes it to Demux::new. That flow is never handed to the connector. It is only the template for every sub-flow:

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 toward(&self, destination: Destination) -> Self
}

toward clones the carrier’s user (the payload is behind an Arc, so T need not be Clone), copies source, sets the sub-flow’s own destination, and resets sniffed to None. Every sub-flow is therefore attributed to the user who authenticated the carrier. In the supervisor, T is Principal (supervisor/src/topology/flow.rs → pub type Flow = etemenanki_protocols::flow::Flow<Principal>), so every sub-flow carries the carrier’s principal.

Until its request is parsed, a connection is in Phase::Handshake, whether or not it turns out to be a carrier. Timing::new arms nothing, and the first byte event arms HANDSHAKE_TIMEOUT (10 s) through Timing::touch, which in the handshake phase arms only when nothing is armed yet. So the core’s handshake deadline starts at the client’s first bytes and is not re-armed by later ones; when it passes, the core fails with client did not complete its request in time (handshake_timed_out). A client that sends nothing produces no event, so the supervisor watches the handshake from outside as well: drive wraps each runtime step taken before the core is established in tokio::time::timeout(HANDSHAKE_TIMEOUT, runtime.next()), and a step that times out ends the connection with inbound handshake timed out after 10s.

After detection, each core sets State::Mux(Demux::new(flow, self.sniff)) and calls Timing::enter(Phase::Relay), which arms RELAY_IDLE_TIMEOUT (300 s) through Effect::SetDeadline. From then on Timing::is_established is true (the phase is Relay or Closing), so the core reports is_established() and drive stops applying its handshake timeout. The carrier has one idle deadline. Timing::touch re-arms it at the top of every Transport, Outbound and Datagram event, so traffic on any sub-flow, or a KeepAlive frame, re-arms it. When the deadline passes, Timing::expired moves to Phase::Closing and pushes Effect::Finish, and the core returns Ok(0) for Expired::Idle. What the runtime does once Finish is applied is described in The server runtime.

A frame is a length-prefixed metadata block, optionally followed by a length-prefixed data block. All integers are big-endian.

Field Size (bytes) Meaning
Metadata length 2 Length of the metadata block that follows. Must be at least MIN_META_LEN (4) and at most MAX_META_LEN (512)
Session id 2 The sub-flow this frame belongs to, chosen by the client
Status 1 0x01 New, 0x02 Keep, 0x03 End, 0x04 KeepAlive
Option 1 Bit OPTION_DATA (0x01): a data block follows. Bit OPTION_ERROR (0x02): the peer reports an error on this session
Network 1 Present on every New frame, and on a Keep frame only when this byte is NETWORK_UDP. 0x01 TCP, 0x02 UDP
Address 5 to 259 The target (New) or per-packet peer (UDP Keep), in AddressCodec::VMESS layout: a 2-byte port, then type 0x01 IPv4 (4 bytes), 0x02 domain (1 length byte and up to 255 bytes) or 0x03 IPv6 (16 bytes)
Global id 8 XUDP session identity. Read only on a New frame that opens a UDP session with OPTION_DATA set, when at least 8 bytes remain in the metadata
Rest of metadata variable Ignored. The metadata length accounts for it
Data length 2 Present only with OPTION_DATA. At most MAX_DATA_LEN (8192)
Data data length The sub-flow’s payload: stream bytes, or one UDP packet

The address codec is the one VLESS and VMess use (frame::ADDR is AddressCodec::VMESS), with the port first. AddressCodec::MAX_LEN is 259: the type byte, a length byte, a 255-byte domain and the port. A domain is checked the way Xray’s address parser checks it (protocols/src/helpers/address.rs → parse_domain_bytes): a name that starts with a digit or [ and parses as an IP address becomes Remote::IpAddr, and any other name must be UTF-8 made of ASCII letters, digits, -, . and _. So a New frame naming the domain 192.0.2.1 opens a sub-flow toward an IP, which sniffing inspects when it is on.

A Keep frame on a stream session carries no network or address. parse_meta looks at the byte after the option first, and only NETWORK_UDP there makes it parse an address, as upstream does, because on a stream session the metadata ends at the option byte.

protocols/src/mux/frame.rs
pub const ADDR: AddressCodec = AddressCodec::VMESS;
pub const STATUS_NEW: u8 = 0x01;
pub const STATUS_KEEP: u8 = 0x02;
pub const STATUS_END: u8 = 0x03;
pub const STATUS_KEEP_ALIVE: u8 = 0x04;
pub const OPTION_DATA: u8 = 0x01;
pub const OPTION_ERROR: u8 = 0x02;
pub const NETWORK_TCP: u8 = 0x01;
pub const NETWORK_UDP: u8 = 0x02;
pub const MAX_META_LEN: usize = 512;
pub const MAX_DATA_LEN: usize = 8 * 1024;
const MIN_META_LEN: usize = 4;
pub const FRAME_OVERHEAD_MAX: usize = 2 + MIN_META_LEN + 1 + AddressCodec::MAX_LEN + 2;
const GLOBAL_ID_LEN: usize = 8;

MAX_META_LEN matches frame.go’s metaLen > 512 rejection and bounds the per-frame allocation from an untrusted peer. MAX_DATA_LEN matches the 8 KiB split in upstream’s writer and the buf.Size limit of its PacketReader. The largest uplink frame is therefore 2 + 512 + 2 + 8192 = 8708 bytes, which fits the read buffer of the Trojan and VLESS runtimes once it has grown to its 16 KiB cap, so a well-formed frame never trips the runtime’s FrameTooLarge (protocol frame exceeds the read buffer). A VMess carrier reassembles a split frame in the held buffer instead. MIN_META_LEN is the session id, status and option. FRAME_OVERHEAD_MAX is 268: the most a frame this crate emits adds beyond its payload (a Keep or New with a UDP peer and a 255-byte domain address). A stream Keep header is 8 bytes and an End frame is 6.

protocols/src/mux/frame.rs
pub enum SessionStatus {
New,
Keep,
End,
KeepAlive,
}
pub struct FrameMeta {
pub session_id: u16,
pub status: SessionStatus,
pub option: u8,
pub target: Option<Destination>,
pub global_id: Option<[u8; GLOBAL_ID_LEN]>,
}
impl FrameMeta {
pub fn has_data(&self) -> bool // option & OPTION_DATA != 0
}
pub struct Frame {
pub meta: FrameMeta,
pub data: Option<Range<usize>>,
pub consumed: usize,
}

SessionStatus derives Debug, Clone, Copy, PartialEq and Eq; FrameMeta and Frame derive Debug, Clone, PartialEq and Eq. SessionStatus::from_byte and SessionStatus::byte (both private) map the status byte both ways, and the private dial_network maps the network byte to a DialNetwork. FrameMeta::target is the destination on a New frame, the per-packet peer on a UDP Keep frame, and None otherwise; its network comes from the network byte. Frame::data is the payload’s range inside the parsed buffer, not a copy, and consumed is the whole frame’s length.

protocols/src/mux/frame.rs
pub fn parse_meta(b: &[u8]) -> io::Result<FrameMeta>
pub fn parse_frame(buf: &[u8]) -> io::Result<Option<Frame>>
pub fn encode_keep(session_id: u16, udp_peer: Option<&Destination>, payload: &[u8]) -> Bytes
pub fn encode_end(session_id: u16) -> Bytes
pub fn encode_keep_into(
session_id: u16,
udp_peer: Option<&Destination>,
payload: &[u8],
out: &mut Staging<'_>,
) -> Option<()>
pub fn encode_end_into(session_id: u16, out: &mut Staging<'_>) -> Option<()>
pub(crate) fn encode_new_udp_into(
session_id: u16,
target: &Destination,
payload: &[u8],
out: &mut Staging<'_>,
) -> Option<()>
  • parse_meta decodes one metadata block. It reads the session id, status and option, decides whether a target follows (always on New, only when byte 4 is NETWORK_UDP on Keep, never on End or KeepAlive), reads the network byte and the address, and then the global id when the global_id rule applies. Bytes after the last field it reads are ignored.
  • parse_frame is the sans-I/O parser the demultiplexer uses. It returns Ok(None) while the buffer holds only part of a frame. It checks both length fields as soon as they are visible, before it waits for the body, so an oversized length fails at once instead of making the caller buffer up to 64 KiB.
  • encode_keep and encode_end build server-to-client frames into a BytesMut and freeze it into Bytes. encode_keep allocates payload.len() + 64 bytes up front and encode_end 8. Both write the metadata with the private put_meta, which writes a zero length prefix, the body, and then patches the prefix with the body length, because the prefix covers only what follows it. put_meta computes that length with saturating_sub and casts it with as u16, and encode_keep writes the payload length with as u16 too: neither has a failure path, unlike the checked u16::try_from in meta_bytes below, so callers keep payloads within MAX_DATA_LEN. The server never emits New or KeepAlive: upstream’s NewResponseWriter starts in follow-up mode, so every response is a Keep, and a session is closed with an End whose option is 0. The one New this crate sends is the XUDP client’s, from encode_new_udp_into.
  • encode_keep_into and encode_end_into write the same bytes straight into a Staging area. The private meta_bytes builds the metadata in a FRAME_OVERHEAD_MAX-byte stack array first, with checked arithmetic and u16::try_from for the length prefix. They return None and stage nothing when the room is short, the payload does not fit a u16, or the address does not encode (a domain over 255 bytes). Demux builds its downlink with encode_keep and encode_end; encode_keep_into serves the XUDP client and the unit tests, and encode_end_into only the unit tests.
  • encode_new_udp_into stages the New frame an XUDP client opens its UDP session with: OPTION_DATA, the network byte NETWORK_UDP and target, the first packet, and no global id, so no session reuse across carriers is asked for. It and encode_keep_into share the private encode_data_into, with the same None cases.

Earlier versions also had async readers, read_meta and read_data, which only the tests used. They were removed; the tests now read frames back with parse_frame.

protocols/src/mux/demux.rs
pub const MAX_SESSIONS: usize = 256;
pub const fn downlink_overhead(read_size: usize) -> usize
struct Sub {
key: SubKey,
peer: Option<Destination>,
}
enum Origin {
Slice(usize),
Held(usize),
}
pub struct Demux<T> {
sessions: BTreeMap<u16, Sub>,
generation: u32,
straddle: Vec<u8>,
partial_at: usize,
out: Vec<u8>,
flow: Flow<T>,
sniff: bool,
}
impl<T> Demux<T> {
pub fn new(flow: Flow<T>, sniff: bool) -> Self
pub fn held(&self) -> &[u8]
pub fn out(&self) -> &[u8]
pub fn keys(&self) -> impl Iterator<Item = FlowKey> + '_
pub fn is_empty(&self) -> bool
}
impl<T: Send + Sync + 'static> Demux<T> {
pub fn feed<C>(
&mut self,
plain: &[u8],
base: usize,
fx: &mut Effects<'_, C>,
) -> io::Result<usize>
where
C: ProxyCoreDecode<Key = FlowKey, Target = Flow<T>>;
pub fn feed_chunks<C>(
&mut self,
data: &[u8],
chunks: &[std::ops::Range<usize>],
fx: &mut Effects<'_, C>,
) -> io::Result<()>
where
C: ProxyCoreDecode<Key = FlowKey, Target = Flow<T>>;
pub fn take_out(&mut self) -> Vec<u8>
pub fn on_outbound(&mut self, key: SubKey, data: &[u8])
pub fn on_datagram(&mut self, key: SubKey, from: &Destination, data: &[u8])
pub fn on_outbound_gone<C>(&mut self, key: SubKey, fx: &mut Effects<'_, C>)
where
C: ProxyCoreDecode<Key = FlowKey, Target = Flow<T>>;
pub fn on_transport_eof<C>(&mut self, fx: &mut Effects<'_, C>)
where
C: ProxyCoreDecode<Key = FlowKey, Target = Flow<T>>;
}
Field Holds
sessions One Sub per live wire session id: its current SubKey, and for a UDP session the target from its New frame (peer), used as the fallback peer
generation The last generation minted. It starts at 0 and is incremented with wrapping_add on every accepted New, so the first sub-flow gets generation 1
straddle The held buffer: the frames completed from held bytes during the current byte event, which its held forwards reference, then the partial tail of a frame split across VMess chunks
partial_at Where the partial tail starts inside straddle
out The frames of the last call only: the downlink frames of a downlink call, or the declines of an uplink call
flow, sniff The carrier’s flow template, and whether sub-flows are sniffed

The private helpers:

Helper Job
session_id(key) The wire id of key, only while sessions[key.id] holds that exact SubKey
trim_held() Drains straddle up to partial_at and resets partial_at to 0; a no-op when partial_at is 0
parse_from(plain, base, fx) feed without the trim: parses whole frames off plain and dispatches each with Origin::Slice(base + at)
feed_chunk(plain, base, fx) One chunk of feed_chunks: completes the held partial frame, then parses the rest of the chunk in place. While it dispatches the completed held frame it moves straddle out with std::mem::take, because dispatch needs &mut self while the frame’s bytes are borrowed from that buffer, then puts it back and sets partial_at to straddle.len()
dispatch(frame, bytes, origin, fx) Applies one frame to the session table
deliver(id, range, peer, origin, fx) Pushes the forward or send for one payload
decline(id) Appends encode_end(id) to out
frame_need(buf) How many bytes the frame at the front of buf needs before it can be parsed, or None once it is whole
bad(what) An InvalidData error whose text is mux: followed by what

keys (documented as the live keys “for closing them all”) and is_empty are not called by the three cores at this revision; they close every sub-flow through on_transport_eof.

MAX_SESSIONS is a cap upstream does not have. Its doc comment gives the reason: Xray’s SessionManager has no limit, so a peer could open sessions until the process runs out of file descriptors. Past the limit a New is answered with End and its payload is discarded.

protocols/src/core/mod.rs
pub enum FlowKey {
Direct,
Sub(SubKey),
}
pub struct SubKey {
pub id: u16,
pub generation: u32,
}

Both derive Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord and Hash; Copy and Ord are what the runtime’s key bound (Copy + Ord + Send + Sync + 'static) requires. The three carrier cores declare type Key = FlowKey. FlowKey::Direct is the connection’s own flow on a plain request, and FlowKey::Sub is one mux sub-flow.

The generation exists because of the runtime’s key rule (concepts/src/runtime.rs): an Effect::Open on a key that still has an outbound slot fails the connection with RuntimeError::DuplicateKey (open reuses a live outbound key). A stream outbound’s slot stays until the outbound is gone: until both halves have closed, or it is closed or fails. After a Shutdown that means until its read side reaches EOF. A mux client may reuse a session id right after it ends it. When the client sends End, the demultiplexer removes the id from sessions and pushes Effect::Shutdown, while the old outbound’s slot may still be in the runtime (a stream outbound’s until its read side ends). A New on the same id then gets a fresh generation, so its SubKey differs and the two outbounds never collide.

session_id(key) maps a key back to its wire id only while sessions[key.id] still holds that exact key. Downlink bytes from a retired generation therefore frame nothing and are dropped. This is how a stream outbound that is still draining after the client’s End is kept off the wire.

Every parsed frame goes through Demux::dispatch. The payload is never copied on this path: the demultiplexer pushes an effect that names a range, either in the event’s slice (Origin::Slice) or in the held buffer (Origin::Held).

flowchart TB
  f["parse_frame"] --> s{"status"}
  s -- New --> n{"MAX_SESSIONS reached or id live?"}
  n -- yes --> dec["queue End for the id, drop the payload"]
  n -- no --> open["mint SubKey, sniff payload, push Open"]
  open --> del["deliver the payload"]
  s -- "Keep with data" --> k{"id live?"}
  k -- no --> dec
  k -- yes --> del
  s -- End --> e["remove the id, push Shutdown"]
  s -- "KeepAlive or Keep without data" --> x["nothing"]
  del --> u{"UDP session?"}
  u -- no --> fw["Forward or ForwardHeld"]
  u -- yes --> st["SendTo or SendToHeld, to the frame's peer or the session target"]

The rules, status by status:

  • New. target is required. parse_meta always reads it for New, and dispatch still fails with mux: new session without a target if it is missing. If sessions.len() >= MAX_SESSIONS, or the id is already live, the demultiplexer queues an End for that id and discards the frame’s payload. A duplicate New leaves the live session under that id as it is. Otherwise it mints SubKey { id, generation }, builds the sub-flow with flow.toward(target), and sniffs it (below). It pushes Effect::Open { key: FlowKey::Sub(key), target }, records the Sub (with peer set to the target for UDP), and delivers the payload if there is one.
  • Keep. A Keep with data on a live id is delivered. A Keep with data on an unknown id, for example one the server already ended, is answered with an End, as upstream does, so the client stops sending on it. A Keep without data is ignored.
  • End. The id is removed and Effect::Shutdown is pushed for its key. On a stream sub-flow that half-closes the outbound’s write side once everything forwarded to it is written. An End for an unknown id is ignored. An End that carries a data block has the block skipped. OPTION_ERROR is parsed but does not change what End does.
  • KeepAlive. Nothing happens in the demultiplexer. The transport event that carried it has already re-armed the idle deadline.

deliver chooses the effect from the session type and the origin of the bytes:

Session Bytes in the event slice Bytes in the held buffer
Stream (peer is None) Effect::Forward { key, range } Effect::ForwardHeld { key, range }
UDP (peer is the New target) Effect::SendTo { key, to, range } Effect::SendToHeld { key, to, range }

For a UDP session, to is the frame’s own address when the frame carried one, and the session’s New target otherwise. That is XUDP’s per-packet addressing: one sub-flow, one outbound key, many peers. Each UDP frame’s data block is exactly one datagram. A stream session’s frames that carry an address are delivered as stream bytes, and the address is not used.

Frame ranges are absolute. feed takes base, the offset of plain inside the event’s slice, and adds it to every range. feed_chunks takes each chunk as a range of the event’s slice data, so its ranges are absolute already and it has no base argument.

With sniff on, a New whose target is an IP address (sniff::worth_sniffing) has its payload passed to sniff::sniff, which tries only two sniffers: the TLS ClientHello (SNI) sniffer, then the HTTP request (Host) sniffer. A hit sets the sub-flow’s Flow::sniffed before Effect::Open is pushed, so routing sees it. The demultiplexer sniffs only the payload of the New frame, at most MAX_DATA_LEN bytes. It does not collect more bytes, and SNIFF_LIMIT (4096) and SNIFF_TIMEOUT (300 ms) do not apply: a sub-flow is routed the moment it opens, so the only bytes available to sniff are whatever its New frame carried, as the comment in dispatch says. A New without data, or one whose first bytes do not show the name, opens unsniffed. A New whose target is a domain is never sniffed. The same check runs for a UDP sub-flow, and whatever it finds is set on the sub-flow’s Flow but never used: the supervisor’s FanOutLink routes each packet as flow.toward(to), which resets sniffed to None, and files each sub-link under that flow.

sniff is the inbound’s InboundSpec::sniff (supervisor/src/topology/spec_plan/inbound.rs), which the supervisor passes to each core’s constructor. etemenanki-app lowers it from the [[inbound]] key sniffing (default true, app/src/config.rs, app/src/lower.rs); katana from [node.controller] disable_sniffing, negated (src/lower/inbound.rs). The comment there notes that disable_sniffing had no effect until the kernel learned to sniff, and that honouring it keeps the key from being a setting that quietly does nothing. How sniffing works on single-flow connections is described in Sniffing.

The carrier cores see mux frames in two shapes, and the demultiplexer has one entry point for each.

feed feed_chunks
Caller TrojanCore, VlessCore VMessCore, once per byte event with all opened chunks
Input The whole unparsed transport region, base 0 Every opened chunk’s range in data
Trailing partial frame Not consumed. feed returns the bytes used, and the runtime hands the tail back, prefixed to the next read Consumed. It is copied into straddle and completed by a later chunk, of the same event or the next
Effects for complete frames Forward / SendTo over the read buffer Forward / SendTo over the read buffer
Effects for a completed straddling frame Not applicable ForwardHeld / SendToHeld over straddle

A Trojan or VLESS carrier is plaintext at this layer, so a partial frame can stay in the runtime’s read buffer. VMess cannot do that: ChunkDecoder::open (protocols/src/vmess/framing.rs) opens each AEAD chunk in place and consumes it whole, so an unconsumed tail would come back already decrypted. VMessCore::open_chunks opens every whole chunk at the front of the read and returns what it opened:

protocols/src/vmess/core.rs
struct Opened {
plain: SmallVec<[Range<usize>; 16]>, // plaintext range of each opened chunk
consumed: usize, // bytes of the read those chunks took
ended: bool, // the terminator chunk ended the uplink
}

It stops at the first incomplete chunk (ChunkStep::NeedMore) or at the terminator (ChunkStep::End, which also sets uplink_done). Without a chunk decoder it fails with vmess: no session, a defensive check: the decoder is created with the request header, before the core can reach Mux.

feed_chunks then handles the event’s chunks one by one in the private feed_chunk, which copies a frame’s leading part into straddle instead of leaving it behind. When a partial frame is held from partial_at, frame_need works out how many bytes the frame needs in total: 2 while the metadata length is incomplete, then the end of the metadata, then (only when the option byte has OPTION_DATA) the end of the data length, then the end of the data. frame_need calls parse_frame first, so a length over its cap fails before frame_need trusts it. The loop copies only the missing bytes from the chunk. If the chunk runs out first, the partial frame stays held for the next chunk. Once the frame is whole, it is completed in place, after any frames completed earlier in the same event, and dispatched with Origin::Held(start), where start is its offset partial_at. partial_at then moves to the end of straddle, and the rest of the chunk is parsed in place with parse_from. A chunk that ends inside a frame appends that frame’s leading part at partial_at, for the next chunk of the event or the next event to complete.

A held range is resolved when the runtime applies the effect (The server runtime), so the demultiplexer leaves those bytes in place until its next byte event. trim_held runs only at the start of feed and of feed_chunks, that is once per byte event and never between the chunks of one event: it drains the completed frames before partial_at and keeps the partial tail. VMessCore passes every chunk that one read opened in a single feed_chunks call for this reason, because the held forwards pushed for earlier chunks of the read are applied only after the core returns. VMessCore::held, VlessCore::held and TrojanCore::held return Demux::held in the Mux state and the sniff prefix (SniffPrefix::held) otherwise. A held range that points past held() would end the connection with RuntimeError::RangeOutOfBounds (forward range outside the event slice or held buffer). The server core contract and the pin rule are described in Server cores and The server runtime.

During one byte event, straddle holds every frame completed from held bytes in that event (at most one per chunk), then the partial tail. Its size is therefore bounded by the tail carried in from the previous event plus the plaintext of one read. The carried tail is part of one frame, bounded by the length caps that parse_frame checks before frame_need trusts a length, so it is shorter than 8708 bytes.

Outbound events for a sub-flow reach the carrier core with FlowKey::Sub(key), and the core’s private on_sub passes them to the demultiplexer as a SubEvent (Bytes, Packet or Gone):

Core event Demux call Frames in out
Event::Outbound on_outbound(key, data) One Keep per MAX_DATA_LEN piece of data, without an address
Event::Datagram on_datagram(key, &from, data) One Keep with from as the UDP peer address. A packet longer than MAX_DATA_LEN is dropped
Event::OutboundEof, ConnectFailed, OutboundError on_outbound_gone(key, fx) One End, plus Effect::Close for the key, when the key is still the live generation; the id is freed
Event::TransportEof (the carrier’s uplink ended) on_transport_eof(fx) None. Effect::Close for every live sub-flow, and the table is emptied

Every Demux call that writes out clears it first: the downlink calls on_outbound, on_datagram and on_outbound_gone, and the uplink calls feed and feed_chunks. out therefore only ever holds the frames of the last call, and after an uplink call it contains only that call’s End declines, never downlink frames a carrier has already staged. The module docs state this rule (“whatever a carrier staged from it earlier is never queued again”); it is the fix for the 2.0.0 regression described at the end of Known limitations. A downlink call frames nothing when session_id(key) does not match.

The from address on a reply is the packet’s source as the datagram link reports it (Event::Datagram::from). A link that resolves domains reports the IP it received from, so a client that sent to a domain gets replies tagged with an IP. The XUDP client uses that address to attribute each reply to a peer. The three cores declare MAX_DATAGRAM = 8192, and the runtime receives an outbound packet into at most datagram_limit() bytes, the smaller of MAX_DATAGRAM and BUF_SIZE - STAGING_RESERVE, which is 8192 for all three. on_datagram therefore never sees more than MAX_DATA_LEN from the runtime, and its length check is a backstop.

After a sub-flow’s outbound ends, the demultiplexer sends End and closes the key in both directions. On the wire a mux session has no half-close: once either side ends an id, the server frames nothing more for it.

take_out moves the buffer out with std::mem::take, so the caller receives out’s allocation and out starts again as an empty Vec. The carrier cores deliver out in two ways:

  • TrojanCore and VlessCore read demux.out() in place after a downlink call and stage it with fx.stage when it is not empty, so the downlink reuses one buffer. After every uplink feed they call demux.take_out() and stage the result when it is not empty.
  • VMessCore calls take_out after every call, uplink and downlink, and seals the result with seal_frames, which does nothing for an empty buffer and otherwise calls seal(frames, fx, false): the pending response header first, if any, then body chunks of at most MAX_PAYLOAD (1966) bytes each. The response header is staged through reply, which stages it once and clears it; on a carrier that happens when the core enters Mux, so later seals find it empty. seal fails with vmess: downlink already ended once terminate has taken the chunk encoder. Chunk boundaries and frame boundaries are independent in both directions.

Events for a FlowKey::Direct key, or for a sub-flow key after the core has left the Mux state, are consumed and ignored.

The runtime delivers an outbound read of n bytes only when STAGING_RESERVE + n bytes of staging are free, and an outbound read is at most BUF_SIZE bytes. Framing adds headers, so each core declares their worst case in its reserve:

protocols/src/mux/demux.rs
pub const fn downlink_overhead(read_size: usize) -> usize {
read_size
.div_ceil(MAX_DATA_LEN)
.saturating_mul(FRAME_OVERHEAD_MAX)
}
Core BUF_SIZE STAGING_RESERVE MAX_DATAGRAM
TrojanCore 16384 PACKET_HEADER_MAX.next_multiple_of(16) + downlink_overhead(Self::BUF_SIZE) = 272 + 536 = 808 MAX_LENGTH = 8192
VlessCore 16384 272 + downlink_overhead(Self::BUF_SIZE) = 808 8192
VMessCore 32768 4096, a flat value for the response header and the chunk overhead of one read. It does not call downlink_overhead: a stream Keep header is 8 bytes, so the mux framing of one read is small next to the chunk overhead (CHUNK_OVERHEAD_MAX, 82 bytes per chunk) 8192

A reserve that is too small shows up as staging_full(), the error staging room below the core's declared reserve, which ends the carrier.

The sequence below shows a VLESS carrier with one stream sub-flow. Trojan differs only in its signal and in staging no response header. VMess seals every staged byte into chunks.

sequenceDiagram
  participant C as Xray client
  participant R as Runtime
  participant K as VlessCore
  participant D as Demux
  participant A as AppConnector
  participant O as Outbound
  C->>R: VLESS header with command 0x03
  R->>K: Event::Transport
  K->>R: stage RESPONSE_HEADER
  K->>D: Demux::new(flow, sniff)
  K->>R: enter Relay, SetDeadline 300 s
  C->>R: New id 1, TCP target, data
  R->>K: Event::Transport
  K->>D: feed(data, 0, fx)
  D-->>R: Open Sub(1, gen 1), Forward range
  R->>A: connect(sub-flow): admit, route
  A->>O: dial the routed target
  A-->>R: metered stream
  R->>O: forwarded bytes
  O-->>R: reply bytes
  R->>K: Event::Outbound for Sub(1, gen 1)
  K->>D: on_outbound(key, data)
  K->>R: stage Keep frames from out
  R-->>C: Keep id 1 with data
  O-->>R: read EOF
  R->>K: Event::OutboundEof
  K->>D: on_outbound_gone(key, fx)
  D-->>R: Close Sub(1, gen 1)
  R-->>C: End id 1
  C->>R: transport EOF
  R->>K: Event::TransportEof
  K->>D: on_transport_eof(fx)
  K->>R: ShutdownTransport, Finish

One stream SubKey (a session id plus a generation) goes through these states:

stateDiagram-v2
  [*] --> Live: New accepted, push Open
  Live --> Live: Keep with data, push Forward
  Live --> Live: outbound bytes, stage Keep frames
  Live --> Retiring: End from the client, push Shutdown
  Live --> [*]: outbound EOF, error or failed dial, stage End, push Close
  Live --> [*]: carrier uplink EOF, push Close
  Retiring --> [*]: outbound read EOF or error

In Retiring, the id is already free in sessions, the outbound’s write side is shut down once its pending bytes are written, and anything it still sends is dropped because session_id no longer matches. When its read side ends, the runtime removes the slot and the core’s on_outbound_gone finds no live key, so no second End goes out. A New on the same id starts a new SubKey in Live with the next generation. When the runtime is dropped (in the supervisor, for example when the carrier’s session token is cancelled), every outbound it owns goes with it.

A UDP sub-flow has the same Live transitions, with SendTo for uplink packets and one Keep per reply.

Uplink frames that do not open a key never reach this diagram. A New over MAX_SESSIONS, a duplicate New, and a Keep with data for an unknown id are each answered with one End on the downlink and leave the session table unchanged.

XUDP adds two things to mux.cool UDP sessions. The server implements the first and parses the second.

  1. Per-packet addresses. Each Keep frame of a UDP session may carry its own peer, and each downlink Keep names the peer the packet came from. parse_meta reads the address on a Keep frame when the network byte is NETWORK_UDP. deliver sends to that address, or to the session’s New target when a frame has none. on_datagram tags every reply with its source. In the supervisor, the UDP sub-flow’s outbound is a FanOutLink (supervisor/src/topology/outbound/udp_fanout.rs), which routes each packet on the plane current when it is sent, as the flow flow.toward(to). It keys its sub-links by OutboundId (an outbound’s tag and version), never by a target’s address, and keeps at most MAX_SUBS (64) of them, the least recently sent to going first. So one XUDP session can reach peers behind different outbounds. The fan-out is described in Outbounds, UDP fan-out and balancers.
  2. The global id. A New frame that opens a UDP session with data may append an 8-byte global id after the address. Xray uses it to let a UDP session continue over a new carrier. parse_meta decodes it into FrameMeta::global_id so the metadata block is fully accounted for, but the demultiplexer does not look at it: every New opens a fresh session, and a UDP session does not survive the loss of its carrier.

A VLESS outbound with the Vision flow sends each UDP flow as Xray’s VLESS client does: over a connection of its own, as a carrier with one XUDP session (protocols/src/vless/codec.rs → VlessDatagram::with_flow). The supervisor picks that codec for every UDP flow of a Vision outbound (supervisor/src/build/outbound.rs → build_outbound).

  • The request header carries CMD_MUX and the Vision addons, and no address.
  • Every packet is a frame of session 0 (XUDP_SESSION) that names its peer: the first a New toward it (encode_new_udp_into), each later one a Keep (encode_keep_into). A packet longer than MAX_DATA_LEN is dropped, as Xray’s XUDP writer drops one it cannot frame.
  • From the server it takes Keep frames with data as packets from the peer the frame names, or from the flow’s destination when it names none, skips a Keep without data and KeepAlive, ends the flow on End, and refuses a New (vless xudp: the server opened a session).

On a Vision inbound the adapter strips the flow from the header and VlessCore serves the carrier with Demux like any other. The Vision framing around it is on XTLS Vision, the codec on VLESS.

The runtime applies Effect::Open { key: FlowKey::Sub(key), target } by calling connect(target) on its connector and registering the returned future as that key’s outbound. In the supervisor the connector is the AppConnector built for the carrier’s session (supervisor/src/serve.rs → Shared::connector_for), so every sub-flow of one carrier shares one session, one FlowContext (the inbound tag and the connection’s source: the socket’s peer, the client a PROXY protocol v2 header named, the client named beside a handed-over socket, or the client a trusted proxy named in a WebSocket upgrade’s header) and one Tracker. An accepted connection is one session. On a gRPC transport each HTTP/2 stream is a session of its own, so a carrier inside a gRPC stream belongs to that stream’s session.

supervisor/src/connector.rs
#[derive(Clone)]
pub struct AppConnector {
plane: PlaneCell, // Arc<ArcSwap<Plane>>
ctx: FlowContext,
tracker: Tracker,
session: Option<Arc<Session>>,
charge_datagrams: bool,
}
impl AppConnector {
pub fn source(&self) -> Option<IpAddr>; // ctx.source: the connection's client
pub fn session(&self) -> Option<&Arc<Session>>;
}
type ConnectFuture =
Pin<Box<dyn Future<Output = io::Result<Outbound<Metered<OutboundStream>, FanOutLink>>> + Send>>;
impl Connector<Flow> for AppConnector {
type Stream = Metered<OutboundStream>;
type Datagram = FanOutLink;
type Future = ConnectFuture;
fn connect(&mut self, flow: Flow) -> ConnectFuture;
}
#[derive(Clone)]
pub(crate) struct FlowScope {
pub tracker: Tracker,
pub session: Option<SessionId>,
pub charge: Option<Arc<Wire>>,
}
flowchart TB
  o["Demux pushes Open for Sub(key)"] --> c["runtime calls AppConnector::connect"]
  c --> a{"Session::admit"}
  a -- refused --> f["ConnectFailed: End and Close for the key"]
  a -- admitted --> n{"destination network"}
  n -- UDP --> u["FanOutLink: each packet routed when sent"]
  n -- TCP --> p["load the plane, Plane::route"]
  p --> r["Target::resolve picks a balancer member"]
  r --> s["Target::connect_stream"]
  s --> m["Tracker::meter_stream: one tracked flow"]
  m --> d["Target::close_if_drained"]

connect first calls Session::admit(&flow.user.user_data) (supervisor/src/entity/session.rs). admit checks the session’s token first. On the first sub-flow, before it binds, it also checks the principal is not revoked and that the user’s device limit leaves room for the session’s source. The first sub-flow of a carrier binds the session to the carrier’s principal, the Arc<Principal> the protocol’s user table returned when the carrier authenticated, and sets the session’s bound flag. When that principal is a user, the same step also binds the session’s wire to the user’s account in the usage ledger (ledger.bind(user, id, wire)). Every later sub-flow is admitted on the token check and that flag alone. A refusal returns a future that fails at once, so the runtime hands the core Event::ConnectFailed for that key, the core logs it at debug level (vless: outbound gone: …, and the same with vmess: or trojan:), and the demultiplexer answers with End and Close for that sub-flow. The refusals are:

Error When
the session was closed The session’s token is cancelled, or, on the flow that would bind it, the session is no longer registered
the user was removed before the session opened a flow The principal was revoked before the first sub-flow bound the session. The admit also cancels the session’s token, so the carrier’s runtime is dropped (Shared::spawn_until)
the user's sessions already come from as many IPs as their device limit On the flow that would bind the session to a user with a device limit: the user’s bound sessions already come from as many distinct source IPs as the limit, and this session’s source is not one of them (Inner::over_device_limit). The admit also cancels the session’s token, so the carrier ends

How principals are revoked and what each removal policy does to live sessions is described in Users, principals and sessions.

A sub-flow whose destination network is UDP is not dialed. connect returns Outbound::Datagram(FanOutLink::new(...)) at once, with a FlowScope (the tracker, the session id, and charge) whose charge is None: only the SOCKS driver sets charging_datagrams, because SOCKS datagrams bypass its control stream, whereas a mux sub-flow’s datagrams travel inside the carrier’s stream, which the session’s wire already counts.

For a TCP sub-flow, connect loads the plane once (PlaneCell::load), calls Plane::route(&flow, &ctx) for a Routed { target, rule }, resolves a balancer to its member with Target::resolve(None), so the flow is filed under the outbound that carries it, and builds the flow’s metadata with FlowMeta::of. It then dials with Target::connect_stream(flow). Once the stream is metered, connect calls Target::close_if_drained(stream.entry()): if a drain closed that outbound version while the sub-flow was dialing, the new flow is killed as it is registered.

FlowMeta (supervisor/src/track/mod.rs) is fixed when the flow opens:

Field For a TCP sub-flow
session The carrier’s session id
inbound The inbound tag from the connector’s FlowContext
principal flow.user.user_data, the carrier’s principal
source flow.source, or else the connector’s source
destination The sub-flow’s own destination from its New frame
sniffed The domain sniffing found in the New payload, if any
outbound The OutboundId (tag and version) of the resolved target
rule The rule that matched, None for the default route
plane_epoch Plane::epoch() of the plane the flow was routed on

The route decision (supervisor/src/topology/router.rs → route_target) sees the sub-flow’s own destination address and port, its sniffed name, the inbound tag, the source, and the network. The flow’s source wins over the connector’s: for a TCP inbound they are the same address, but a QUIC inbound serves many peers from one socket and only the flow knows which. The network is passed so that RouteMatch::Network rules can match at all. Plane::route checks one thing first: when the plane has a DNS service, a flow to DNS_PORT (53) goes to it, keyed on the port alone over TCP and UDP, because an application retries over TCP after a truncated UDP answer and that retry must reach the same service. A mux sub-flow to port 53 is intercepted like any other flow (Name resolution and the DNS service).

The plane is read-copy-update. Because each connect loads it, a route change applied while a carrier is open reaches the next sub-flow the carrier opens, and a sub-flow already open keeps the target it was opened on. A TCP sub-flow is a tracked flow like any other, so Supervisor::close_rerouted, which a front end may call after an apply, closes it when the current plane would send it to another outbound. A UDP sub-flow’s FanOutLink loads the plane on every send, so a route change reaches its next packet. The plane: routing each flow describes the plane and the route decision.

Once the dial succeeds, Tracker::meter_stream(meta, stream) (supervisor/src/track/mod.rs) wraps the stream in a Metered that registers the sub-flow as one FlowEntry and counts its payload in both directions. Each fan-out sub-link of a UDP sub-flow is registered the same way with meter_datagram. Every flow of one carrier carries the same session id, inbound tag and user label.

  • Killing one sub-flow. Tracker::kill(id) calls FlowEntry::kill, which sets the flow’s kill flag and wakes both its read and its write waker. The Metered wrapper fails its next poll, in either direction, with an io::ErrorKind::ConnectionAborted error whose text is the flow was killed, the runtime hands the core Event::OutboundError for that key, the core logs vless: outbound gone: the flow was killed (or the vmess: or trojan: form) at debug level, and the demultiplexer sends End and Close for that sub-flow only. The carrier and its other sub-flows run on, and new sub-flows still open on it.
  • The carrier’s session. drive in supervisor/src/serve.rs adds the transport byte counts the runtime reports for each step (Traffic::transport_rx and transport_tx) to the session’s wire (Wire), so the wire includes the request header and the frame headers. The tracker’s per-flow counters count payload only. Per-user usage for billing comes from the session wires (Per-user usage accounting).
  • Closing the session. The carrier’s serve future runs under the session’s token (Shared::spawn_until). A removal policy that closes the session, a refused admission that cancels it (above), an explicit close, removing the inbound, or shutdown cancels that token, and the runtime is dropped with the Demux and every sub-flow.

The flow registry, flow events and sampling are described in Tracking flows, stats and speed limits, and the accept loop in Listeners and the serve loop.

katana 6 lowers each node into a supervisor spec (Lowering a node into a spec), so its VLESS, VMess and Trojan nodes serve carriers exactly as above. Its destination audit is routing: src/rule.rs → audit_routes turns each rule id into a blackhole outbound tagged audit#<id> and a route toward it, and the rules match domain names only, the requested one or the sniffed one, lower-cased. A mux sub-flow is routed on its own, so a sub-flow whose domain matches goes to that rule’s audit outbound like any other flow (Destination audit).

Invariant Mechanism Pinned by
A frame’s lengths are capped before the parser waits for its body parse_frame checks MAX_META_LEN and MIN_META_LEN from the 2-byte prefix, and MAX_DATA_LEN as soon as the data length is visible parse_frame_enforces_the_length_caps, frames_parse_from_slices_and_stage_into_buffers
Unknown status and network bytes, and metadata that ends inside a field, are errors SessionStatus::from_byte, dial_network, take / take_array returning ProtocolError::Truncated rejects_unknown_status_and_network, rejects_truncated_metadata
A stream Keep frame is never read as an address parse_meta reads a Keep target only when the network byte is NETWORK_UDP keep_frame_carries_an_address_only_when_flagged_udp, end_and_keepalive_carry_no_target
The global id is read only on a UDP New with data parse_meta’s global_id match parses_new_udp_session_with_global_id, parses_new_tcp_session
At most MAX_SESSIONS live session ids per carrier; excess, duplicate and unknown sessions are each answered with an End for that id The sessions.len() and contains_key checks in dispatch, and decline unknown_or_excess_sessions_are_declined_with_end (excess and unknown ids)
A reused session id never produces a duplicate runtime key A fresh generation per accepted New; session_id matches the exact SubKey stream_sessions_open_forward_and_end_with_fresh_generations
A retired generation frames nothing on the downlink session_id(key) returns None for a key that is not the live one stream_sessions_open_forward_and_end_with_fresh_generations
UDP payloads go to the frame’s peer, or the session target when none is given, and replies carry their source deliver with Sub::peer as the fallback; on_datagram passes from to encode_keep udp_sessions_address_each_packet_and_tag_replies, encoded_udp_keep_carries_the_peer_address, vless_xudp_datagram_roundtrip, xudp_attributes_replies_to_the_right_peer
Uplink payloads are forwarded by range, never copied, unless a frame straddles VMess chunks Origin::Slice in feed; Origin::Held only for a frame completed in straddle stream_sessions_open_forward_and_end_with_fresh_generations, a_frame_straddling_chunks_is_held_and_forwarded_from_the_held_buffer
The demultiplexer leaves held bytes in place until its next byte event trim_held runs only at the start of feed and feed_chunks, once per byte event a_frame_straddling_chunks_is_held_and_forwarded_from_the_held_buffer (trimmed at the next event)
Every frame one read completes from held bytes stays in straddle until the next byte event VMessCore passes all chunks of a read to one feed_chunks call; feed_chunk completes each held frame after the ones before it and does not trim vmess_keeps_every_frame_one_read_completes, vmess_mux_payload_spans_both_framings
Each downlink frame is staged once out.clear() at the start of every call that writes out, uplink and downlink a_downlink_frame_is_not_sent_again_by_the_next_uplink, vless_answers_mux_at_once_and_demultiplexes (the next uplink stages nothing), xudp_attributes_replies_to_the_right_peer
No stream downlink frame exceeds MAX_DATA_LEN on_outbound splits with chunks(MAX_DATA_LEN) vmess_demultiplexes_across_chunk_boundaries (10,000 bytes become two Keep frames)
The framing of one outbound read fits the room the runtime guarantees for it downlink_overhead in STAGING_RESERVE for Trojan and VLESS; the runtime’s reserve check before an outbound read frames_parse_from_slices_and_stage_into_buffers (a domain Keep fits FRAME_OVERHEAD_MAX exactly)
The carrier is answered before any sub-flow connects VLESS and VMess stage their response header on entering Mux vless_answers_mux_at_once_and_demultiplexes, vmess_demultiplexes_across_chunk_boundaries
Trojan detects a carrier by address is_mux_destination, which matches Remote::Domain alone, so the port plays no part trojan_carries_mux_when_the_connect_names_the_carrier, trojan_mux_tcp_single_stream (both connect to v1.mux.cool port 9527; no test uses another port)
A VLESS mux request carries no address parse_request_header substitutes mux_destination() after the command byte mux_command_synthesises_its_destination, mux_request_header_roundtrips, request_header_is_parsed_from_a_slice_once_whole
The XUDP client opens session 0 with one New without a global id, sends every later packet as a Keep naming its peer, and drops a packet over MAX_DATA_LEN VlessDatagram::seal_to with Framing::Xudp and its opened flag a_vision_datagram_codec_speaks_xudp, our_vision_client_carries_udp_to_an_xray_server
Every sub-flow is a tracked flow of its own, under the carrier’s session and user The runtime calls connect once per Effect::Open; Flow::toward keeps the carrier’s principal mux_sub_flows_and_their_session_count_exactly_what_moved
Each sub-flow is routed on the plane current when it opens, and keeps the target it opened on AppConnector::connect loads the plane per call a_route_change_reaches_the_next_mux_sub_flow_of_a_live_session
A kill reaches only the killed sub-flow The killed Metered fails at its next poll; the core closes only that key through on_outbound_gone killing_one_mux_sub_flow_leaves_its_siblings_and_the_carrier
  • Malformed frames end the carrier. Every error from parse_frame is returned as an io::Error from the core’s handle. The runtime stops with RuntimeError::Core, drive returns the error, and the runtime is dropped with every sub-flow. The messages are:

    Message Cause
    mux: metadata length N exceeds 512 Metadata length prefix over MAX_META_LEN
    mux: metadata length N below 4 Metadata length prefix under MIN_META_LEN
    mux: data length N exceeds 8192 Data length over MAX_DATA_LEN
    mux: unknown session status N Status byte outside 0x01 to 0x04
    mux: unknown target network N Network byte other than 0x01 or 0x02 where a target is read
    truncated input: … A field cut short inside a complete metadata block, for example truncated input: mux network for a New frame whose metadata stops at the option byte, or truncated input: fixed-size field for a port or IP address cut short
    unknown address type: N, empty domain name, non-utf8 domain, invalid domain name: … An address the codec rejects

    mux: new session without a target and mux: frame range are defensive checks in dispatch and parse_from that a frame from parse_frame does not reach. In the supervisor, the connection’s end is logged at debug level by etemenanki_supervisor::serve, in the form vless connection from Some(203.0.113.7) ended: proxy core: mux: metadata length 600 exceeds 512 (the protocol name, the connection’s source as an Option, and the runtime error).

  • Per-session problems. Excess, duplicate and unknown sessions are answered with an End for their id. A refused admission, a failed dial or an outbound error on one sub-flow reaches the core as ConnectFailed or OutboundError for that FlowKey::Sub, is logged at debug level as vless: outbound gone: <error> (or vmess:, trojan:), and on_outbound_gone sends End and closes only that key.

  • A refused datagram send. If the runtime reports one as Event::SendFailed, the core logs it at debug level as vless: packet to {to:?} dropped: {error} (or vmess:, trojan:) and changes nothing. The destination is printed in Rust’s Debug form, for example vless: packet to Destination { network: Udp, remote: IpAddr(192.0.2.10), port: 53 } dropped: ….

  • The carrier’s uplink ends. On Event::TransportEof, or the VMess uplink terminator chunk, the core calls on_transport_eof, which pushes Effect::Close for every live sub-flow, then moves to Done and pushes ShutdownTransport and Finish. VMess also seals its downlink terminator with terminate (the pending response header, if any, then seal_terminator_into) before ShutdownTransport. Stream sub-flows in Retiring are not in sessions, so on_transport_eof does not close them; they go when their own read side ends or fails, or when the runtime is dropped. What Finish does is described in The server runtime.

  • Idle carrier. RELAY_IDLE_TIMEOUT passes with no byte event in either direction. Timing::expired moves to Phase::Closing and pushes Finish, and the core returns Ok(0).

  • Handshake timeout. A carrier whose request header is not complete HANDSHAKE_TIMEOUT after its first bytes fails in the core with client did not complete its request in time. In the supervisor, a runtime step before the core is established that takes longer than HANDSHAKE_TIMEOUT ends the connection with inbound handshake timed out after 10s. Either way no sub-flow exists yet.

  • Staging shortfall. A fx.stage or seal that finds less room than it needs returns staging_full() (staging room below the core's declared reserve) and ends the carrier. For an outbound read, the room is what STAGING_RESERVE promises, which downlink_overhead sizes for Trojan and VLESS.

  • Runtime key errors. The generation keeps RuntimeError::DuplicateKey unreachable, and the pin rule keeps RuntimeError::RangeOutOfBounds unreachable for held ranges. Either would end the connection.

  • Cancellation. The demultiplexer owns no task, timer or socket. Dropping the runtime drops the core, the Demux and every outbound with it. In the supervisor the runtime is dropped when drive returns, or when the carrier’s session token is cancelled (Shared::spawn_until); a kill reaches one sub-flow instead.

Constant Value Where Effect
MAX_META_LEN 512 bytes protocols/src/mux/frame.rs Longer metadata is an error
MIN_META_LEN 4 bytes protocols/src/mux/frame.rs (private) Shorter metadata is an error
MAX_DATA_LEN 8192 bytes protocols/src/mux/frame.rs Longer uplink data is an error; downlink stream bytes are split at it; a longer downlink packet is dropped, and so is a longer packet from the XUDP client; the most a New frame offers to sniffing
FRAME_OVERHEAD_MAX 268 bytes protocols/src/mux/frame.rs Worst-case header of a frame this crate emits
GLOBAL_ID_LEN 8 bytes protocols/src/mux/frame.rs (private) Size of the XUDP global id
MAX_SESSIONS 256 protocols/src/mux/demux.rs Live session ids per carrier; further News are declined
downlink_overhead(16384) 536 bytes protocols/src/mux/demux.rs Staging reserve share for framing one Trojan or VLESS outbound read
MUX_PORT 9527 protocols/src/mux/mod.rs Reference only; the carrier check ignores the port
RELAY_IDLE_TIMEOUT 300 s protocols/src/core/mod.rs Idle limit of the whole carrier
HANDSHAKE_TIMEOUT 10 s protocols/src/core/mod.rs Used twice. The core’s deadline, armed by Timing::touch at the first byte event, fails the carrier with client did not complete its request in time if the request header is not complete by then. The supervisor’s drive also wraps each runtime step before the core is established in tokio::time::timeout(HANDSHAKE_TIMEOUT, …) and fails with inbound handshake timed out after 10s
MAX_DATAGRAM 8192 bytes the three cores Largest outbound packet the runtime delivers to a UDP sub-flow’s core
MAX_PAYLOAD 1966 bytes protocols/src/vmess/framing.rs Largest VMess body chunk that downlink frames are sealed into
MAX_SUBS 64 supervisor/src/topology/outbound/udp_fanout.rs Fan-out sub-links a UDP sub-flow keeps open; the least recently sent to goes first

These are functional limitations at the revision this page describes:

  • Only the New frame is sniffed. A sub-flow whose New frame carries no data, or too little of a ClientHello or HTTP request to show the name, opens unsniffed and routes on its destination. The comment in dispatch gives this as deliberate: a sub-flow is routed the moment it opens.
  • No XUDP session resumption. The global id is decoded and ignored; the comment in parse_meta says reuse across mux connections is not implemented.
  • A duplicate New is declined with an End for the live id. The live session is left open on the server, while the client is told that the id has ended.
  • No multiplexing client. etemenanki-app and katana outbounds never put several flows on one connection; the only client framing is the single XUDP session of a Vision outbound’s UDP flow. The module docs give this scope as deliberate.

History: etemenanki-protocols 2.0.0 sent downlink frames a second time on VLESS and Trojan carriers and scrambled VMess mux uploads. 2.0.1 fixed both with two rules this page describes: every call that writes out clears it first, and VMessCore passes all chunks of one read to a single feed_chunks call (Known issues).

Test File Pins
parses_new_tcp_session protocols/tests/unit/mux/frame.rs New metadata with a port-first IPv4 target; no global id on TCP, even with data
parses_new_udp_session_with_global_id same The 8-byte global id after a UDP target
keep_frame_carries_an_address_only_when_flagged_udp same A UDP Keep’s peer address; nothing parsed from a stream Keep
end_and_keepalive_carry_no_target same End and KeepAlive metadata
rejects_unknown_status_and_network same Status 0x09 and network 0x07 are errors
rejects_truncated_metadata same Short metadata and a cut IPv4 address are errors
parse_frame_enforces_the_length_caps same A 513-byte and a 3-byte metadata length are refused from the 2-byte prefix alone, and an 8193-byte data length from its prefix, before any body arrives
encoded_keep_round_trips_through_the_parser same encode_keep for a stream parses back exactly, with nothing left over
encoded_udp_keep_carries_the_peer_address same encode_keep with a UDP peer
encoded_end_has_no_data_block same encode_end layout
frames_parse_from_slices_and_stage_into_buffers same parse_frame waiting on partial frames, the staging encoders matching encode_keep, a short staging area refused, and FRAME_OVERHEAD_MAX fitting a 255-byte domain exactly
stream_sessions_open_forward_and_end_with_fresh_generations protocols/tests/unit/mux/demux.rs Open and Forward order, absolute ranges (base 100), the partial frame left unconsumed, Shutdown on End, generation 3 on reuse, a retired key framing nothing, Close and End on on_outbound_gone
unknown_or_excess_sessions_are_declined_with_end same End for an unknown Keep; exactly MAX_SESSIONS Opens and an End for the next id
udp_sessions_address_each_packet_and_tag_replies same Per-frame peers, the fallback to the New target, reply tagging
a_downlink_frame_is_not_sent_again_by_the_next_uplink same After a UDP reply is read in place with out(), as Trojan and VLESS stage it, the next uplink feed leaves nothing in out
a_frame_straddling_chunks_is_held_and_forwarded_from_the_held_buffer same feed_chunks holding a tail; the next event’s chunk, at offset 1000 of its read, completing it; ForwardHeld over the held buffer and an absolute Forward for the following frame; trimming at the next event
trojan_carries_mux_when_the_connect_names_the_carrier same A Trojan CONNECT to v1.mux.cool:9527 becomes a carrier; framed reply; End and Close on outbound EOF; Finish on transport EOF
vless_answers_mux_at_once_and_demultiplexes same RESPONSE_HEADER staged at once; a UDP sub-flow’s SendTo and its tagged reply; a next uplink packet to another peer that stages nothing
vmess_demultiplexes_across_chunk_boundaries same A frame split across two sealed chunks; downlink framed and sealed into chunks that a ChunkDecoder opens back (ChunkStep::Data), 10,000 bytes as two Keep frames
vmess_keeps_every_frame_one_read_completes same One read of three sealed chunks that completes two straddling frames: both ForwardHeld ranges resolve to their own payloads, and the last frame is forwarded in place
mux_command_synthesises_its_destination protocols/tests/unit/vless/protocol.rs A VLESS mux header yields mux_destination() and leaves the first frame unread
mux_request_header_roundtrips same A VLESS mux header is 19 bytes with no address
request_header_is_parsed_from_a_slice_once_whole same Among the slice-parsing checks, a mux header consumes 19 bytes and yields mux_destination()
a_vision_datagram_codec_speaks_xudp protocols/tests/unit/vless/codec.rs The XUDP client: a mux header with the Vision flow and no address, a New on session 0 toward the first peer without a global id, a Keep naming another, a 9000-byte packet dropped, and a Keep reply, a KeepAlive and an End read back
a_held_range_past_the_buffer_is_rejected concepts/tests/runtime.rs RangeOutOfBounds for a held range past held()
mux_sub_flows_and_their_session_count_exactly_what_moved supervisor/tests/tracking.rs Three VLESS mux sub-flows are three flows of one session, each with the inbound tag, the carrier’s user label, outbound direct, no rule and exactly its payload. In this test the session’s count equals the bytes the client socket sent and received (Mux::sent, Mux::received), the user’s sampled upload equals the payload, and take_usage returns the session’s count once
killing_one_mux_sub_flow_leaves_its_siblings_and_the_carrier same The client sees End for the killed sub-flow; its sibling still echoes; a new sub-flow opens; the session count stays 1
a_route_change_reaches_the_next_mux_sub_flow_of_a_live_session supervisor/tests/hot_swap.rs After a route change, the next sub-flow of a live carrier takes the new route (it ends without data), while the sub-flow opened before still echoes
a_speed_limit_change_keeps_the_users_sessions same A speed limit set through set_users keeps a live mux carrier’s session and its sub-flow
vless_mux_tcp_single_stream app/tests/integration/e2e_xray_mux.rs One stream over a VLESS carrier from a real Xray client
vless_mux_tcp_concurrent_streams_stay_separate same Eight concurrent 4 KiB streams on one carrier each get their own bytes
vless_mux_over_ws_tls same A carrier under WebSocket and TLS
vless_xudp_datagram_roundtrip same UDP over a VLESS carrier with xudpConcurrency
vmess_mux_tcp_single_stream same Mux frames inside the VMess chunk stream
vmess_mux_payload_spans_both_framings same A 64 KiB echo split by both framings
vmess_xudp_datagram_roundtrip same UDP over a VMess carrier
xudp_attributes_replies_to_the_right_peer same Two peers on one XUDP session, each reply attributed by its frame address
trojan_mux_tcp_single_stream same The address-based Trojan signal over WebSocket and TLS
our_vision_client_carries_udp_to_our_server, our_vision_client_carries_udp_to_an_xray_server, xray_vision_client_carries_udp_to_our_server app/tests/integration/e2e_xray_reality.rs XUDP under Vision over REALITY: datagrams to two UDP echoes through our client to our server and to Xray’s, and through Xray’s client to ours, each reply attributed to its peer
vmess_tcp_plain_mux katana tests/integration/xray_interop.rs An Xray client with mux enabled (concurrency 8) against a katana VMess node over plain TCP: the echo comes back and the fake panel receives traffic for the user
vless_ws_tls_mux same The same for a VLESS node under WebSocket and TLS
trojan_tcp_tls_mux same The same for a Trojan node over TLS

Run them from the Etemenanki workspace:

Terminal window
cargo test -p etemenanki-protocols mux
cargo test -p etemenanki-protocols request_header_is_parsed_from_a_slice_once_whole
cargo test -p etemenanki-protocols a_vision_datagram_codec_speaks_xudp
cargo test -p etemenanki-concepts --test runtime a_held_range_past_the_buffer_is_rejected
cargo test -p etemenanki-supervisor --test tracking mux
cargo test -p etemenanki-supervisor --test hot_swap mux_sub_flow
cargo test -p etemenanki-supervisor --test hot_swap a_speed_limit_change_keeps_the_users_sessions
cargo test -p etemenanki-app --test integration mux
cargo test -p etemenanki-app --test integration carries_udp

The mux filter does not match the VLESS slice-parsing test, the XUDP client test or the Vision UDP tests, and mux_sub_flow does not match the speed-limit test, so each has a line of its own.

and the katana ones from the katana repository:

Terminal window
cargo test --test integration mux

The Xray interop tests build Xray from the reference tree with Go (build_xray in app/tests/support/mod.rs and in katana’s tests/support/mod.rs). Without Go, or when the build fails, they print a SKIP: line and pass. katana’s helper builds from the sibling Etemenanki/Xray-core checkout and also skips, with a SKIP: line, when that checkout is missing. The XUDP two-peer test paces its two exchanges on purpose: back to back, they trip a buffer-aliasing race in Xray’s own mux client, which reports an earlier packet with a newer address.

The setup of each suite:

Suite Setup
etemenanki-app e2e_xray_mux etemenanki-app serves the inbound, and an Xray client with a SOCKS inbound dials it. The client’s mux settings are {"enabled":true,"concurrency":8}, plus "xudpConcurrency":4 for the UDP tests, which is what sends UDP over the carrier instead of a plain VLESS UDP request. The WebSocket tests use the path /muxws (MUX_WS_PATH) under TLS with a pinned certificate. Xray’s xudpProxyUDP443 defaults to reject, but the tests use ephemeral echo ports, so it never applies. Each exchange waits up to 15 s, 20 s in the concurrent-streams test and 30 s in the 64 KiB test
katana xray_interop Each mux test is run_interop(name, protocol, network, tls, true): a fake panel serves the node config and one user, katana runs the node, and an Xray client with "mux":{"enabled":true,"concurrency":8} echoes one payload through it. The test then waits up to 15 s for the fake panel to receive a traffic report with up > 0 && down > 0 for that user
etemenanki-supervisor tracking, hot_swap A hand-built VLESS mux client in supervisor/tests/support/mod.rs. Mux::open sends a VLESS header with the mux command, and Mux counts every byte its socket sent (sent, starting with the header) and received (received), which the tracking test compares with the session’s count. mux_new(id, target, data) builds a New frame with data toward an IPv4 TCP target and panics on an IPv6 one

How the suites are organised is described in Testing.