Sniffing
Source files: 80 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/protocols/src/sniff/mod.rsEtemenanki/protocols/src/sniff/collector.rsEtemenanki/protocols/src/sniff/tls.rsEtemenanki/protocols/src/sniff/http.rsEtemenanki/concepts/src/sniff.rsEtemenanki/concepts/src/lib.rsEtemenanki/concepts/src/core.rsEtemenanki/concepts/src/runtime.rsEtemenanki/protocols/src/lib.rsEtemenanki/protocols/Cargo.tomlEtemenanki/protocols/src/core/mod.rsEtemenanki/protocols/src/flow.rsEtemenanki/protocols/src/http/core.rsEtemenanki/protocols/src/http/protocol.rsEtemenanki/protocols/src/socks/server.rsEtemenanki/protocols/src/socks/handshake.rsEtemenanki/protocols/src/hysteria/server/config.rsEtemenanki/protocols/src/hysteria/server/inbound.rsEtemenanki/protocols/src/hysteria/server/datagrams.rsEtemenanki/protocols/src/trojan/core.rsEtemenanki/protocols/src/trojan/protocol.rsEtemenanki/protocols/src/vless/core.rsEtemenanki/protocols/src/vmess/core.rsEtemenanki/protocols/src/ss_legacy/core.rsEtemenanki/protocols/src/ss_2022/core.rsEtemenanki/protocols/src/anytls/core.rsEtemenanki/protocols/src/sss/core.rsEtemenanki/protocols/src/ss_aead.rsEtemenanki/protocols/src/tun/inbound.rsEtemenanki/protocols/src/tun/udp.rsEtemenanki/protocols/src/mux/mod.rsEtemenanki/protocols/src/mux/demux.rsEtemenanki/environment/src/routing.rsEtemenanki/app/src/config.rsEtemenanki/app/src/lower.rsEtemenanki/app/src/instance.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/serve.rsEtemenanki/supervisor/src/topology/router.rsEtemenanki/supervisor/src/topology/flow.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/connector.rsEtemenanki/supervisor/src/topology/outbound/udp_fanout.rsEtemenanki/supervisor/src/topology/outbound/dns.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/webclient/src/tracking.rsEtemenanki/webclient/src/router.rsEtemenanki/ffi/src/types.rsEtemenanki/ffi/src/client.rsEtemenanki/ffi/src/proxy.rsEtemenanki/protocols/tests/unit/sniff/mod.rsEtemenanki/protocols/tests/unit/sniff/collector.rsEtemenanki/protocols/tests/unit/sniff/tls.rsEtemenanki/protocols/tests/unit/sniff/http.rsEtemenanki/protocols/tests/unit/core/mod.rsEtemenanki/protocols/tests/unit/http/core.rsEtemenanki/protocols/tests/unit/hysteria/server/inbound.rsEtemenanki/protocols/tests/unit/trojan/core.rsEtemenanki/protocols/tests/unit/vless/core.rsEtemenanki/protocols/tests/unit/vmess/core.rsEtemenanki/protocols/tests/unit/ss_legacy/core.rsEtemenanki/protocols/tests/unit/ss_2022/core.rsEtemenanki/protocols/tests/unit/anytls/core.rsEtemenanki/protocols/tests/unit/sss/core.rsEtemenanki/protocols/tests/pipeline/socks.rsEtemenanki/protocols/tests/unit/socks/server.rsEtemenanki/protocols/tests/pipeline/tun.rsEtemenanki/concepts/tests/runtime.rsEtemenanki/environment/tests/unit/routing.rsEtemenanki/app/tests/integration/e2e_sniff.rsEtemenanki/app/tests/support/mod.rskatana/src/config.rskatana/src/lower/inbound.rskatana/src/manager/node.rskatana/src/rule.rskatana/tests/integration/sniff.rskatana/tests/support/mod.rs
A proxy request often names only an IP address. A TUN client always does, and so does a browser or proxy client that resolved the name before it connected. Such a flow cannot match any rule written in domains, geosite lists and katana’s audit rules included. Sniffing reads the first bytes the client sends through the tunnel, recovers the name it is addressing (the SNI of a TLS ClientHello, or the host of an HTTP/1.x request) and gives that name to the router as a second domain to match.
This page follows the mechanism from the two parsers up: the byte budget and the time window, the clock-free Collector, how a sans-I/O core holds the collected prefix and forwards it after the connect, the protocols that must answer the client before they can sniff, mux sub-flows and AnyTLS streams, how the sniff flag travels from a config file to each core, and the two places in etemenanki-supervisor that read the result. Read it before you add a sniffer, add sniffing to a new core, or change what routing or tracking does with Flow::sniffed.
Responsibilities
Section titled “Responsibilities”Sniffing fills Flow::sniffed for a flow whose destination is a bare IP, and nothing else. Only a TCP flow’s value is ever read: a UDP mux sub-flow can carry one that nothing reads (see Mux sub-flows). By design it does not:
- fail a connection. Every parser returns
Option. Malformed, truncated or unrecognised bytes yieldNone, and the flow is then routed on its destination as if sniffing were off. The module docs ofprotocols/src/sniff/mod.rsput it as “strictly a hint”. - change the destination. The outbound dials the address the client asked for. Only routing and flow tracking read the sniffed name.
- inspect a flow that already names a domain.
worth_sniffingrejects it before the core enters the sniffing phase, so such a flow never waits for a sniff window. - recognise anything but a TLS ClientHello and an HTTP/1.x request. There is no QUIC, DNS or BitTorrent sniffer:
SniffedProtocolhas two variants,TlsandHttp. UDP flows are never collected, so the SNI inside a QUIC Initial packet is not read (see Which requests are sniffed).
The pieces are spread over the kernel crates, etemenanki-supervisor and the front ends:
| Crate | Piece | Role |
|---|---|---|
etemenanki-concepts |
concepts/src/sniff.rs |
The shared vocabulary: Sniffer, SniffedBehavior, SniffedProtocol. No parsing. |
etemenanki-concepts |
concepts/src/core.rs, concepts/src/runtime.rs |
The held buffer, Effect::ForwardHeld and the rule that makes forwarding a held prefix after the dial safe. |
etemenanki-protocols |
protocols/src/sniff/ |
The two parsers, plausible_domain, worth_sniffing, the Collector, SNIFF_LIMIT and SNIFF_TIMEOUT. |
etemenanki-protocols |
protocols/src/core/mod.rs and each server core |
SniffPrefix, Phase::Sniff and Expired::Sniff: holding the bytes, arming the window, opening the flow with the result. |
etemenanki-environment |
environment/src/routing.rs |
RouteTarget::sniffed_domain, which every domain matcher consults. |
etemenanki-supervisor |
supervisor/src/build/inbound.rs, supervisor/src/serve.rs |
Carry InboundSpec::sniff into each handler and core. |
etemenanki-supervisor |
supervisor/src/topology/router.rs → route_target, supervisor/src/track/mod.rs → FlowMeta::of |
The two readers of Flow::sniffed, used by every front end. |
| Front ends | app/src/lower.rs, katana src/lower/inbound.rs, ffi/src/client.rs |
Set InboundSpec::sniff and never touch Flow::sniffed. The REST API (webclient/src/tracking.rs) and the mobile library (ffi/src/types.rs) display the name the tracker recorded (see Tracking). |
Key types
Section titled “Key types”The shared vocabulary
Section titled “The shared vocabulary”concepts/src/sniff.rs defines what a sniffer produces, with no parsing. The concepts crate’s module map (concepts/src/lib.rs) describes sniff as “what sniffing recovered from a flow’s first bytes, carried to routing alongside the destination”. protocols/src/flow.rs imports SniffedBehavior from there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum SniffedProtocol { Tls, Http,}
#[derive(Debug, Clone)]pub struct SniffedBehavior { pub protocol: SniffedProtocol, pub domain: CompactString,}
pub trait Sniffer { fn sniff(&self, data: &[u8]) -> Option<SniffedBehavior>;}Sniffer::sniff is a pure function of the bytes, with no state and no clock. The collector calls it again on the whole buffer each time more bytes arrive, and stops calling it once a call has returned Some.
Nothing outside the tests reads SniffedBehavior::protocol. Routing and tracking take only domain.
Budget, window and entry points
Section titled “Budget, window and entry points”protocols/src/sniff/mod.rs holds the two limits and three free functions, and re-exports Collector, Verdict, HttpSniffer and TlsSniffer:
pub const SNIFF_TIMEOUT: Duration = Duration::from_millis(300);pub const SNIFF_LIMIT: usize = 4 * 1024;const MAX_DOMAIN_LEN: usize = 253;
pub fn plausible_domain(host: &str) -> Option<CompactString>;pub fn sniff(data: &[u8]) -> Option<SniffedBehavior>;pub fn worth_sniffing(destination: &Destination) -> bool;| Constant | Value | Why it must exist |
|---|---|---|
SNIFF_TIMEOUT |
300 ms | In a server-speaks-first protocol the client sends nothing until the server has spoken; the code comment names SMTP, SSH and MySQL. Without a window the core would wait forever while holding the transport. |
SNIFF_LIMIT |
4096 bytes | Without it a peer could stream an unbounded amount before being routed. The budget spans frames, because a ClientHello with a long extension list can exceed one read or one AEAD chunk. |
MAX_DOMAIN_LEN |
253 | The longest legal DNS name. plausible_domain rejects anything longer. |
| Function | Called by |
|---|---|
plausible_domain |
The two parsers: TlsSniffer (in server_name) and HttpSniffer (for an absolute-form authority and for Host). |
sniff |
Collector::push, Demux for a mux sub-flow’s New payload, and AnyTlsCore for the data that came with a stream’s address. |
worth_sniffing |
Each sniffing core (HttpCore, Hy2StreamCore, TrojanCore, VlessCore, VMessCore, ShadowsocksCore, Ss2022Core, SssCore, and PassthroughCore::sniffing), SocksInbound::connect, Demux and AnyTlsCore. |
sniff runs the implemented sniffers in a fixed order:
pub fn sniff(data: &[u8]) -> Option<SniffedBehavior> { TlsSniffer.sniff(data).or_else(|| HttpSniffer.sniff(data))}TLS goes first because, in the words of the code comment, its record header is “a far tighter discriminator than an HTTP request line”. The two cannot both match the same bytes: the TLS sniffer requires a first byte of 0x16, and the HTTP sniffer requires the buffer to start with an upper-case method name.
worth_sniffing is the gate every caller checks before it enters the sniffing phase:
pub fn worth_sniffing(destination: &Destination) -> bool { matches!(destination.remote, Remote::IpAddr(_))}A destination that already names a domain routes by that name, so waiting on it would cost every such flow up to SNIFF_TIMEOUT and buy nothing. The check looks at remote only, not at network: keeping UDP out is the job of the callers, which never enter the phase for a datagram request. The one caller that offers UDP bytes to the sniffers anyway, the mux demultiplexer, is covered under Mux sub-flows.
Collector and Verdict
Section titled “Collector and Verdict”protocols/src/sniff/collector.rs is the clock-free half of sniffing: a bounded accumulator that re-runs sniff over everything it holds each time bytes are appended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Verdict { Found, More, Exhausted,}
#[derive(Debug, Default)]pub struct Collector { buf: Vec<u8>, found: Option<SniffedBehavior>,}
impl Collector { pub fn new() -> Self; pub fn remaining(&self) -> usize; pub fn push(&mut self, bytes: &[u8]) -> Verdict; pub fn held(&self) -> &[u8]; pub fn found(&self) -> Option<&SniffedBehavior>; pub fn take(self) -> (Vec<u8>, Option<SniffedBehavior>);}| Verdict | Meaning |
|---|---|
Found |
A sniffer recognised the bytes; nothing more is needed. |
More |
Nothing recognised yet and the budget is not spent. |
Exhausted |
The budget is spent without a match; stop waiting. |
| Method | Behaviour |
|---|---|
new |
An empty collector with no result. It owns no memory: the doc comment notes that every protocol core builds one when a connection is accepted, before anything is known about the peer, and only a flow that reaches its sniff phase ever fills it. |
remaining |
SNIFF_LIMIT.saturating_sub(buf.len()): how many more bytes fit. |
push |
The first non-empty push reserves the whole SNIFF_LIMIT in one allocation, so filling the budget never reallocates; an empty push reserves nothing. It appends all of bytes, then runs sniff(&buf) unless a result is already stored. Returns Found if a result exists, else Exhausted if buf.len() >= SNIFF_LIMIT, else More. Found wins: a match in the bytes that fill the budget is still Found. Once a result is stored, later pushes append without sniffing again. |
held |
Everything collected so far. It is ordinary payload that the caller must forward to the outbound ahead of the rest of the stream. |
found |
The stored result, by reference. |
take |
Consumes the collector and returns the bytes and the result. The async SOCKS server uses it. |
push does not truncate its input. The caller must offer at most remaining() bytes, and both callers do: SniffPrefix::push slices its input, and the SOCKS server’s collect_prefix reads at most remaining() bytes per read.
Collector has no deadline. A sans-I/O core arms the runtime’s single timer itself through Timing, and the async SOCKS server wraps its reads in tokio::time::timeout_at. Keeping the clock out of Collector lets both kinds of caller share it and lets the unit tests drive it without a runtime.
SniffPrefix in the cores
Section titled “SniffPrefix in the cores”Every sniffing sans-I/O core composes a SniffPrefix from protocols/src/core/mod.rs. It wraps a Collector and adapts it to the core contract, where handle returns how many bytes of an event it consumed.
#[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;}| Method | Behaviour |
|---|---|
new |
A prefix over an empty Collector. |
push |
Takes take = min(plain.len(), collector.remaining()) bytes and returns take with the verdict. With nothing to take, it answers Exhausted if the budget is spent and More otherwise (an empty input, such as a zero-length Shadowsocks record). A plaintext core returns take as its consumed length, so bytes past the budget stay in the runtime’s read buffer and are relayed normally after the open. |
held |
Everything collected, “to forward ahead of the rest of the stream”. Every byte push takes is kept, not only the bytes up to the name: in a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host the second event carries the rest of the Host line and a 4-byte body, and the held range covers all 41 bytes. |
found |
The stored result, by reference. |
result |
Clones the found value and leaves the bytes in place, because they still have to be forwarded. |
clear |
Drops the collected bytes “once the forward that referenced them has been applied”, and the buffer they were in: “sniffing is over by then”. It replaces the collector with a new one, which owns no memory. Each sniffing core calls it at its first Transport or Outbound event after the open, which the held-buffer rule makes safe. |
is_empty |
True when nothing is held. |
The same file defines the phase and deadline machinery that sniffing plugs into:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Phase { Handshake, Sniff, Relay, Closing,}
pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);pub const RELAY_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Expired { Handshake, Sniff, Idle,}
#[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;pub fn staging_full() -> io::Error;| Call | In Phase::Sniff |
|---|---|
enter(Phase::Sniff, fx) |
Sets the phase and pushes Effect::SetDeadline(Some(SNIFF_TIMEOUT)). The runtime has one timer and “arming again replaces the previous deadline”, so in a core that parses a request header this replaces the handshake deadline that touch armed on the core’s first event. PassthroughCore never calls touch before it starts sniffing, so its first event arms only this deadline. |
touch(fx) |
Does nothing. The window is therefore a fixed 300 ms from the moment the core starts sniffing, not an idle timer that each byte extends. |
expired(fx) |
Clears armed, returns Expired::Sniff and pushes no effect. The core then opens the flow with whatever it holds. |
is_established() |
false. It becomes true in Phase::Relay, which the core enters when it opens. |
handshake_timed_out() is TimedOut with the text client did not complete its request in time. A core cannot return it while sniffing, because Expired::Handshake is only reported in Phase::Handshake. staging_full() is io::Error::other("staging room below the core's declared reserve").
The window reaches a sniffing core through the runtime: the core arms it with Effect::SetDeadline and learns that it passed from Event::Deadline.
Flow::sniffed
Section titled “Flow::sniffed”The result travels on the flow itself, in 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::new starts with sniffed: None. A core sets the field immediately before it pushes Effect::Open, so the connector sees it when it routes. Flow::toward builds a flow for another destination that shares the user and source, and it resets sniffed to None (see Flow::toward starts clean). The hand-written Clone keeps sniffed; it is written out so that cloning does not require T: Clone.
In the supervisor the flow is supervisor/src/topology/flow.rs → pub type Flow = etemenanki_protocols::flow::Flow<Principal>;.
The TLS ClientHello parser
Section titled “The TLS ClientHello parser”protocols/src/sniff/tls.rs → TlsSniffer walks the record header, the handshake header and the extension list to the server_name extension (RFC 8446 section 4.1.2, RFC 6066 section 3). It reads only what it needs and ignores every version field.
const RECORD_HANDSHAKE: u8 = 0x16;const HANDSHAKE_CLIENT_HELLO: u8 = 0x01;const EXT_SERVER_NAME: u16 = 0x0000;const SNI_HOST_NAME: u8 = 0x00;const AFTER_RANDOM: usize = 4 + 2 + 32;
#[derive(Debug, Clone, Copy, Default)]pub struct TlsSniffer;
fn u16_at(b: &[u8], at: usize) -> Option<u16>;fn client_hello_sni(data: &[u8]) -> Option<CompactString>;fn server_name(ext: &[u8]) -> Option<CompactString>;TlsSniffer::sniff maps the name client_hello_sni returns into SniffedBehavior { protocol: SniffedProtocol::Tls, domain }. u16_at reads a big-endian u16 at an offset and returns None past the end.
Wire layout
Section titled “Wire layout”The record header is read from the whole buffer:
| Field | Size | Offset | What the parser does |
|---|---|---|---|
| Content type | 1 | 0 | Must be 0x16 (RECORD_HANDSHAKE), else None. |
| Legacy record version | 2 | 1 | Not read. |
| Record length | 2 | 3 | Advisory: body = data[5 .. min(5 + length, data.len())]. |
The rest of the walk works on body, so these offsets are into body:
| Field | Size | Offset in body |
What the parser does |
|---|---|---|---|
| Handshake type | 1 | 0 | Must be 0x01 (HANDSHAKE_CLIENT_HELLO), else None. |
| Handshake length | 3 | 1 | Not read. |
legacy_version |
2 | 4 | Not read. |
random |
32 | 6 | Skipped. The walk starts at AFTER_RANDOM = 4 + 2 + 32 = 38: handshake header, legacy_version and random, as an offset into body. |
legacy_session_id |
1 + n | 38 | Length byte, then skipped. |
cipher_suites |
2 + n | varies | Big-endian length, then skipped. |
legacy_compression_methods |
1 + n | varies | Length byte, then skipped. |
| Extensions length | 2 | varies | Sets ext_end = min(p + length, body.len()). |
| Extension type | 2 | per extension | 0x0000 (EXT_SERVER_NAME) ends the walk. |
| Extension length | 2 | per extension | The extension data must lie inside body, else None. |
Inside the server_name extension:
| Field | Size | What the parser does |
|---|---|---|
server_name_list length |
2 | The list must lie inside the extension data, else None. |
name_type |
1 | Only 0x00 (SNI_HOST_NAME) carries a domain. Other types are skipped. |
| Name length | 2 | The name must lie inside the list, else None. |
HostName |
n | Must be UTF-8, then must pass plausible_domain. |
The walk
Section titled “The walk”- Check the content type, read the record length and cut
body. The code comment calls the record length advisory: a ClientHello may be split across records, and while bytes are still arriving the buffer holds only a prefix of the first one. The walk runs out of bytes and returnsNone, and the nextCollector::pushtries again with more. - Check the handshake type and set
p = AFTER_RANDOM. - Skip the three variable-length vectors, each with
p = p.checked_add(width)?.checked_add(length)?. - Read the extensions length and compute
ext_end, clamped tobody.len(). - While
p < ext_end, read the type and length, takebody.get(at..at + len)?, and returnserver_name(edata)at the first extension of type0x0000. Otherwise step past the extension. - In
server_name, walk the entries and returnplausible_domainof the firsthost_nameentry.
The parser stops at the first server_name extension and the first host_name entry, even when that entry fails plausible_domain. Both RFCs allow only one of each.
Because every length is checked against the bytes present, a truncated ClientHello can only produce None or the real name. An extension whose data runs past body ends the whole parse with None, whether or not it is the server_name extension, so a cut inside the SNI fails before the name is read. A cut at an extension boundary ends the loop at ext_end, which was clamped to body.len(), and also yields None.
How the bounds are checked
Section titled “How the bounds are checked”No step can panic or read out of bounds, whatever the peer sends:
- Every offset is computed with
checked_add, so an overflowing length yieldsNone. - Every read goes through
slice::getoru16_at, which returnNonepast the end. ?carriesNoneout of the whole parse.
The crate-level lint set in protocols/src/lib.rs keeps it that way: #![deny(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing, clippy::arithmetic_side_effects)], lifted only under cfg(test) (“Tests exercise known-good inputs and may use the panicking forms freely”). The lints are deny, so an index expression or an unchecked + in a parser is a cargo clippy error, whatever warning level the run uses.
The HTTP request parser
Section titled “The HTTP request parser”protocols/src/sniff/http.rs → HttpSniffer recovers the host of an HTTP/1.x request. Its first job is to refuse bytes that merely contain Host:.
const METHODS: &[&str] = &[ "GET", "POST", "HEAD", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH",];
#[derive(Debug, Clone, Copy, Default)]pub struct HttpSniffer;
fn request_host(data: &[u8]) -> Option<CompactString>;fn request_target(line: &str) -> Option<&str>;fn authority_of(target: &str) -> Option<CompactString>;fn strip_port(host: &str) -> Option<&str>;fn find(haystack: &[u8], needle: &[u8]) -> Option<usize>;HttpSniffer::sniff maps the result of request_host into SniffedBehavior { protocol: SniffedProtocol::Http, domain }.
- Cut the head.
head_endis the position of the first\r\n\r\n(found byfind, a window search), or the end of the buffer when the blank line has not arrived yet, which is the usual case while collecting. Onlydata[..head_end]is decoded, and it must be valid UTF-8. A body after the head is never decoded, so a binary body does not defeat the parse. - Require a request line. The head is split on
\r\n.request_targetsplits the first line on single spaces and requires a method fromMETHODS(case-sensitive), a request target, and a third field starting withHTTP/. Anything else yieldsNone. The code comment calls the fixed method list “the check that keeps binary payloads from being read as HTTP”. It also means an HTTP/2 connection preface (PRI * HTTP/2.0) and methods outside the list, such as WebDAV’s, are not recognised. - Prefer an absolute-form authority. If the target starts with
http://orhttps://,authority_oftakes the text up to the first/, drops userinfo by keeping what follows the last@, strips the port and runsplausible_domain. A proxy request carries this form, and the module docs call its authority “the better answer when both are present”. When it yields a domain it wins over anyHostheader; when it does not (an IP authority, for example), the parser falls through to the next step. - Otherwise read
Host. Lines without a:are skipped. The first header line whose name (the text before the first:, not trimmed) equalshost, ignoring ASCII case, supplies the value. LaterHostlines are not consulted, even when the first one is rejected. The value is trimmed,strip_portremoves a trailing:followed only by digits (or by nothing), andplausible_domaindecides.
strip_port leaves a value that starts with [ untouched, so a bracketed IPv6 literal reaches plausible_domain whole and is rejected there for its characters.
plausible_domain
Section titled “plausible_domain”Both parsers end in the same filter, which decides whether a string can be used as a routing domain:
pub fn plausible_domain(host: &str) -> Option<CompactString>;| Step | Rule | Rejects |
|---|---|---|
| 1 | Trim trailing . characters. |
Nothing: example.com. becomes example.com. |
| 2 | Length must be 1 to MAX_DOMAIN_LEN (253). |
"", ".", a 254-character name |
| 3 | Every character is ASCII alphanumeric, -, . or _. |
Spaces, :, [, ], /, ?, non-ASCII, and therefore every IPv6 literal such as ::1 |
| 4 | Must not parse as IpAddr. |
IPv4 literals such as 192.0.2.1 |
An IP literal is rejected on purpose. The doc comment gives the reason: it “says nothing the destination did not already say, and honouring it would let a peer relabel a flow with an address it is not talking to”. Case is preserved here; the route model lowercases the name when it matches (see Routing).
Where the flag comes from
Section titled “Where the flag comes from”Every inbound carries one boolean, InboundSpec::sniff, from its front end to the supervisor, which hands it to each core it builds.
flowchart LR app["etemenanki-app: sniffing"] --> spec["InboundSpec::sniff"] kat["katana: not disable_sniffing"] --> spec ffi["ffi: appended tun inbound"] --> spec spec --> build["build_handler"] build --> stream["StreamInbound::sniff"] build --> socks["SocksInbound in the user table"] build --> hy2["Hy2 ServerConfig::sniff"] build --> tun["TunInbound::without_sniffing"] stream --> cores["serve_connection: core constructors"] hy2 --> hcore["Hy2StreamCore::new"] tun --> pt["PassthroughCore::sniffing"]
Front ends
Section titled “Front ends”| Front end | Key and default | Lowered in | Covered by |
|---|---|---|---|
| etemenanki-app | Per inbound: sniffing, app/src/config.rs → InboundConfig::sniffing, default true through default_sniffing |
app/src/lower.rs → lower_inbound copies it into InboundSpec::sniff for every inbound protocol, tun included |
etemenanki-app: from TOML to a spec |
| katana | Per node: disable_sniffing under [node.controller], src/config.rs → ControllerConfig::disable_sniffing, default false |
src/lower/inbound.rs → lower_inbound sets sniff: !cfg.controller.disable_sniffing |
Lowering inbounds and outbounds |
| Mobile library | The app config’s tun inbound, or none |
ffi/src/client.rs → supply_tun appends a TUN inbound with sniff: true when the config has none |
Mobile library |
The doc comment on InboundConfig::sniffing reads “Inspect the opening payload for a routing domain (default true)”, and gives the trade: “Only a flow whose destination is a bare address is inspected, and only briefly; turning this off gives that up in exchange for never waiting on a client that speaks second.”
The katana lowering comment explains why the key is honoured at all: it “had no effect at all until the kernel learned to sniff; honouring it is what keeps the key from being a setting that quietly does nothing”.
In the mobile library the platform supplies the TUN device. The doc comment on supply_tun says what that means for the config’s own tun inbound: “The platform owns the interface, so what the config says of its name, addresses and routes does not apply; its MTU, UDP relay, flow limits and sniffing do.” Such an inbound keeps its sniffing value. When it names an interface name, addresses or routes, supply_tun logs at WARN: inbound <tag>: the platform owns the tun interface, so its name, addresses and routes in the config are ignored. A config with more than one tun inbound is refused with the config has more than one tun inbound; the platform supplies one device.
The supervisor
Section titled “The supervisor”pub struct InboundSpec { pub tag: CompactString, pub bind: BindSpec, pub handoff: Option<HandoffSpec>, /// Whether to read a domain out of a flow addressed by IP. pub sniff: bool, pub protocol: InboundProtocolSpec, pub users: Option<CompactString>, pub user_removal: Option<UserRemovalPolicy>, pub proxy_protocol: bool, pub real_ip: Option<RealIpSpec>,}supervisor/src/build/inbound.rs → build_handler places the flag where each kind of handler reads it:
| Handler | Where the flag lives | Who reads it |
|---|---|---|
| Stream protocols (HTTP, Trojan, VLESS, VMess, Shadowsocks, Shadowsocks 2022, AnyTLS, sss) | StreamInbound::sniff |
supervisor/src/serve.rs → serve_connection passes it to the core constructor for each accepted connection. The field lives in supervisor/src/topology/inbound/mod.rs (“Whether to read a domain out of a flow addressed by IP”). |
| SOCKS | Inside the SocksInbound that user_table builds with SocksInbound::new(config, spec.sniff); a user-set change rebuilds the table with the same value |
SocksInbound::connect |
| Hysteria 2 | protocols/src/hysteria/server/config.rs → ServerConfig::sniff (“Whether to read a domain out of a flow that was addressed by IP”), set by hy2_handler |
The listener passes config.sniff to Hy2StreamCore::new for each classified proxy stream. |
| TUN | TunInbound::sniff, true from TunInbound::new; build_handler calls TunInbound::without_sniffing() when spec.sniff is false |
Each TCP flow gets PassthroughCore::sniffing(flow) or PassthroughCore::new(flow). TunInbound::sniffs() also hands the flag to the IPv6 screen: supervisor/src/serve.rs → ipv6_unreachable passes it as may_sniff to Plane::ipv6_unreachable, whose CompiledRoutes::every_outcome → RouteTable::every_outcome (environment/src/routing.rs) also counts every earlier rule with a domain matcher, which a domain sniffed later could still make match. See TUN. |
The constructors that take the flag:
pub fn new(config: Arc<HttpServerConfig<T>>, sniff: bool, source: Option<IpAddr>) -> Self;// protocols/src/socks/server.rspub fn new(config: SocksServerConfig<T>, sniff: bool) -> Self;// protocols/src/hysteria/server/inbound.rs (Hy2StreamCore)pub fn new(user: UserEntry<T>, sniff: bool, source: IpAddr) -> Self;// protocols/src/trojan/core.rs and protocols/src/vless/core.rspub fn new(validator: Arc<Validator<T>>, sniff: bool, source: Option<IpAddr>) -> Self;// protocols/src/vmess/core.rspub fn new( validator: Arc<AccountValidator<T>>, now: fn() -> i64, sniff: bool, source: Option<IpAddr>,) -> Self;// protocols/src/ss_legacy/core.rspub fn new(inner: Arc<Resolved<T>>, sniff: bool, source: Option<IpAddr>) -> Self;// protocols/src/ss_2022/core.rs (the supervisor calls with_system_clock)pub fn with_system_clock( config: Arc<Ss2022ServerConfig<T>>, validator: Option<Arc<Validator<T>>>, sniff: bool, source: Option<IpAddr>,) -> Self;// protocols/src/anytls/core.rspub fn new( validator: Arc<Validator<T>>, padding: Arc<PaddingScheme>, sniff: bool, source: Option<IpAddr>,) -> Self;// protocols/src/sss/core.rspub fn new( validator: Arc<Validator<T>>, max_datagram: u16, sniff: bool, source: Option<IpAddr>,) -> Self;// protocols/src/core/mod.rs (PassthroughCore, used by TUN)pub fn new(flow: Flow<T>) -> Self;pub fn sniffing(flow: Flow<T>) -> Self;// protocols/src/tun/inbound.rspub fn without_sniffing(self) -> Self;// protocols/src/mux/demux.rs (the carrier core passes its own flag)pub fn new(flow: Flow<T>, sniff: bool) -> Self;PassthroughCore::sniffing stores sniff = worth_sniffing(&flow.destination), so the decision is made once, when the core is built. A TUN flow’s destination is always the IP the packet was addressed to.
Changing the flag on a running supervisor
Section titled “Changing the flag on a running supervisor”InboundSpec equality covers sniff, so a spec that flips it on an inbound whose BindSpec is unchanged plans Step::Build of the inbound and Step::SwapHandler (supervisor/src/topology/spec_plan/plan.rs). The listener stays open. A core reads the flag once, when it is built; connections accepted after the apply are served by the new handler. Planning and applying a change covers the plan.
A sniffing change on a tun inbound is a TUN change: etemenanki-app refuses the reload, keeps the running config and logs the reason (app/src/instance.rs). A restart applies it. See etemenanki-app: running, reloading and shutting down.
katana treats a disable_sniffing change as a local rebuild setting: the comment in src/manager/node.rs → apply_static calls these “Local settings the listener or its routes are built from”, which the panel’s answer cannot show. When the node’s supervisor is up, apply_static runs one panel poll at once with rebuild = true; a node still coming up builds from the new config on its next attempt. reconcile applies the new spec with ApplyOptions { allow_disruptive: true } and then calls supervisor.close(Selector::All), so the node’s open connections are closed. See The node manager.
Which requests are sniffed
Section titled “Which requests are sniffed”A caller sniffs only when its flag is set and worth_sniffing(&flow.destination) is true, and only for the request kinds in this table:
| Inbound | Where | Sniffed requests | Bytes inspected | Reply before sniffing |
|---|---|---|---|---|
| TUN | PassthroughCore::sniffing |
TCP connections | First transport bytes | No reply exists |
| HTTP | HttpCore |
CONNECT only |
Tunnel payload | Yes, HTTP/1.1 200 Connection established |
| SOCKS 4, 4a, 5 | SocksInbound::connect |
CONNECT only |
Tunnel payload | Yes, the grant |
| Hysteria 2 | Hy2StreamCore |
TCP streams | Stream payload | Yes, a TCPResponse “Connected” |
| Trojan | TrojanCore |
CONNECT (0x01), except to the mux address |
Payload after the header | No |
| VLESS | VlessCore |
Command::Tcp |
Payload after the header | No |
| VMess | VMessCore |
Command::Tcp |
Decrypted body chunks | No |
| Shadowsocks | ShadowsocksCore |
Every request (TCP) | Decrypted chunks | No |
| Shadowsocks 2022 | Ss2022Core |
Every request (TCP) | Decrypted records | No |
| sss | SssCore |
cmd = 0x01 (TCP) |
Payload after the header, after the transform chains are undone | No reply exists |
| AnyTLS | AnyTlsCore |
Every TCP stream to an IP | The data that came in the same event as the stream’s address only | No |
| mux.cool | Demux |
Every New to an IP |
The New frame’s payload only |
No |
A plain (non-CONNECT) HTTP proxy request is never sniffed: HttpCore opens it as soon as its head is parsed, with the request rewritten to origin form in its rewritten buffer. HttpCore::held returns rewritten when it is not empty and the sniff prefix otherwise, so both uses share the one held-buffer mechanism.
UDP requests are never collected: SOCKS UDP ASSOCIATE, Trojan (0x03), VLESS and VMess UDP, sss UDP streams (cmd = 0x02), AnyTLS UDP-over-TCP streams, the Hysteria 2 datagram core (protocols/src/hysteria/server/datagrams.rs → Hy2UdpCore) and TUN UDP (protocols/src/tun/udp.rs → TunUdpCore, whose Expired::Sniff arm does nothing) open their flows without entering Phase::Sniff.
A SOCKS UDP ASSOCIATE is served by SocksInbound::associate, which never reads the sniff flag. It opens its one link with Flow::new(dest, user, source) for the first datagram it forwards, so sniffed stays None, and it forwards only datagrams from the client its ExpectedSender admits. Whom an association hears covers that check.
Over the TLS, WebSocket, gRPC and REALITY transports the transport unwraps the tunnel before the protocol core sees it, so sniffing inspects the same payload it would over plain TCP. That holds for the SOCKS and Shadowsocks inbounds that sit behind a transport too, and for VLESS under the Vision adapter, which hands VlessCore the unframed body. On a gRPC carrier each HTTP/2 stream is a session of its own and is sniffed on its own.
Data flow
Section titled “Data flow”Phases of a sniffing core
Section titled “Phases of a sniffing core”Every single-stream core that sniffs has the same shape, whatever its protocol calls the states: State::Sniff(Flow<T>) in the HTTP, Hysteria 2, Trojan, VLESS and sss cores; State::Sniff with the flow stored beside it in VMess and both Shadowsocks cores; pending plus Phase::Sniff in PassthroughCore.
stateDiagram-v2 [*] --> Handshake Handshake --> Relay: parsed, domain target or sniff off Handshake --> Sniff: parsed, IP target and sniff on Sniff --> Sniff: push returns More Sniff --> Relay: Found or Exhausted Sniff --> Relay: Event Deadline, Expired Sniff Sniff --> Relay: client EOF, then half-close Relay --> Closing Closing --> [*]
Every exit from Sniff goes through the core’s open path (open_sniffed, or open in PassthroughCore), which does three things in order:
flow.sniffed = self.prefix.result(), which isSomeonly afterFound.timing.enter(Phase::Relay, fx), which pushesEffect::SetDeadline(Some(RELAY_IDLE_TIMEOUT)): the one deadline is now the 300 s idle limit.- Push
Effect::Openwith the flow, thenEffect::ForwardHeld { range: 0..held }when anything was collected.
The unit tests pin exactly this order: SetDeadline(RELAY_IDLE_TIMEOUT), Open, ForwardHeld. The doc comment of Timing::enter gives the reason the deadline comes first: a forward queued after the Open waits out the connect, and so would a deadline queued after that forward, so the sniff window’s 300 ms would still be armed during the connect and could end the flow as idle.
When the whole request header arrives in the core’s first event, that event pushes two deadlines: touch arms HANDSHAKE_TIMEOUT, then enter(Phase::Sniff) arms SNIFF_TIMEOUT, which replaces it. sniffing_an_ip_target_holds_the_prefix_until_a_host_is_found checks that the second effect of the Trojan header event is SetDeadline(Some(SNIFF_TIMEOUT)). A core whose first event is an earlier part of the request pushes only the sniff deadline on the header event: VMess arms the handshake deadline on the call that takes the 16-byte auth id, and the two Shadowsocks cores on the call that takes the salt.
PassthroughCore has no header to parse. It enters Phase::Sniff on its first transport event without calling touch, so that event pushes only SetDeadline(Some(SNIFF_TIMEOUT)) (a_sniffing_passthrough_core_holds_the_prefix_and_opens_with_the_host asserts one effect), and its window starts with the client’s first bytes. A runtime delivers no event before the client speaks, so TUN’s serve_stream (protocols/src/tun/inbound.rs) keeps its own HANDSHAKE_TIMEOUT watchdog per runtime step until the core is established, and fails a silent flow with TimedOut and the text tun: the client never spoke. The TUN inbound logs a flow that ends in an error at debug as tun: tcp flow <source> -> <destination> ended: <error>. The 300 ms sniff deadline produces a step long before that watchdog could fire.
The supervisor’s drive (supervisor/src/serve.rs) works the same way for the stream cores: is_established() stays false through Phase::Sniff, and its per-step watchdog is HANDSHAKE_TIMEOUT (10 s) against the 300 ms window. When it fires, the connection fails with inbound handshake timed out after 10s.
Collecting inside a sans-I/O core
Section titled “Collecting inside a sans-I/O core”flowchart TB
ev["Event::Transport(data)"] --> push["SniffPrefix::push(plain)"]
push --> take["take = min(len, remaining)"]
take --> sniffers["sniff(held): TLS, then HTTP"]
sniffers --> v{"Verdict"}
v -->|More| ret["return Ok(take), wait for the next event"]
v -->|"Found or Exhausted"| open["open_sniffed"]
dl["Event::Deadline"] --> open
eof["Event::TransportEof"] --> open
open --> relay["Phase::Relay: SetDeadline RELAY_IDLE_TIMEOUT"]
relay --> fx["Effect::Open, then Effect::ForwardHeld 0..held"]
The cores fall into two groups by how their payload arrives:
- Plaintext payload (HTTP, Hysteria 2, Trojan, VLESS, sss, TUN). The core pushes the event slice directly and returns the count
SniffPrefix::pushtook. sss’s core sees the stream after its transform chains are undone, so its payload is plaintext too. The HTTP, Hysteria 2, Trojan, VLESS and sss cores return right after the request header, so the payload that followed it in the same read reaches theSniffstate on the runtime’s next call: the runtime offers the unparsed rest again while the core keeps consuming. Bytes past the budget stay unconsumed and are relayed normally after the open. - Decrypted payload (VMess, Shadowsocks, Shadowsocks 2022). The core opens a chunk or record in place, pushes its plaintext range, and consumes the chunk whole. When the verdict ends collection partway through a chunk, the core pushes an
Effect::Forwardfor the plaintext after the bytes it took. VMess opens every complete chunk of the event first:VMessCore::open_chunksreturns anOpened { plain, consumed, ended }with the plaintext ranges, the bytes they took, and whether the terminator chunk (ChunkStep::End) ended the uplink, which also setsuplink_done. TheSniffarm pushes the ranges in order until the verdict ends collection, then forwards the later ranges of the same event withEffect::Forward; ifendedis set it opens (when it has not yet) and half-closes the outbound in the same call. The two Shadowsocks cores return after the record that ended collection and relay the rest on the next call.
The Shadowsocks cores also receive payload inside the request itself. The legacy core accumulates its first plaintext in its own held buffer until the address parses, and what follows the address is payload; a Shadowsocks 2022 variable header carries a first payload. Both push that payload before deciding, so a request whose own payload already answers Found or Exhausted opens at once without entering Phase::Sniff:
| Core | Payload in the request | Budget ends inside that payload |
|---|---|---|
ShadowsocksCore::on_address |
Moved out of held into a Vec |
The sniff result is set, the prefix and the rest of the payload are copied together into held, the prefix is cleared, and one ForwardHeld carries both (“hold the prefix and the rest together so one forward carries both”). The private held_bytes, which ProxyCoreDecode::held returns, is held when it is not empty and the prefix otherwise. held and the prefix are both cleared at the first Transport or Outbound event in Relay. |
Ss2022Core, variable header |
A range of the chunk decrypted in place in the event slice | open_sniffed, then an Effect::Forward for the rest of the payload range. No copy is needed, because the bytes are still in the event slice. |
The held-buffer rule
Section titled “The held-buffer rule”A sniffing core consumes the collected bytes from the wire and keeps them in SniffPrefix. It exposes them through ProxyCoreDecode::held and forwards them by range with Effect::ForwardHeld, which the runtime resolves against held() when it applies the effect. That happens after the connector has dialled, not when the effect is pushed.
The rule that makes this safe is in concepts/src/core.rs (module docs, “The held buffer”, whose first listed use is sniffing): until every queued held effect has been applied, the runtime delivers the core no byte event (Transport, TransportDatagram, Outbound, Datagram, OutboundEof, TransportEof). concepts/src/runtime.rs enforces it: a queued held effect pins the held buffer, and while it is pinned the runtime does not read the transport. The events that can still arrive meanwhile (Connected, ConnectFailed, OutboundError, Deadline) may only append to the held buffer. A core can therefore drop the prefix with SniffPrefix::clear at its first Transport or Outbound event in Relay, and every sniffing core does.
When the runtime queues a held effect it checks the range against held().len(); a range past the end fails the connection with RuntimeError::RangeOutOfBounds, displayed as forward range outside the event slice or held buffer. Per-connection runtime covers the runtime side.
Reply before sniff
Section titled “Reply before sniff”Three kinds of client send nothing after their request until the server has answered. Sniffing needs payload, so these servers answer success first, then collect, then connect:
| Protocol | What the client waits for | Where the early answer is written |
|---|---|---|
HTTP CONNECT |
HTTP/1.1 200 Connection established |
HttpCore::on_head stages CONNECT_ESTABLISHED (protocols/src/http/protocol.rs) |
SOCKS 4, 4a and 5 CONNECT |
The grant | SocksInbound::connect calls write_granted |
| Hysteria 2 TCP stream | The TCPResponse |
Hy2StreamCore stages response(true, "Connected") |
The Hysteria 2 module docs give the reason: “A client blocks reading the TCPResponse before it sends any payload, and sniffing means reading payload.” The other protocols let the client send payload right behind the request header, so they collect first and answer after the connect, where the protocol has an answer at all: VLESS and VMess stage their response headers on Event::Connected, and the two Shadowsocks cores send theirs (a fresh salt for legacy Shadowsocks, a response header for Shadowsocks 2022) with the first downlink bytes. Trojan and TUN have no answer.
sequenceDiagram participant C as Client participant S as Server core participant R as Runtime participant N as Connector participant T as Target 192.0.2.10 C->>S: CONNECT 192.0.2.10:443 S->>R: stage success, SetDeadline(SNIFF_TIMEOUT) R->>C: success answer C->>S: ClientHello S->>S: SniffPrefix::push returns Found S->>R: SetDeadline(RELAY_IDLE_TIMEOUT), Open (sniffed = example.com), ForwardHeld 0..n R->>N: connect(flow) N->>N: route_target with the sniffed domain N->>T: dial 192.0.2.10:443 R->>S: Event::Connected Note over S: reply is false, no second answer R->>T: held ClientHello
The diagram shows the sans-I/O cores. HttpCore and Hy2StreamCore open a sniffed flow with reply: false, so Event::Connected stages nothing. Both declare a STAGING_RESERVE large enough for the early answer: 256 bytes for HTTP (“A status line and its headers”), and 2048 for a Hysteria 2 TCPResponse with the longest padding. If staging still fails, the core returns staging_full().
SOCKS is not a sans-I/O core. SocksInbound::connect in protocols/src/socks/server.rs follows the same order with async I/O:
async fn collect_prefix<S: AsyncRead + Unpin>( stream: &mut S,) -> (Vec<u8>, Option<etemenanki_concepts::sniff::SniffedBehavior>);granted = self.sniff && worth_sniffing(&flow.destination). The code comment explains why the decision is recorded here: “The prefix does not say whether that happened: a client waiting for the server to speak first (SSH, SMTP) leaves it empty.”- When
granted,write_granted(protocols/src/socks/handshake.rs) sends the success reply, andcollect_prefixruns. It collects into aCollectorunder one deadlineSNIFF_TIMEOUTahead: each pass reads at mostremaining()bytes undertokio::time::timeout_at(deadline, …). The loop stops on a verdict other thanMore, on EOF, on a read error, at the deadline, or when no room is left, and returnsCollector::take().flow.sniffedis set from the result. connector.connect(flow)routes withflow.sniffedset. If it fails and the request was not granted early,write_refusalanswers with the code fromrefusal_code:STATUS_CONNECTION_REFUSED(0x05) forConnectionRefused,STATUS_HOST_UNREACHABLE(0x04) otherwise. The code applies to SOCKS5; a SOCKS4 or 4a client always gets request rejected. A granted request gets no refusal.- When not
granted, the grant is written now, after a successful connect. For SOCKS5,write_grantednames the connection’s local IP as the bound address, or0.0.0.0when there is none (a Unix socket). - A non-empty prefix is written to the upstream with
write_alland then flushed, andrelay_with_idle_guardrelays both directions with aRELAY_BUF(16 KiB) buffer per direction. EveryRELAY_IDLE_TIMEOUTit compares the relay’srelayed()count with the last one, and fails withTimedOutand the textsocks: relay idlewhen nothing moved.
The client therefore gets exactly one reply. If the client sent nothing within SNIFF_TIMEOUT, the prefix is empty, the connect goes ahead after the window, and the upstream’s first bytes follow the single grant, which is what a server-speaks-first protocol needs.
The flush in step 5 matters for an upstream that holds small writes until it is flushed: a WebSocket sink keeps messages below its write buffer, and sss’s transforms encode only on a flush. The relay flushes only after its own writes, so without it the client’s first bytes would wait in the upstream until the client sent more, and a TLS or HTTP client waiting for the answer to them never does. the_sniffed_prefix_reaches_an_upstream_that_buffers pins it.
Mux sub-flows
Section titled “Mux sub-flows”protocols/src/mux/demux.rs → Demux serves mux.cool inside Trojan, VLESS and VMess. The carrier core passes its own sniff flag to Demux::new(flow, sniff).
Demux::dispatch fixes a sub-flow’s sniffed name when it parses the New frame, in the same step that pushes the sub-flow’s Effect::Open, so the only bytes available to sniff are whatever that frame carried. A sub-flow is sniffed once, from that payload, with no Collector, no SNIFF_LIMIT and no deadline:
let mut flow = self.flow.toward(target.clone());if self.sniff && crate::sniff::worth_sniffing(&target) { flow.sniffed = payload.and_then(crate::sniff::sniff);}A New without data, or one whose data ends before the SNI or the Host line, gives the sub-flow no sniffed name. A New that Demux declines (the session table already holds MAX_SESSIONS, 256, or the id is live) is not opened and not sniffed: decline queues an End frame for the id toward the client, and the frame’s payload is not delivered. Each sub-flow’s Effect::Open goes through the connector like any flow, and the connector loads the current plane for it.
The carrier itself is never sniffed. Trojan checks crate::mux::is_mux_destination before it considers sniffing: the check compares a domain destination with MUX_ADDRESS (v1.mux.cool) ignoring ASCII case, and ignores the port (MUX_PORT, 9527, is informational; the doc comment says “the port is not part of the signal”). VLESS and VMess switch to State::Mux on Command::Mux.
The check is worth_sniffing(&target) alone, so a UDP sub-flow’s first packet is offered to the sniffers too. The result is never read for UDP; see Flow::toward starts clean.
AnyTLS streams
Section titled “AnyTLS streams”AnyTlsCore carries many streams on one session, as mux.cool does, and sniffs them the same way. open_tcp routes a stream the moment its address is whole, and sniffs only the data that came in the same event as the address, with crate::sniff::sniff and no Collector, SNIFF_LIMIT or deadline. Its doc comment gives the reason: holding the session’s uplink for one stream’s sniff would stall the others. A stream whose first data arrives in a later event, or whose destination is a domain, gets no sniffed name; UDP-over-TCP streams are not sniffed. sniffing_reads_only_the_data_that_came_with_the_address pins all three cases. See AnyTLS.
How the result is used
Section titled “How the result is used”Two functions in etemenanki-supervisor read Flow::sniffed: route_target, to route the flow, and FlowMeta::of, to record it on the tracked flow. etemenanki-app, katana and the mobile library all use them through the same connector.
Routing
Section titled “Routing”supervisor/src/connector.rs → AppConnector::connect first admits the flow on its session (session.admit, when the connector has one); a refusal fails the connect before any routing. It then turns a UDP flow into a FanOutLink and routes a TCP flow on the plane:
self.plane.load()loads the current plane. The code comment gives the reason: “Loaded once for this flow: a route change reaches the next flow, while this one keeps the target it is opened on.”Plane::route(&flow, &ctx)(supervisor/src/topology/plane.rs) first checks DNS interception: when the plane has a DNS service and the destination port isDNS_PORT(53), the flow goes to that service with no rule, and the route table, sniffed name included, is not consulted. Otherwiseroute_upstreamcallsCompiledRoutes::decide, which matchesroute_target(flow, ctx).routed.target.resolve(None)picks a balancer’s member,FlowMeta::of(...)captures the flow’s metadata (the sniffed name included),target.connect_stream(flow)opens it, andTracker::meter_streamrecords the flow once the stream is open.Target::close_if_drainedthen kills the new flow if a drain closed that outbound version while it was dialing.
Plane::route_upstream is also called directly by the DNS service’s own queries (supervisor/src/topology/outbound/dns.rs → RoutedDialer), so they skip the port-53 interception: “intercepting them would send the service’s questions back to itself”. Those flows are built with Flow::new and carry no sniffed name. Name resolution and the DNS service covers RoutedDialer.
pub fn route_target<'a>(flow: &'a Flow, ctx: &'a FlowContext) -> routing::RouteTarget<'a>;route_target builds RouteTarget::new(remote, port) from the destination, then calls with_sniffed_domain(s.domain.as_str()) when flow.sniffed is set, then adds the inbound tag, the source (flow.source.or(ctx.source)) and the network. The doc comment explains the sniffed name: “a flow addressed by IP carries its real name only in its payload, and passing it here is what lets a domain or geosite rule reach such a flow at all”. The plane: routing each flow covers the other fields.
RouteTarget in environment/src/routing.rs is Copy and is built with RouteTarget::new and the with_* setters “rather than a struct literal, so a later field costs consumers nothing”. Its sniffed_domain field is “a domain recovered from the payload … when the request itself carried only an IP”. RouteTable::pick builds the private Domains view once per routed flow (Domains::of, “case-folded once per routed flow rather than once per matcher”). It holds the request’s own domain (when the destination names one) and the sniffed domain, both lowercased with to_ascii_lowercase:
| Matcher | Reads the sniffed name |
|---|---|
DomainSuffix, DomainKeyword, DomainFull, GeoSite |
Yes, through Domains::any: the rule matches if either name satisfies it. DomainSuffix uses is_subdomain_of: the name itself or a subdomain of it (example.com and a.example.com, not notexample.com). |
DomainRegex |
Yes, through Domains::any. It holds a DomainRegexSet, the patterns compiled into regex::RegexSets. |
Cidr, GeoIp |
No. They read remote, so an IP-addressed flow with a sniffed name still matches them on its address. |
SourceCidr, PortRange, Network, InboundTag |
No. |
No matcher reads SniffedBehavior::protocol, and the first-match order of the table is unchanged: an IP-addressed flow with a sniffed name can match a domain rule through the name or an IP rule through its address, and whichever rule comes first wins. Routing covers the matchers.
katana’s destination audit is built on the same matchers. src/rule.rs → audit_routes turns each panel rule id into a blackhole outbound audit#<id> and a route whose matcher comes from routing::parse_domain_regexes. The module docs state the consequence: “Rules match domain names only — the one requested, or the one sniffed — lower-cased.” A sniffed name can therefore trigger an audit rule. See Destination audit.
Tracking
Section titled “Tracking”supervisor/src/track/mod.rs → FlowMeta::of copies the name onto the tracked flow:
/// What a flow is, fixed when it opens.#[derive(Debug, Clone)]pub(crate) struct FlowMeta { pub session: Option<SessionId>, pub inbound: CompactString, pub principal: Arc<Principal>, pub source: Option<IpAddr>, pub destination: Destination, pub sniffed: Option<CompactString>, pub outbound: OutboundId, pub rule: Option<RuleId>, pub plane_epoch: u64,}
impl FlowEntry { /// Where it goes. For a UDP sub-link, the first packet's destination. pub fn destination(&self) -> &Destination; /// The domain sniffing recovered, if any. pub fn sniffed(&self) -> Option<&str>;}FlowMeta::of sets sniffed: flow.sniffed.as_ref().map(|s| s.domain.clone()), beside the rule that matched and the plane’s epoch. FlowEntry::destination() keeps reporting the requested address and FlowEntry::sniffed() the name. Two front ends expose it:
| Front end | Field | Where |
|---|---|---|
REST API (webclient/src/tracking.rs) |
FlowView::sniffed |
GET /v1/connections and the opened and closed events of GET /v1/connections/events, both routed in webclient/src/router.rs (The REST API) |
Mobile library (ffi/src/types.rs) |
ConnectionInfo::sniffed, “The domain read from its first bytes, if any” |
ffi/src/proxy.rs → Proxy::connections (Mobile library) |
The router reads the recorded name back as well. CompiledRoutes::decide_tracked (supervisor/src/topology/router.rs) makes the decision route_target made at open again, from the destination, the sniffed name, the source and the inbound tag the tracker kept, so Supervisor::close_rerouted judges an IP-addressed flow by its sniffed name, as the route table did when the flow opened.
A UDP sub-link’s FlowMeta is built from a flow made by Flow::toward, so its sniffed is always None. Tracking flows, stats and speed limits covers the tracker.
The destination is not rewritten
Section titled “The destination is not rewritten”After routing, AppConnector::connect hands the unchanged flow to target.connect_stream(flow), and the outbound dials flow.destination: still the IP the client asked for. No outbound reads sniffed. The sniffed name changes which rule matches, never where the bytes go. The end-to-end tests of both products rely on this: the only route to the direct outbound (protocol freedom) is a domain_suffix rule for sniffed.example, a name that does not resolve, and the echo server they reach listens on 127.0.0.1.
Flow::toward starts clean
Section titled “Flow::toward starts clean”Flow::toward copies the user and source to a new destination and sets sniffed: None. It is used wherever one flow fans out to others:
| Caller | New flow | Why a clean sniffed is right |
|---|---|---|
Demux, on New |
A mux sub-flow | The carrier’s value says nothing about the sub-flow. The sub-flow’s own value is set from its New payload right after. |
TrojanCore, UDP |
The association’s first packet | A UDP flow is not sniffed. |
supervisor/src/topology/outbound/udp_fanout.rs → FanOutLink::poll_send_to |
One flow per datagram, to route it on the plane current when it is sent and, for a new sub-link, to open and record it | Each packet has its own destination, and a name recovered for one target must not route packets to another. |
AppConnector::connect turns every UDP flow into a FanOutLink, which routes each packet as self.flow.toward(to.clone()). That is why a sniffed value on a UDP mux sub-flow is never read, and why a UDP packet addressed to an IP matches only non-domain rules. etemenanki-app and katana both use FanOutLink. Outbounds, UDP fan-out and balancers covers the fan-out.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
| Sniffing never fails a connection. | Every sniffer returns Option, and every exit from the sniffing state goes through the core’s open path. |
non_tls_and_malformed_input_yield_nothing (protocols/tests/unit/sniff/tls.rs), an_unsniffable_payload_falls_through_to_the_default (app/tests/integration/e2e_sniff.rs) |
| The parsers cannot panic or read out of bounds. | checked_add, slice::get and u16_at; the crate’s deny(clippy::indexing_slicing, clippy::arithmetic_side_effects, clippy::unwrap_used, clippy::expect_used). |
non_tls_and_malformed_input_yield_nothing, a_truncated_client_hello_yields_nothing_rather_than_garbage |
| A truncated ClientHello yields the real SNI or nothing. | Every length is checked against the bytes present; a short read ends in None. |
a_truncated_client_hello_yields_nothing_rather_than_garbage (cuts at 1, 5, 10, 40 and 60 bytes) |
| A request split across reads is re-examined as a whole, and every byte is kept. | Collector::push re-runs sniff over the whole buffer. |
a_host_split_across_pushes_is_found_once_complete, sniff_prefix_finds_a_host_across_pushes_and_keeps_the_bytes (both split inside the header name) |
No more than SNIFF_LIMIT bytes are collected for sniffing. |
SniffPrefix::push takes min(len, remaining()); collect_prefix reads at most remaining(). |
sniff_prefix_takes_no_more_than_its_budget (protocols/tests/unit/core/mod.rs), the_budget_ends_the_search_without_a_match |
No flow waits longer than SNIFF_TIMEOUT for a name. |
Timing::enter(Phase::Sniff) arms the deadline and touch never extends it; timeout_at against one fixed deadline in SOCKS. |
timing_reports_handshake_and_sniff_expiry_to_the_core, a_sniffing_passthrough_core_opens_on_the_sniff_deadline, sniff_deadline_opens_with_what_was_collected (protocols/tests/unit/trojan/core.rs), a_client_silent_through_the_sniff_window_gets_one_reply_then_the_upstream (protocols/tests/unit/socks/server.rs) |
| A flow that names a domain never waits for a sniff window. | worth_sniffing is checked before entering the phase. |
a_domain_target_is_never_sniffed, a_sniffing_passthrough_core_with_a_domain_target_opens_at_once |
| Collected bytes reach the outbound in order, ahead of later payload. | Effect::ForwardHeld is pushed right after Effect::Open; the runtime’s held-buffer rule. |
held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites (concepts/tests/runtime.rs), new_server_vs_new_client_tcp (protocols/tests/pipeline/socks.rs) |
| An IP literal is never a sniffed name. | plausible_domain rejects anything that parses as IpAddr. |
domain_plausibility, an_ip_literal_sni_is_rejected, an_ip_host_is_rejected |
Bytes that merely contain Host: are not HTTP. |
request_target requires a listed method and an HTTP/ version. |
bytes_that_merely_contain_a_host_header_are_not_http |
| An early-answer server answers once. | open(flow, false, fx) after the early answer, so Connected stages nothing; SOCKS writes its grant either before collecting or after the connect, never both. |
connect_to_an_ip_with_sniffing_replies_early_and_holds_the_prefix (protocols/tests/unit/http/core.rs), sniffing_an_ip_target_answers_early_and_opens_with_the_host (protocols/tests/unit/hysteria/server/inbound.rs), a_client_silent_through_the_sniff_window_gets_one_reply_then_the_upstream, new_server_lets_the_upstream_speak_first_while_sniffing |
| After an early grant, a failed dial is reported as the close. | if !granted guards write_refusal. |
a_client_silent_through_the_sniff_window_sees_a_failed_dial_as_the_close |
sniffing = false (katana: disable_sniffing = true) stops the inspection itself. |
The flag gates entry into Phase::Sniff (in SOCKS, the granted path), so the flow is opened as soon as the request is parsed and no sniff window is armed. |
turning_sniffing_off_stops_the_domain_rule_matching and katana’s disable_sniffing_stops_the_domain_rule_matching check the outcome (the domain rule no longer matches); no test observes that the wait is gone. |
| The sniffed name only adds a domain to match. | Domains::any in the route model; outbounds dial flow.destination. |
a_sniffed_domain_makes_an_ip_target_match_domain_rules, a_sniffed_domain_feeds_geosite_too (environment/tests/unit/routing.rs), a_tcp_connection_becomes_a_stream (protocols/tests/pipeline/tun.rs) |
Failure paths and cancellation
Section titled “Failure paths and cancellation”- Unrecognised or malformed bytes. The collector answers
Moreuntil the budget or the window ends. The flow then opens withsniffed: None, and the collected bytes are forwarded unchanged. - Deadline.
Event::DeadlineinPhase::Sniffmaps toExpired::Sniff, and the core opens the flow. The handshake deadline no longer applies once the request is parsed, becauseenterreplaced it. - Client EOF while sniffing. The sans-I/O cores handle
Event::TransportEofin the sniffing state by opening the flow first and then callingPassthrough::on_transport_eof. VMess does the same when the uplink’s terminator chunk (ChunkStep::End) arrives while it is sniffing. The outbound is still dialled, receives what was collected, and then sees the half-close. Legacy Shadowsocks has no terminator:protocols/src/ss_aead.rs→RecordStep::Datadocuments that a zero-length record “carries nothing and ends nothing”, andan_empty_chunk_is_skippedpins it. In SOCKS a zero-byte read or a read error endscollect_prefixearly, and the connect goes ahead with what was read. - Connect failure after an early answer. See the caution above.
HttpCorelogshttp: connect failed: <error>atdebug. The SOCKS driver returns the connector’s error, whichserve_connection(supervisor/src/serve.rs) logs atdebugassocks connection from Some(<client IP>) ended: <error>; the source is printed withDebug. Without an early answer, each protocol reports a failed connect as it normally does. - A SOCKS
CONNECTanswered with a datagram link.connectfails withUnsupportedand the textsocks: a CONNECT was answered with a datagram link. - Staging failure.
fx.stage(...).ok_or_else(staging_full)?returnsstaging room below the core's declared reserve, which the runtime reports asproxy core: staging room below the core's declared reserve. It cannot happen while the core’sSTAGING_RESERVEcovers the early answer. - Cancellation. Sniffing owns no task, channel or lock. In a sans-I/O core the collected bytes live in the core and are dropped with it. In SOCKS,
collect_prefixruns inline in the connection’s task, so dropping theservefuture drops the in-flighttimeout_atread and theCollector.
Limits
Section titled “Limits”| Name | Value | Where | Meaning |
|---|---|---|---|
SNIFF_TIMEOUT |
300 ms | protocols/src/sniff/mod.rs |
Longest wait for a recognisable prefix, from entering the phase. |
SNIFF_LIMIT |
4096 bytes | protocols/src/sniff/mod.rs |
Most bytes inspected and held per flow, across frames. |
MAX_DOMAIN_LEN |
253 | protocols/src/sniff/mod.rs |
Longest accepted name, after trimming trailing dots. |
AFTER_RANDOM |
38 | protocols/src/sniff/tls.rs |
Offset of legacy_session_id inside the handshake body. |
HANDSHAKE_TIMEOUT |
10 s | protocols/src/core/mod.rs |
Applies before sniffing, while the request is parsed. |
RELAY_IDLE_TIMEOUT |
300 s | protocols/src/core/mod.rs |
Armed just before the Open is pushed. |
HttpCore::STAGING_RESERVE |
256 bytes | protocols/src/http/core.rs |
Room for the early 200. |
Hy2StreamCore::STAGING_RESERVE |
2048 bytes | protocols/src/hysteria/server/inbound.rs |
Room for the early TCPResponse with the longest padding. |
MAX_SESSIONS |
256 | protocols/src/mux/demux.rs |
A New beyond it is declined, and so not sniffed. |
Behaviour worth knowing when you change these:
- A flow whose first message is complete but carries no name (a ClientHello without SNI, an HTTP request without
Host) waits the fullSNIFF_TIMEOUT, because neither sniffer can answer “definitely not” and the collector keeps asking for more. The same wait applies to server-speaks-first protocols and to any other client-first protocol that sends less thanSNIFF_LIMITbytes before it waits for an answer. Turning sniffing off, or letting the client send a domain, removes the wait. - A mux sub-flow has no sniff window: it is sniffed only from its
Newframe’s payload. - An SNI that lies outside the first TLS record is not found, and a
Hostvalue cut by a read boundary is kept as cut.
Run cargo test -p etemenanki-protocols sniff for the parsers and the collector, and the whole crate for the cores. The app end-to-end tests (app/tests/integration/e2e_sniff.rs) and katana’s (tests/integration/sniff.rs) drive a real Xray client that app/tests/support/mod.rs and katana’s tests/support/mod.rs build with go build from the Xray-core reference tree; when Go is missing or the build fails they print a SKIP: … line and return early, passing.
| File | Tests | What they pin |
|---|---|---|
protocols/tests/unit/sniff/mod.rs |
domain_plausibility |
Trailing dot, empty, ., a space, 254 characters, IPv4 and IPv6 literals. |
protocols/tests/unit/sniff/collector.rs |
a_host_split_across_pushes_is_found_once_complete, the_budget_ends_the_search_without_a_match, a_new_collector_owns_no_memory, pushing_nothing_reserves_nothing, the_first_bytes_reserve_the_whole_budget_and_filling_it_never_moves_it |
More then Found across pushes with the full prefix kept; Exhausted at exactly SNIFF_LIMIT; no allocation before the first bytes, one allocation of the whole budget after them. |
protocols/tests/unit/sniff/tls.rs |
extracts_sni_from_a_real_client_hello, a_truncated_client_hello_yields_nothing_rather_than_garbage, an_ip_literal_sni_is_rejected, non_tls_and_malformed_input_yield_nothing, hand_built_and_real_hellos_agree |
The parser against a ClientHello produced by OpenSSL, truncations at several cuts, a hand-built hello with an IP SNI, and lengths that run past the buffer. |
protocols/tests/unit/sniff/http.rs |
extracts_the_host_header, host_header_port_and_case_are_normalised_away, absolute_form_authority_wins_over_the_host_header, userinfo_is_stripped_from_an_absolute_target, bytes_that_merely_contain_a_host_header_are_not_http, an_ip_host_is_rejected, a_request_with_no_host_at_all_yields_nothing, a_binary_body_does_not_defeat_header_parsing |
Every rule of the HTTP parser. |
protocols/tests/unit/core/mod.rs |
timing_reports_handshake_and_sniff_expiry_to_the_core, sniff_prefix_finds_a_host_across_pushes_and_keeps_the_bytes, sniff_prefix_takes_no_more_than_its_budget, 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 |
The Phase::Sniff deadline, the SniffPrefix budget and clear, and the exact effect order SetDeadline(RELAY_IDLE_TIMEOUT), Open, ForwardHeld. |
protocols/tests/unit/http/core.rs |
connect_to_an_ip_with_sniffing_replies_early_and_holds_the_prefix |
The early 200, the sniff window, and no second 200 on Connected. |
protocols/tests/unit/hysteria/server/inbound.rs |
sniffing_an_ip_target_answers_early_and_opens_with_the_host |
The early “Connected” TCPResponse and no second response. |
protocols/tests/unit/trojan/core.rs |
sniffing_an_ip_target_holds_the_prefix_until_a_host_is_found, sniff_deadline_opens_with_what_was_collected, a_domain_target_is_never_sniffed |
Entry condition, deadline, effect sequence, and the prefix dropped at the next byte event. |
protocols/tests/unit/vless/core.rs, vmess/core.rs, ss_legacy/core.rs, ss_2022/core.rs |
sniffing_holds_the_prefix_then_opens_with_the_domain, sniffing_reads_chunks_until_a_host_appears, sniffing_an_ip_target_waits_for_a_recognisable_prefix, sniffing_reads_records_until_a_host_appears |
Collection across plaintext events, encrypted chunks and records. |
protocols/tests/unit/ss_legacy/core.rs |
an_empty_chunk_is_skipped |
A zero-length chunk is an empty record, not the end of the uplink. |
protocols/tests/unit/socks/server.rs |
a_client_silent_through_the_sniff_window_gets_one_reply_then_the_upstream, a_client_silent_through_the_sniff_window_sees_a_failed_dial_as_the_close, the_sniffed_prefix_reaches_an_upstream_that_buffers |
With paused time: one grant, then an upstream banner after the window, and nothing but the client’s own bytes upstream; a failed dial after the grant closes with no refusal; the collected prefix reaches an upstream that holds writes until a flush. |
protocols/tests/unit/sss/core.rs |
an_ip_destination_is_sniffed_when_asked |
sss’s core collects the payload after the header, opens with a sniffed name and forwards the held prefix. |
protocols/tests/unit/anytls/core.rs |
sniffing_reads_only_the_data_that_came_with_the_address |
Only the data in the event that completed the address is sniffed; later data and domain destinations get no name. |
protocols/tests/pipeline/socks.rs |
new_server_vs_new_client_tcp, new_server_refuses_an_unreachable_target_after_trying, new_server_lets_the_upstream_speak_first_while_sniffing |
With sniffing on and an IP target, 100 000 bytes round-trip intact; with sniffing off, the refusal reaches the client; a greeting server’s banner follows exactly one 10-byte reply. |
protocols/tests/pipeline/tun.rs |
a_tcp_connection_becomes_a_stream |
A TUN TCP flow to an IP carries sniffed = example.com from its Host header, and the request bytes reach the outbound unchanged. |
concepts/tests/runtime.rs |
held_bytes_are_forwarded_after_the_dial_and_survive_later_rewrites, a_held_range_past_the_buffer_is_rejected |
The runtime side of the held-buffer rule. |
environment/tests/unit/routing.rs |
a_sniffed_domain_makes_an_ip_target_match_domain_rules, a_sniffed_domain_feeds_geosite_too, every_outcome_counts_the_domain_rules_a_sniff_could_still_reach |
Domain and geosite matchers consult the sniffed name; every_outcome counts the domain rules a sniffed name could still reach. |
app/tests/integration/e2e_sniff.rs |
an_http_host_routes_an_ip_addressed_flow, a_tls_sni_routes_an_ip_addressed_flow, a_flow_whose_sniffed_host_does_not_match_is_blocked, an_unsniffable_payload_falls_through_to_the_default, turning_sniffing_off_stops_the_domain_rule_matching |
End to end through a VLESS inbound: only a rule written in domains leads to freedom, so bytes coming back prove the sniffed name routed the flow. |
katana tests/integration/sniff.rs |
a_sniffed_host_reaches_a_domain_rule, disable_sniffing_stops_the_domain_rule_matching |
The same proof through a katana VMess node served by a fake panel, with disable_sniffing false and true. |
Demux’s sniffing of the New payload and the reset in Flow::toward have no dedicated test, and no supervisor test sets sniff: true. A change to any of these should come with one.