Skip to content

Routing

Source files: 57 · checked against Etemenanki 46c12e4 · katana v6.1.0
  • Etemenanki/environment/Cargo.toml
  • Etemenanki/environment/src/lib.rs
  • Etemenanki/environment/src/routing.rs
  • Etemenanki/environment/src/routing/dat.rs
  • Etemenanki/environment/tests/unit/routing.rs
  • Etemenanki/concepts/src/net.rs
  • Etemenanki/concepts/src/sniff.rs
  • Etemenanki/protocols/src/flow.rs
  • Etemenanki/protocols/src/sniff/mod.rs
  • Etemenanki/protocols/src/anytls/core.rs
  • Etemenanki/protocols/src/transports/reality.rs
  • Etemenanki/protocols/src/sss/server.rs
  • Etemenanki/supervisor/src/topology/router.rs
  • Etemenanki/supervisor/src/topology/spec_plan/route.rs
  • Etemenanki/supervisor/src/topology/spec_plan/inbound.rs
  • Etemenanki/supervisor/src/topology/spec_plan/plan.rs
  • Etemenanki/supervisor/src/topology/plane.rs
  • Etemenanki/supervisor/src/topology/flow.rs
  • Etemenanki/supervisor/src/topology/outbound/udp_fanout.rs
  • Etemenanki/supervisor/src/topology/outbound/dns.rs
  • Etemenanki/supervisor/src/topology/outbound/mod.rs
  • Etemenanki/supervisor/src/topology/outbound/freedom.rs
  • Etemenanki/supervisor/src/connector.rs
  • Etemenanki/supervisor/src/serve.rs
  • Etemenanki/supervisor/src/build/route.rs
  • Etemenanki/supervisor/src/build/validate.rs
  • Etemenanki/supervisor/src/build/apply.rs
  • Etemenanki/supervisor/src/supervisor.rs
  • Etemenanki/supervisor/tests/unit/router.rs
  • Etemenanki/supervisor/tests/unit/plane.rs
  • Etemenanki/supervisor/tests/unit/plan.rs
  • Etemenanki/supervisor/tests/unit/validate.rs
  • Etemenanki/app/src/config.rs
  • Etemenanki/app/src/lower.rs
  • Etemenanki/app/src/subscribe.rs
  • Etemenanki/app/src/instance.rs
  • Etemenanki/app/src/main.rs
  • Etemenanki/app/tests/unit/config.rs
  • Etemenanki/app/tests/unit/lower.rs
  • Etemenanki/app/tests/support/mod.rs
  • Etemenanki/app/tests/integration/e2e_route_context.rs
  • Etemenanki/app/tests/integration/e2e_sniff.rs
  • Etemenanki/app/tests/integration/e2e_udp_route.rs
  • katana/src/config.rs
  • katana/src/lower/mod.rs
  • katana/src/lower/route.rs
  • katana/src/lower/outbound.rs
  • katana/src/rule.rs
  • katana/src/runtime.rs
  • katana/src/main.rs
  • katana/src/manager/node.rs
  • katana/src/api/mod.rs
  • katana/src/api/newv2board.rs
  • katana/tests/unit/lower/spec.rs
  • katana/tests/unit/e2e.rs
  • katana/tests/support/mod.rs
  • katana/tests/integration/sniff.rs

The route model decides which outbound a flow leaves by. It lives in etemenanki-environment (version 3.2.1 in environment/Cargo.toml at the pinned revision) as the module etemenanki_environment::routing, in environment/src/routing.rs with a private .dat reader in environment/src/routing/dat.rs: the matchers, an ordered first-match table, the geosite and geoip loaders, and two parsers. The module knows no config format and is generic over what a rule outputs.

Only the supervisor builds and queries a table. supervisor/src/topology/router.rs → CompiledRoutes wraps a routing::Router<Decision>, and supervisor/src/build/route.rs → compile_routes builds it from the spec’s RouteSpec. The front ends depend on etemenanki-environment directly and use its types and parsers, but never build a table: etemenanki-app (app/src/lower.rs → lower_route) and katana (src/lower/route.rs → lower_route) lower their TOML rules into RouteMatch values inside that spec with parse_port_match and parse_domain_regexes, and katana puts its audit rules in front (src/rule.rs → audit_routes).

Read this page before you add a matcher, change how a domain is compared, touch the geodata loader, change the context the supervisor hands the table, or change how a front end lowers its rules. The plane that holds the compiled table and routes each flow on it is on The plane: routing each flow. The operator’s view of the same rules is in Etemenanki routing and katana routing.

The module does four things:

  • Matching. RouteTable::pick walks an ordered list of rules and returns the output of the first rule that has at least one matching matcher, or the default output. RouteTable::every_outcome walks the same list to check a condition on every output a target may still reach once a domain is sniffed from its payload.
  • Geodata loading. build_geo_data reads v2ray/Xray geoip.dat and geosite.dat files (protobuf) from disk entry by entry, checks all of each file, and builds sets only for the codes the rules reference. A file is never held in memory whole.
  • Parsing. parse_port_match and parse_domain_regexes turn config strings into validated matchers, so a front end refuses bad input while it lowers its rules.
  • Composition. Router bundles a table with the GeoData its rules reference.

It leaves the following to its callers:

Not here Where it is
The config format. The module never sees TOML; each front end maps its own rule struct to RouteMatch values. app app/src/lower.rs → lower_route, katana src/lower/route.rs → lower_route
Resolving outbound tags. RouteTable is generic over its output and stores Arc<Out>. The supervisor’s table outputs a Decision that names a slot, and the plane fills each slot with an outbound or balancer target. supervisor/src/topology/router.rs → CompiledRoutes, supervisor/src/topology/plane.rs → Plane
Checking that every tag a rule names exists. supervisor/src/build/validate.rs → validate
DNS. A domain target is matched by name only. It is never resolved, so a cidr or geoip rule never sees the address a domain will dial. The supervisor’s port-53 interception happens in Plane::route, before the table is asked. the outbounds that dial the flow (Outbounds, UDP fan-out and balancers); Plane::route (Name resolution and the DNS service)
Sniffing. The module accepts a sniffed domain but never inspects a payload. the protocols crate (Sniffing)
UDP fan-out. The module routes one target at a time; routing an association packet by packet is the caller’s job. supervisor/src/topology/outbound/udp_fanout.rs → FanOutLink
Deciding whether an apply compiles a new table, and publishing it. the planner and Actor::prepare / Actor::commit (Planning and applying a change)

pick is a pure function of the target, the table and the geodata. The module performs no I/O apart from reading the two .dat files inside build_geo_data, through the reader in routing/dat.rs, spawns no task, takes no lock of its own and has no async code. It inherits the crate-wide lint gate from environment/src/lib.rs: #![deny(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing, clippy::arithmetic_side_effects)], relaxed only under cfg(test). That gate is why the module uses checked_sub, saturating_sub, get and try_from where a plain index or subtraction would be shorter.

environment/src/routing.rs
#[derive(Debug, Clone, Copy)]
pub enum Remote<'a> {
IpAddr(IpAddr),
Domain(&'a str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetNetwork {
Tcp,
Udp,
}

Remote is a borrowed view of the destination host. It is a type of its own rather than etemenanki_concepts::net::Remote (which owns a CompactString), so the route model takes no position on a caller’s network types and a target can be built without cloning a name. The supervisor converts its flow’s destination in route_target.

environment/src/routing.rs
#[derive(Debug, Clone, Copy)]
pub struct RouteTarget<'a> {
pub remote: Remote<'a>,
pub port: u16,
pub network: Option<TargetNetwork>,
pub source: Option<IpAddr>,
pub sniffed_domain: Option<&'a str>,
pub inbound_tag: Option<&'a str>,
}
impl<'a> RouteTarget<'a> {
pub fn new(remote: Remote<'a>, port: u16) -> Self;
pub fn with_network(mut self, network: TargetNetwork) -> Self;
pub fn with_source(mut self, source: IpAddr) -> Self;
pub fn with_sniffed_domain(mut self, domain: &'a str) -> Self;
pub fn with_inbound_tag(mut self, tag: &'a str) -> Self;
}

remote and port are what every request has; new sets the four Option fields to None, and each with_* builder sets one of them. RouteTarget is Copy because every field is, so it is passed by value on the hot path. The fields are public, but the code comment asks callers to use new and the builders rather than a struct literal, so that adding a field later does not break a caller’s code.

Field Read by When it is None
remote every domain matcher (when it is a Domain), Cidr and GeoIp (when it is an IpAddr) never; always set
port PortRange never; always set
network Network a Network matcher does not match
source SourceCidr a SourceCidr matcher does not match
sniffed_domain every domain matcher, including GeoSite and DomainRegex only remote is tried
inbound_tag InboundTag an InboundTag matcher does not match

The rule that holds the model together: a matcher whose field was not supplied does not match. The module never guesses a network, a source or a domain. The cost is that an unsupplied field turns a rule into one that silently never fires, which is why the supervisor supplies every field it has (see route_target) and the app has end-to-end tests proving that each context field reaches the table.

environment/src/routing.rs
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RouteMatch {
GeoSite(CompactString),
DomainSuffix(CompactString),
DomainKeyword(CompactString),
DomainFull(CompactString),
DomainRegex(DomainRegexSet),
GeoIp(CompactString),
Cidr(IpCidr),
SourceCidr(IpCidr),
PortRange(u16, u16),
Network(TargetNetwork),
InboundTag(CompactString),
}

The private function matches(m, target, domains, geo) evaluates one variant. Each variant reads only the part of the target it is about; the domain matchers read both the request domain and the sniffed domain, lowercased once per pick (see Domain normalisation):

Variant Reads Matches when
DomainSuffix(parent) request and sniffed domain either domain is parent or a subdomain of it, on a label boundary (Suffix matching)
DomainKeyword(needle) request and sniffed domain either domain contains needle as a substring
DomainFull(name) request and sniffed domain either domain equals name
DomainRegex(set) request and sniffed domain any pattern of set matches either domain; patterns are unanchored unless they anchor themselves
GeoSite(code) request and sniffed domain the DomainSet loaded under code matches either domain
Cidr(c) remote, only when it is an IP c.contains(&ip)
GeoIp(code) remote, only when it is an IP the CidrSet loaded under code matches the IP
SourceCidr(c) source source is set and c.contains(&source)
PortRange(lo, hi) port port >= lo && port <= hi, inclusive at both ends
Network(want) network network == Some(want)
InboundTag(tag) inbound_tag inbound_tag is set and equals tag

RouteMatch must be PartialEq + Eq because the supervisor’s RouteSpec, which holds the lowered matchers, derives both (The spec: desired state).

A rule’s domain regexes are one matcher, not one matcher per pattern:

environment/src/routing.rs
#[derive(Debug, Clone)]
pub struct DomainRegexSet(RegexSets);
impl DomainRegexSet {
pub fn new<S: AsRef<str>>(patterns: &[S]) -> io::Result<Self>;
pub fn patterns(&self) -> impl Iterator<Item = &str>;
}
impl PartialEq for DomainRegexSet { /* self.patterns().eq(other.patterns()) */ }
impl Eq for DomainRegexSet {}
// Private.
#[derive(Debug, Clone)]
struct RegexSets(Vec<regex::RegexSet>);
impl RegexSets {
fn new<S: AsRef<str>>(patterns: &[S]) -> Result<Self, regex::Error>;
fn with_size_limit<S: AsRef<str>>(patterns: &[S], size_limit: Option<usize>)
-> Result<Self, regex::Error>;
fn compile<S: AsRef<str>>(
patterns: &[S],
size_limit: Option<usize>,
sets: &mut Vec<regex::RegexSet>,
) -> Result<(), regex::Error>;
fn is_match(&self, d: &str) -> bool;
fn patterns(&self) -> impl Iterator<Item = &str>;
}

Why sets. A regex::RegexSet searches a domain once however many patterns it holds, where one Regex per pattern would search it once per pattern. The same private RegexSets type holds a rule’s domain_regex patterns and all the regex entries of one geosite code.

Why more than one set. The regex engine bounds the compiled size of a set by the size of all its patterns together. The limit is the regex crate’s default: 10 MiB, which its error prints as 10485760 bytes (regex 1.13.1 in Cargo.lock). A list whose every pattern fits alone may therefore not fit as one set. RegexSets::compile handles this:

  1. It builds regex::RegexSetBuilder::new(patterns), with size_limit(limit) when one was given.
  2. On success it appends the set to sets.
  3. On regex::Error::CompiledTooBig with more than one pattern, it splits the list at patterns.len() / 2 and compiles the first half, then the second, recursively.
  4. Any other error, or CompiledTooBig for a single pattern, is returned.

Halves are compiled left first, so the sets keep the patterns in their original order, and patterns() (a flat_map over each set’s patterns()) returns them as they were written. is_match is true when any set matches. new is with_size_limit(patterns, None); with_size_limit exists so the unit test can force a split without depending on the default’s value.

Errors. DomainRegexSet::new calls RegexSets::new. Only when that fails does it compile the patterns one by one with regex::Regex::new, to name the first one at fault; the success path never pays for it. The error is io::ErrorKind::InvalidInput with one of two messages:

Case Message
A pattern fails on its own (syntax, or too big alone) invalid domain regex {p:?}: {e}, naming the first such pattern, for example invalid domain regex "(unclosed": regex parse error: followed by the regex crate’s multi-line explanation, or invalid domain regex "^[a-z]{150000}0$": Compiled regex exceeds size limit of 10485760 bytes.
Every pattern compiles alone but the set does not domain regex set of {n} patterns: {e}

The code comment gives the reason for validating here: an unvalidated pattern would become a rule that never matches, which looks exactly like a rule that is never hit.

Equality. RegexSet implements neither PartialEq nor Eq, so equality is defined on the source patterns: two sets are equal when they hold the same patterns in the same order, however the engine split them. The same patterns in another order compare unequal. patterns() is the only accessor; the compiled sets stay private, so a DomainRegexSet can only come from new, and compilation always happens while a spec is lowered, never while matching.

A DomainRegexSet built from an empty list holds one empty set and matches nothing. The app adds no matcher for an empty domain_regex list, and katana’s audit groups always hold at least one pattern, so neither front end builds one.

environment/src/routing.rs
pub struct RouteItem<Out> {
pub matchers: SmallVec<[RouteMatch; 3]>,
pub output: Arc<Out>,
}
pub struct RouteTable<Out> {
pub routes: Vec<RouteItem<Out>>,
pub default: Arc<Out>,
}
impl<Out> RouteTable<Out> {
pub fn pick(&self, target: RouteTarget<'_>, geo: &GeoData) -> Arc<Out>;
pub fn every_outcome(
&self,
target: RouteTarget<'_>,
geo: &GeoData,
may_sniff: bool,
f: impl FnMut(&Out) -> bool,
) -> bool;
}

A RouteItem is one rule: an OR over its matchers. Up to three matchers sit inline in the SmallVec; a longer rule spills to the heap. Outputs are Arc<Out>, so pick returns a reference-count clone, and one output can serve several rules and the default. Neither type derives anything, and no bound is placed on Out. every_outcome is described in every_outcome and the TUN IPv6 screen.

environment/src/routing.rs
pub struct Router<Outbound> {
table: RouteTable<Outbound>,
geo: GeoData,
}
impl<Outbound> Router<Outbound> {
pub fn new(table: RouteTable<Outbound>, geo: GeoData) -> Self;
pub fn route(&self, target: RouteTarget<'_>) -> Arc<Outbound>;
pub fn every_outcome(
&self,
target: RouteTarget<'_>,
may_sniff: bool,
f: impl FnMut(&Outbound) -> bool,
) -> bool;
pub fn default_outbound(&self) -> Arc<Outbound>;
}

route is self.table.pick(target, &self.geo), and every_outcome is self.table.every_outcome(target, &self.geo, may_sniff, f). default_outbound returns a clone of the table’s default; no crate calls it at the pinned revisions. The one Router in use is the supervisor’s routing::Router<Decision> inside CompiledRoutes (CompiledRoutes and Decision).

environment/src/routing.rs
#[derive(Default)]
pub struct GeoData {
pub domain: HashMap<CompactString, DomainSet>,
pub ip: HashMap<CompactString, CidrSet>,
}
pub struct DomainSet {
matchers: Vec<DomainMatcher>,
}
enum DomainMatcher {
Substr(String),
Regex(RegexSets),
Domain(String),
Full(String),
}
pub struct CidrSet {
cidrs: Vec<IpCidr>,
reverse: bool,
}

Both maps are keyed by the raw matcher string exactly as the rule wrote it, such as "cn", "google@ads" or "!cn". RouteMatch::GeoSite(raw) and RouteMatch::GeoIp(raw) look themselves up by the same string.

The two maps are pub, so a caller can insert, remove or move entries. DomainSet and CidrSet have private fields and private matches functions, though, so no code outside the module can build one: every set comes from build_geo_data. The unit tests build sets directly only because they are compiled inside the module (Tests). A caller can also pass GeoData::default(), as CompiledRoutes::single does. A code that is referenced but absent from the map, which only happens when a caller builds RouteMatch values without passing them through build_geo_data, never matches.

DomainSet::matches is an OR over its matchers. A set holds at most one DomainMatcher::Regex, which carries every regex entry of the code in one RegexSets. CidrSet::matches is self.cidrs.iter().any(|c| c.contains(&ip)) ^ self.reverse, so a reversed set matches every address outside the entry.

The protobuf messages are public structs deriving Clone, PartialEq, prost::Message, and they are deliberately minimal. Fields a message does not declare are skipped at every level, so extra fields in newer .dat files are ignored.

Message Field Tag Type
GeoIpList entry 1 repeated GeoIp
GeoIp code 1 string
cidr 2 repeated Cidr
Cidr ip 1 bytes, 4 or 16 of them
prefix 2 uint32
GeoSiteList entry 1 repeated GeoSite
GeoSite code 1 string
domain 2 repeated Domain
Domain type (r#type) 1 int32
value 2 string
attribute 3 repeated Attribute
Attribute key 1 string; the attribute’s value is not declared

The loader decodes only the records with prost: Cidr for geoip, and Domain with its Attributes for geosite. The two outer levels, GeoIpList with GeoIp and GeoSiteList with GeoSite, are parsed by hand in routing/dat.rs (The streaming reader). Those four structs stay public and describe the layout that reader walks. Outside the unit tests, nothing in the workspace or in katana uses them; the tests decode a whole GeoSiteList or GeoIpList with them as the reference the streaming load is compared with (Tests).

The message GeoIp and the variant RouteMatch::GeoIp share a name but are unrelated types.

environment/src/routing.rs
pub fn parse_port_match(s: &str) -> io::Result<RouteMatch>;
pub fn parse_domain_regexes<S: AsRef<str>>(patterns: &[S]) -> io::Result<RouteMatch>;

parse_port_match accepts "80" or "1000-2000":

  • It splits on the first - and trims whitespace on each side, so " 1000 - 2000 " is accepted; a single port is trimmed too.
  • Each bound must parse as a u16. "70000", "nope", "" and "-80" fail with invalid port spec: "70000" and so on: the input is quoted with {:?}.
  • A lower bound above the upper bound fails with invalid port spec: "2000-1000" has a lower bound above its upper bound. The code comment gives the reason: an inverted range would compile into a rule that can never match, which is indistinguishable from a rule that is never hit.
  • A single port p becomes PortRange(p, p), and "80-80" is accepted as the same thing.

All its errors are io::ErrorKind::InvalidInput. parse_domain_regexes is DomainRegexSet::new(patterns).map(RouteMatch::DomainRegex): the counterpart of parse_port_match for a rule’s whole list of regexes. The app passes a &Vec<String>, katana a &Vec<&str>.

flowchart TD
  start(["pick(target, geo)"]) --> fold["Domains::of(target): lowercase the request and sniffed domains once"]
  fold --> next{"another rule in routes?"}
  next -- "no" --> def(["return default.clone()"])
  next -- "yes, rule i" --> any{"any matcher of rule i matches?"}
  any -- "yes, stop at the first" --> out(["return routes[i].output.clone()"])
  any -- "no" --> next

Three properties follow directly from the loop in RouteTable::pick:

  1. The first rule wins. The loop returns on the first hit, so rule order is the only priority. A broad rule placed early shadows every later rule.
  2. Any matcher within a rule. item.matchers.iter().any(...) makes a rule an OR of its matchers, and the model has no conjunction. A rule with domain_suffix and port matches a flow that satisfies either one, not both.
  3. The default is the fallback. When no rule matches, pick returns self.default.clone(). It cannot fail and never returns “no route”.

A rule with an empty matchers list never matches, because any over nothing is false. Both front ends accept such a rule, and it is inert: a rule with only outbound = "blackhole" passes --test in etemenanki-app, and one with only outbound = "block" passes it in katana. A catch-all belongs in default.

pick lowercases the target’s domains once per call, through a private helper:

environment/src/routing.rs
struct Domains {
request: Option<String>,
sniffed: Option<String>,
}

Domains::of sets request to d.to_ascii_lowercase() when remote is Remote::Domain(d) and to None for an IP, and sets sniffed to the lowercased sniffed_domain. Every domain matcher then goes through Domains::any, which tries request first and sniffed second. The code comment gives the reason for folding once: the per-matcher fold it replaced allocated a fresh String for every domain rule the walk passed, on every routing decision.

Only the target side is folded here. The rule side must already be lowercase:

  • etemenanki-app lowercases domain_suffix, domain_keyword and domain_full with to_ascii_lowercase while it lowers the rule; katana lowercases domain_suffix, the only plain domain key it has.
  • DomainSetBuilder::push lowercases every geosite value before building its matcher.
  • A RouteMatch::DomainSuffix built by hand with an uppercase letter never matches anything.

The fold is ASCII only: to_ascii_lowercase leaves every non-ASCII byte as it is.

sniffed_domain carries a name recovered from the payload, a TLS SNI or an HTTP Host, when the request itself named only an IP. Every domain matcher, including GeoSite and DomainRegex, tries it as well as the request domain. This is the only way a rule written in domains can match a flow addressed by IP. Cidr and GeoIp ignore the sniffed domain and read remote only, so an IP-addressed flow is still matched by its address.

The name comes from Flow::sniffed (protocols/src/flow.rs), an Option<SniffedBehavior> whose domain is a CompactString (concepts/src/sniff.rs). A flow is sniffed only when its inbound’s spec sets sniff (supervisor/src/topology/spec_plan/inbound.rs) and worth_sniffing (protocols/src/sniff/mod.rs) holds, that is when the destination is a bare IP: a destination that already names a domain routes by that name, so waiting for the payload would buy nothing. route_target passes s.domain.as_str() to with_sniffed_domain.

The name is normalised before it reaches the table. Both sniffers pass the host they find through protocols/src/sniff/mod.rs → plausible_domain, which trims trailing dots and then rejects:

  • an empty name, or one longer than 253 bytes (MAX_DOMAIN_LEN, the longest legal DNS name);
  • a name with a character other than an ASCII letter, a digit, -, . or _;
  • an IP literal. The code 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.

A rejected name is not used as a sniffed domain. The same module bounds the inspection with SNIFF_TIMEOUT (300 ms) for the client’s first payload and SNIFF_LIMIT (4 KiB) across however many frames it arrives in. How the payload is inspected is covered in Sniffing.

An AnyTLS stream does not wait for its first payload. One AnyTLS session carries many streams, and protocols/src/anytls/core.rs → open_tcp routes each one the moment its address is whole, so only the bytes that arrived with the address are inspected. The code comment gives the reason: holding the session’s uplink for one stream’s sniff would stall the others. See AnyTLS.

A UDP packet is never routed with a sniffed domain. The fan-out routes each packet as flow.toward(destination), and Flow::toward sets sniffed to None, so a domain rule matches a UDP packet only when the packet itself is addressed by name.

DomainSuffix and geosite’s type-2 (Domain) entries share one allocation-free helper:

environment/src/routing.rs
fn is_subdomain_of(d: &str, parent: &str) -> bool {
match d.len().checked_sub(parent.len()) {
Some(0) => d == parent,
Some(n) => d.ends_with(parent) && d.as_bytes().get(n.saturating_sub(1)) == Some(&b'.'),
None => false,
}
}

When d is longer than parent, it must end with parent and the byte immediately before the suffix must be .: a label-boundary check. It replaced ends_with(&format!(".{parent}")), which allocated on every call. checked_sub and get keep it inside the crate’s no-panic lint gate.

d parent Result Why
example.com example.com match same length and equal
mail.example.com example.com match ends with it, preceded by .
notexample.com example.com no match preceded by t, not a label boundary
example.com.example.net example.com no match does not end with it
com example.com no match shorter than parent
a.example.com .example.com no match the byte before .example.com is a

The last row matters to config authors. A suffix written with a leading dot, such as domain_suffix = [".example.com"], matches neither example.com nor a.example.com: neither front end strips the dot, and is_subdomain_of compares it as part of the suffix.

  • Cidr and GeoIp match only when remote is an IP. A domain target returns false before any set is consulted, so a negated GeoIp("!code") does not match a domain target either. IpCidr::contains (the cidr crate, 0.3.2) decides membership.
  • SourceCidr reads source, never remote. A target without a source leaves the rule inert, even when its destination falls inside the range.
  • PortRange is inclusive at both ends.
  • Network compares against Option<TargetNetwork> and InboundTag against Option<&str>, so both are inert until the caller supplies the field. The supervisor supplies the inbound tag for every flow, and the network for DialNetwork::Tcp and DialNetwork::Udp; a flow whose destination network is DialNetwork::Unknown or DialNetwork::Unix (concepts/src/net.rs) has none.

DomainRegex(set) calls RegexSets::is_match on each lowercased domain, request first. One evaluation therefore costs one search per compiled set per domain: usually one set, and two domains at most. RegexSet::is_match answers whether some pattern matches, not which one; the route model needs only the yes or no.

environment/src/routing.rs
pub fn build_geo_data(
geoip_path: Option<&Path>,
geosite_path: Option<&Path>,
geosite_refs: &[CompactString],
geoip_refs: &[CompactString],
) -> io::Result<GeoData>;

The caller collects every geosite and geoip string its rules use and passes them as geosite_refs and geoip_refs; compile_routes does this in rule order, duplicates included. Geosite is handled first, then geoip, so a spec whose references of both kinds fail reports the geosite error. For each kind:

  1. If the reference list is empty, the file is not opened, even when a path is configured. An etemenanki-app config that names a missing geoip file but uses no geoip matcher passes --test.
  2. Otherwise the path must be configured, or the call fails with a geosite matcher is used but no geosite file is configured (or the geoip equivalent), io::ErrorKind::InvalidInput.
  3. load_geo_sets reads the file once, from disk, through the streaming reader, and builds each raw reference from the first entry in file order whose code matches. A repeated raw string is built once, and a later entry with a code already used is checked but never merged in.
    • geosite: code@attr is split on the first @. The entry is found by code with eq_ignore_ascii_case. A leading ! has no meaning here: "!cn" is looked up literally and fails as not found.
    • geoip: a leading ! sets reverse and is stripped. The entry is found by the remaining code, ignoring ASCII case.
  4. A failure to read the file, or malformed data anywhere in it, fails first: InvalidData, geosite decode: … or geoip decode: … (The streaming reader). Only after the whole file has been read are the references taken, in order:
    • A reference whose code no entry has is NotFound, geosite code not found: {code} or geoip code not found: {code}. The geosite code is shown without its @attr, the geoip code without its !.
    • A reference whose set could not be built fails with that set’s error (Geosite entries, Geoip entries). That error is kept for its reference and does not stop the walk, so malformed data later in the file still fails first.
  5. The reader belongs to the walk and is dropped when the walk ends, the geosite file’s before the geoip file is opened. Only the sets for referenced codes stay in memory.

Codes are looked up case-insensitively, but the map key is the raw string. "cn" and "CN" in two rules resolve to the same entry and are built twice, under two keys.

Decoding is strict about wire types. A geoip.dat configured as the geosite file fails with geosite decode: failed to decode Protobuf message: Domain.r#type: invalid wire type: LengthDelimited (expected Varint) instead of loading as wrong data, and a geosite.dat configured as the geoip file fails with geoip decode: failed to decode Protobuf message: Cidr.ip: invalid wire type: Varint (expected LengthDelimited). The two files share their list and entry layout, so the mix-up shows at the first record, and the field path in the message starts at the record type.

environment/src/routing/dat.rs
pub(super) fn for_each_entry<M: Message + Default>(
path: &Path,
what: &'static str,
visit: impl FnMut(&str, &mut Entry<'_, M>) -> io::Result<()>,
) -> io::Result<()>;
impl<M: Message> Entry<'_, M> {
pub(super) fn records(&self) -> usize;
pub(super) fn replay(&mut self, f: impl FnMut(&M)) -> io::Result<()>;
}
environment/src/routing.rs
fn load_geo_sets<M: prost::Message + Default, S>(
path: &Path,
what: &'static str,
refs: &[CompactString],
code_of: fn(&str) -> &str,
build: impl FnMut(&str, &str, &mut dat::Entry<'_, M>) -> io::Result<io::Result<S>>,
) -> io::Result<HashMap<CompactString, S>>;

Both files are one protobuf list: field 1 repeats the entries, and each entry is a code (field 1, a string) and repeated records (field 2, a Cidr or a Domain). for_each_entry opens the file with File::open, takes its length from the file’s metadata, and reads it through a 64 KiB BufReader. The module comment gives the reason for streaming: a route table names a handful of codes out of hundreds, and decoding the whole list would hold all of them at once, far more memory than a packet tunnel on a phone may use.

The list and entry levels are parsed by hand, to the rules prost applies:

  • A key is a varint of at most 10 bytes. Its wire type must be 0 to 5, and its tag must not be 0.
  • The list’s field 1 and an entry’s fields 1 and 2 must be length-delimited, and each length must fit inside the entry, or the file, that holds the field.
  • A code must be UTF-8. When an entry writes its code more than once, the last one counts, wherever it stands among the records.
  • Any other field is skipped by its wire type, groups included. Groups may nest as deep as prost allows, 100 levels counted from the list; deeper fails with recursion limit reached. A length-delimited field is skipped with BufReader::seek_relative, without being read into memory.

Each record goes to prost. scan_entry decodes every record of every entry with Message::merge into one value it clears and reuses, and counts them. Malformed data anywhere in the file therefore fails the load, in an entry no rule names as much as in one a rule does. Only once an entry has been checked whole does visit get its code and an Entry, which knows how many records the entry has (records) and can read it again (replay): replay seeks back to the entry’s start and decodes its records a second time, handing each to f.

load_geo_sets supplies the visit for both kinds. For each reference not yet built whose code (code_of: the part before @, or after a leading !) matches the entry’s code ignoring ASCII case, it calls build with the reference, the entry’s code as the file spells it, and the entry. The closures in build_geo_data make a set builder sized from records() and feed it through replay. An entry no reference names is therefore decoded once, and an entry that references name is decoded once more for each distinct raw string naming it: cn and !cn decode the geoip CN entry three times in all. build returns two layers of Result. An inner error is the set’s own, such as a bad CIDR or regex entries that do not compile, and is kept for its reference while the walk goes on; an outer error is the file’s and stops the walk.

Errors of the hand-parsed levels are worded as prost words them, behind the kind, and carry no field path: geoip decode: failed to decode Protobuf message: buffer underflow for a file cut short, and likewise invalid varint, invalid wire type: Varint (expected LengthDelimited) or recursion limit reached. A record prost refuses gives prost’s own text, whose field path starts at the record type (Cidr. or Domain.). Both are InvalidData. A read that fails for another reason is returned as the I/O error it is.

While it walks a file, the loader holds the 64 KiB read buffer, a byte buffer as large as the largest code or record read so far, one decoded record, the current entry’s code, and the sets built so far. Nothing of an entry no reference names outlives the record being checked. The geosite sets, built first, stay in memory while the geoip file is walked.

environment/src/routing.rs
fn geosite_ref(raw: &str) -> (&str, Option<&str>);
struct DomainSetBuilder<'a> {
attr: Option<&'a str>,
matchers: Vec<DomainMatcher>,
regexes: Vec<String>,
}
impl<'a> DomainSetBuilder<'a> {
fn new(attr: Option<&'a str>, records: usize) -> Self;
fn push(&mut self, dom: &Domain);
fn finish(self, code: &str) -> io::Result<DomainSet>;
}
fn geosite_regex_set(code: &str, patterns: Vec<String>) -> io::Result<RegexSets>;

geosite_ref splits code@attr into the code and the attribute. new reserves one matcher per record of the entry, the most the entry can give. replay hands push the entry’s domains in file order. With an attribute, push first skips every domain that carries no Attribute whose key equals it, ignoring ASCII case. It then lowercases the value and sorts it by Domain.type:

type Becomes Matches when
0 DomainMatcher::Substr the domain contains the value
1 collected for the code’s one DomainMatcher::Regex the compiled set matches the domain
2 DomainMatcher::Domain is_subdomain_of(domain, value)
3 DomainMatcher::Full the domain equals the value
any other nothing the entry is skipped with the warning skipping unknown geosite domain type {other}

finish gets the entry’s code as the file spells it. When at least one regex was collected, geosite_regex_set(code, regexes) compiles them and the result is pushed as the set’s last matcher. Its rule is that an invalid entry is skipped, as it was when every entry was compiled on its own, and that a valid entry is never lost with it:

  1. It tries RegexSets::new on all the entries at once. This already splits a list that is too big for one set.
  2. Only if that fails does it check the entries one by one with regex::Regex::new, dropping each that fails with the warning skipping invalid geosite regex {p:?}: {e}.
  3. It compiles what is left with RegexSets::new. If that still fails, the code fails with InvalidData, geosite {code}: regex entries: {e}, where {code} is spelled as in the file.

Last, when the set holds fewer than half the matchers it reserved room for, as it may for an @attr reference, finish shrinks the vector to fit.

Both warnings are tracing::warn! with target etemenanki_environment::routing. The regex warning carries the regex crate’s multi-line explanation. One bad line in a community list does not take the whole code down, and because the check runs per referenced string, a code referenced as "ads" and as "ADS" logs its warnings twice.

environment/src/routing.rs
fn geoip_ref(raw: &str) -> (bool, &str);
struct CidrSetBuilder {
cidrs: Vec<IpCidr>,
error: Option<io::Error>,
}
impl CidrSetBuilder {
fn new(records: usize) -> Self;
fn push(&mut self, c: &Cidr);
fn finish(self, reverse: bool) -> io::Result<CidrSet>;
}
fn ip_cidr(c: &Cidr) -> io::Result<IpCidr>;

geoip_ref strips a leading ! and reports whether there was one, which becomes reverse. new reserves one CIDR per record of the entry. Geoip entries are hard errors, not warnings: push converts each record with ip_cidr and keeps the first error, ignoring the records after it, and finish returns that error instead of a set. The checks, all InvalidData:

Check Message as --test prints it after building route failed:
The IP is 4 or 16 bytes geoip cidr: ip must be 4 or 16 bytes, got 5
The prefix fits a u8 geoip cidr: prefix too large
IpCidr::new accepts the pair: the prefix is not longer than the address geoip cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)
IpCidr::new accepts the pair: no host bit is set geoip cidr: host part of address was not zero

Only the entries a reference names are converted. In any other entry a record only has to decode, so a CIDR there that would fail these checks does not fail the load.

The geoip cidr: bad ipv4 length and geoip cidr: bad ipv6 length branches convert a slice whose length was checked on the line before, so they cannot be reached; they exist to satisfy the lint gate.

flowchart TB
  appcfg["etemenanki-app: [route], or subscribe route groups"] --> la["app lower_route"]
  katcfg["katana: [node.route]"] --> lk["katana lower_route"]
  audit["node audit rules"] --> ar["rule::audit_routes"]
  la --> spec["RouteSpec"]
  lk --> spec
  ar -- "spliced in front" --> spec
  spec --> val["validate: every tag is an outbound or balancer"]
  val --> comp["compile_routes, in Actor::prepare"]
  comp --> geo["build_geo_data"]
  geo --> cr["CompiledRoutes::new"]
  cr --> plane["Plane::new: one target per slot"]

Lowering a route and validating it read no file; katana’s lowering only stamps the geo files it names (katana). A front end refuses what its own syntax gets wrong (a bad port, CIDR, network or regex), the supervisor’s validation refuses what the typed spec gets wrong (a tag nothing carries), and only the build step reads the geo files.

supervisor/src/topology/spec_plan/route.rs
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteSpec {
pub rules: Vec<RouteRuleSpec>,
pub default: CompactString,
pub geoip: Option<PathBuf>,
pub geosite: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteRuleSpec {
pub matchers: Vec<RouteMatch>,
pub outbound: CompactString,
}

Rules are tried in order; the first with any matcher that matches wins, and a flow no rule matches takes default. outbound and default name an outbound or a balancer tag: the two share one namespace. geoip and geosite are the paths compile_routes passes to build_geo_data. etemenanki-app copies them from its config as written, and File::open in routing/dat.rs receives them unchanged, so a relative path resolves against the process’s working directory, not the directory of the config file. katana keeps its paths as written too, inside the stamped form described under katana. The rest of the spec is on The spec: desired state.

Each front end lowers a rule’s keys into matchers in a fixed order, the order of the table below. Because a rule is an OR, the order inside one rule changes only which matcher short-circuits first, not the result.

Config key RouteMatch Lowered with etemenanki-app [[route.rule]] katana [[node.route.rule]]
domain_suffix DomainSuffix, one per value to_ascii_lowercase yes yes
domain_keyword DomainKeyword, one per value to_ascii_lowercase yes no
domain_full DomainFull, one per value to_ascii_lowercase yes no
domain_regex one DomainRegex for the whole list routing::parse_domain_regexes yes no
cidr Cidr, one per value str::parse::<IpCidr> yes yes
source_cidr SourceCidr, one per value str::parse::<IpCidr> yes no
inbound_tag InboundTag, one per value as written yes no
network one Network parse_network: "tcp" or "udp" only yes no
port PortRange, one per value routing::parse_port_match yes yes
geosite GeoSite, one per value as written yes yes
geoip GeoIp, one per value as written yes yes

The rows follow the order of app/src/lower.rs → lower_route; katana’s lower_route pushes domain_suffix, cidr, port, geosite and geoip, in that order. katana’s audit rules add DomainRegex matchers of their own, one per audit rule id.

Consequences of the lowering:

  • cidr and source_cidr values go through the cidr crate, which rejects set host bits: "192.0.2.1/24" fails with invalid cidr "192.0.2.1/24": host part of address was not zero, and "nope" with invalid cidr "nope": couldn't parse address in network: invalid IP address syntax. A value without a prefix, such as "192.0.2.1", parses as a single host (/32, or /128 for IPv6).
  • network is one string, not a list, so a rule can require at most one transport; "tcp,udp" fails with invalid rule network "tcp,udp" (expected "tcp" or "udp"). parse_network compares exactly, so "TCP" fails the same way: invalid rule network "TCP" (expected "tcp" or "udp").
  • RouteConfig and RuleConfig carry #[serde(deny_unknown_fields)] in both front ends, so a misspelled key, or a key katana does not have such as domain_keyword, fails the TOML parse instead of being ignored: for example configuration invalid: TOML parse error at line <n>, column <m> in the app.
app/src/lower.rs
fn lower_route(cfg: &RouteConfig, first_outbound: CompactString) -> io::Result<RouteSpec>;

lower calls lower_route after the DNS, outbounds and balancers are lowered, and hands it the tag of the first outbound as the default; a config with no outbound at all fails earlier with config defines no outbounds. [route].default overrides it. Every error lower_route raises is an io::ErrorKind::InvalidInput from parse_port_match, parse_domain_regexes, parse_cidr or parse_network, returned unwrapped.

Two steps in config::effective run before lowering and change what the route names:

  • Built-in tags. Without a subscribe file, subscribe::ensure_builtins(&mut cfg, false) appends a freedom outbound tagged direct, or a blackhole outbound tagged blackhole, when [route].default or a rule names that tag and no outbound or balancer carries it. In this mode whatever already carries the tag counts, whatever its protocol, because the config wrote both the tag and the routes naming it. So default = "direct" passes --test without a direct outbound, even in a config that defines no [[outbound]]: the built-in is then the first outbound. block is not a built-in tag in etemenanki-app.
  • Subscribe files. With [subscribe], subscribe::apply replaces the config’s [[route.rule]]s with rules built from the subscribe file’s [[route_group]]s, top to bottom. When the config had rules of its own it logs, at WARN with target etemenanki_app::subscribe, [subscribe] is set, so the config's <n> [[route.rule]] entries are ignored; routing comes from the route groups in <file>, where <file> is the subscribe path or the subscribe file. A [subscribe.routes] default pick overrides [route] default. push_group_rules turns each group into one rule carrying its non-network matchers when it has any (has_matchers), plus one rule per distinct network value, all toward the tag the group resolves to; [route]’s geoip and geosite still apply. Then ensure_builtins runs in strict mode, because the provider wrote these routes: an existing outbound tagged direct must be freedom or direct, one tagged blackhole must be blackhole or block, and a balancer may carry neither tag. Otherwise the config fails with, for example, subscribe: "direct" is routed to, but the outbound tagged "direct" is "blackhole", not "freedom" or subscribe: "direct" is routed to, but it names a balancer, not a "freedom" outbound. The code comment gives the reason: traffic meant to go direct must not quietly leave through a proxy that happens to be tagged direct.

Both are on etemenanki-app: from TOML to a spec and Subscribe files.

src/lower/route.rs
pub fn lower_route(route: &RouteConfig) -> io::Result<RouteSpec>;

katana’s lower_route lowers [node.route] the same way with its five keys. The default is direct unless [node.route].default says otherwise. The tags a rule may name come from src/lower/outbound.rs → lower_outbounds, which starts every node’s outbound list with four built-ins, all with drain: None:

Tag OutboundProtocolSpec
direct Freedom { address_family: AddressFamilyStrategy::Auto }
block Blackhole
freedom Freedom { address_family: AddressFamilyStrategy::Auto }
blackhole Blackhole

freedom and blackhole are the Xray aliases of the first two. Each [[outbound]] follows. A configured outbound that reuses a built-in tag, repeats a tag, or starts with the reserved prefix audit# is refused with duplicate/reserved outbound tag {tag}.

The geo file paths are where katana differs. katana 6.1.0 builds against etemenanki-supervisor 2.1, a later release than the one this page documents, whose RouteSpec holds each geo file as a RouteFile instead of the plain path above. lower_route wraps [node.route] geoip and geosite in RouteFile::stat, which keeps the path as written and stamps it with the file found there when the route is lowered. A file replaced at the same path therefore changes the lowered spec. Every panel poll lowers the node’s spec and applies it when it differs from the running one, so the next poll after the replacement rebuilds the route from the new file.

src/lower/mod.rs → shared_spec puts the node’s audit rules in front of its route table:

src/lower/mod.rs
let (audit_outbounds, audit_rules) = rule::audit_routes(audit);
let mut outbounds = outbound::lower_outbounds(globals)?;
outbounds.extend(audit_outbounds);
// ...
let mut route = route::lower_route(&cfg.route)?;
route.rules.splice(0..0, audit_rules);

The audit rules arrive as src/api/mod.rs → DetectRule { id: i64, pattern: regex::Regex }: the panel clients, and the reader of the local rule-list file, have already compiled each pattern once and dropped, with a WARN, the ones that fail (invalid block rule … from the newV2board client, invalid local rule … for the file). src/rule.rs → audit_routes groups the node’s audit rules by rule id, in the order the ids first appear, and reads each pattern’s source text back with pattern.as_str(). Each group becomes:

  • one parse_domain_regexes matcher over the group’s patterns;
  • one RouteRuleSpec with that single matcher, toward audit_tag(id), which is AUDIT_TAG_PREFIX ("audit#") followed by the id;
  • one Blackhole outbound with that tag and drain: None.

A group whose set does not compile is logged at WARN as audit rule {id} skipped: {e} and left out; since every pattern was compiled once already, this is the only failure left at lowering. Because the audit routes come first, a flow to an audited name goes to its blackhole whatever the node’s own rules say. They also shift the rule numbers: RuleId is a rule’s position in the spliced RouteSpec::rules, so a node’s own first rule is rule N, where N is the number of audit groups that compiled.

RuleManager::update replaces a node’s rule list only when an id or a pattern’s source text differs, position by position, because Regex has no Eq. A flow routed to an audit#<id> outbound ends at that blackhole; katana records no audit hit and reports none to a panel. The rest of the audit is on Destination audit.

test_spec, the spec that katana --test checks and that the runtime checks before it builds a node or applies a reload that changes one, carries no audit rules. For most node types it is shared_spec without an inbound. For a node whose node_type is Hysteria 2 (on newV2board, where such a node’s settings are local), it also lowers the inbound from [node.hysteria] with one placeholder user (a port of 0 becomes 1), so the check builds the listener as a start would. A helium node names no node_type, because its panel describes the protocol, so it gets shared_spec without an inbound like any other node. Lowering in full, including the users, is on Lowering a node into a spec.

supervisor/src/build/validate.rs → validate checks that every rule’s outbound and the default name a tag that is an outbound or a balancer. It walks the rules in order and then the default, and reports the first tag that is neither, as ApplyError::UnknownReference { from: Resource::Route, kind: ResourceKind::Outbound, tag }, which prints as route references unknown outbound {tag}, even where a balancer was meant. The planner validates before it plans, so such a spec is refused without a plan and nothing that runs is touched (an_invalid_spec_is_refused_without_a_plan). The lowering never checks tags itself (semantic_problems_are_left_to_the_supervisor in app/tests/unit/lower.rs). The rest of validation is on Validation and apply errors.

supervisor/src/build/route.rs
pub(crate) fn compile_routes(spec: &RouteSpec) -> io::Result<CompiledRoutes>;

compile_routes:

  1. walks every matcher of every rule and collects each RouteMatch::GeoSite(code) and RouteMatch::GeoIp(code) into two Vec<CompactString>, in rule order, duplicates included;
  2. calls build_geo_data(spec.geoip.as_deref(), spec.geosite.as_deref(), &geosite, &geoip);
  3. hands the rules as (matchers.clone(), outbound.clone()) pairs, the default and the geo data to CompiledRoutes::new.

Actor::prepare (supervisor/src/supervisor.rs) calls it for the plan’s Step::Build(Resource::Route) step and wraps an error as ApplyError::Build { resource: Resource::Route, source }, which prints as building route failed: {e}. The apply is then refused as a whole and the running plane stays published. check, the dry run behind etemenanki-app --test and katana’s node checks, runs compile_routes on the spec it checks, so --test reports the geo errors listed under Failure paths and cancellation. A route change alone builds only the route table and republishes the plane; every outbound, the DNS resolver and every inbound are reused (a_route_change_alone_rebuilds_only_the_route_table).

supervisor/src/topology/router.rs
pub struct CompiledRoutes {
table: routing::Router<Decision>,
targets: Vec<CompactString>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Decision {
pub slot: usize,
pub rule: Option<RuleId>,
}
impl CompiledRoutes {
pub fn new(
rules: impl IntoIterator<Item = (Vec<routing::RouteMatch>, CompactString)>,
default: CompactString,
geo: GeoData,
) -> Self;
pub fn single(tag: CompactString) -> Self;
pub fn targets(&self) -> &[CompactString];
pub fn decide(&self, flow: &Flow, ctx: &FlowContext) -> Decision;
pub fn decide_tracked(&self, flow: &FlowEntry) -> Decision;
pub fn every_outcome(
&self,
destination: &Destination,
ctx: &FlowContext,
may_sniff: bool,
f: impl FnMut(Decision) -> bool,
) -> bool;
}

The supervisor’s table outputs a Decision, never an outbound. Each distinct tag a rule or the default names gets one slot, numbered in order of first mention (the default’s tag last, if no rule named it), and targets() lists the tag of each slot. new numbers the slots with a local HashMap<CompactString, usize>: its slot_of closure calls entry(tag).or_insert_with_key, which pushes the tag onto targets and returns its index the first time a tag is seen, and returns the stored index after that. The module comment gives the reason for slots: a table free of outbounds lets an outbound be rebuilt without recompiling the table, which would mean reading the geo data again, and lets one compiled table be reused while outbounds change.

Each rule becomes one RouteItem whose output is its own Arc<Decision>, with its tag’s slot and rule: Some(RuleId::new(index)), where the index is the rule’s position in RouteSpec::rules converted with u32::try_from(at).expect("fewer than 2^32 rules"). Rules that share a tag share the slot but keep separate decisions, so a flow always says which rule sent it; the tracker files that rule with the flow. The default is Decision { slot, rule: None }. single(tag) is new([], tag, GeoData::default()), the table Plane::empty routes everything with. decide builds the target with route_target, calls Router::route and copies the Decision out of the returned Arc. decide_tracked makes the same decision for a live flow from what the tracker kept of it (FlowEntry: the requested destination, the sniffed domain, the source route_target would have used and the inbound tag), so a flow opened on an earlier plane can be asked where the current table sends it. every_outcome builds a target for a TCP flow to destination, with no sniffed domain and ctx.source as its source, and calls Router::every_outcome, handing f each Decision by value.

Plane::new takes one Arc<Target> per entry of targets(), in slot order, built by the same apply: Actor::commit maps each tag to its current target. Plane::new checks the lengths with debug_assert_eq!(routes.targets().len(), targets.len()), and Plane::route_upstream indexes self.targets[decision.slot], relying on that invariant.

every_rule_naming_a_tag_shares_that_tags_slot pins this for the rules [port 80 → proxy, network udp → direct, port 443 → proxy] with default direct: targets() is ["proxy", "direct"], TCP to port 80 decides the proxy slot with rule 0, TCP to port 443 the proxy slot with rule 2, UDP to port 443 the direct slot with rule 1 (the first matching rule wins), and TCP to port 22 the direct slot with no rule. Its doc comment gives the reason slots are per tag: otherwise the plane would hold two targets for one outbound. The plane: routing each flow covers what the plane does with a decision.

route_target: the context the supervisor supplies

Section titled “route_target: the context the supervisor supplies”
supervisor/src/topology/router.rs
pub fn route_target<'a>(flow: &'a Flow, ctx: &'a FlowContext) -> routing::RouteTarget<'a>;

route_target adapts a supervisor flow (supervisor/src/topology/flow.rs: the protocols crate’s Flow with a Principal, and the FlowContext of the inbound it entered on) to a RouteTarget. It borrows everything and allocates nothing. It delegates to the private target_of(destination, sniffed, source, inbound_tag), which CompiledRoutes::every_outcome also uses for a destination that has no flow yet, and CompiledRoutes::decide_tracked for a flow the tracker holds. It is the one adapter for both front ends, so katana’s flows carry the inbound tag and the network too, although katana’s config has no key that would lower into an InboundTag or Network matcher.

RouteTarget field Taken from
remote flow.destination.remote, as Remote::Domain(&str) or Remote::IpAddr
port flow.destination.port
sniffed_domain flow.sniffed’s domain, when set
inbound_tag ctx.inbound_tag, always
source flow.source.or(ctx.source): the flow’s own source wins over the connection’s client, which is the peer the listener captured at accept (for a connection handed over on a handoff socket, the client named by the PROXY header sent beside it) unless a PROXY protocol v2 header, or on a WebSocket inbound a trusted proxy’s real-IP header, names another
network TargetNetwork::Tcp or Udp from flow.destination.network; nothing for Unknown or Unix

The code comments give the reasons. The source order matters for a listener that serves many peers from one socket, such as a QUIC listener, which knows the peer only per flow. The network is supplied because it costs nothing and withholding it would leave every Network rule permanently inert. The four source tests in supervisor/tests/unit/router.rs pin every combination of the two sources; which accept path sets which one is on The plane: routing each flow.

A compiled table is immutable. Actor::commit keeps it in Actor::routes (an Option<Arc<CompiledRoutes>>) and passes the same Arc to every Plane it publishes over it, so the actor and those planes share one table. Five readers ask it, each through the plane current when it asks:

Reader When The flow and context it routes
AppConnector::connect (supervisor/src/connector.rs) once per TCP flow, after session.admit has admitted it when the connector has a session: a connection’s flow, each mux sub-flow, each Hysteria 2 proxy stream, each AnyTLS stream, each SOCKS CONNECT the flow as the inbound decoded it, with the inbound’s FlowContext, through Plane::route. FlowMeta::of records the matched rule and plane.epoch() beside the outbound that carries the flow.
FanOutLink::poll_send_to (supervisor/src/topology/outbound/udp_fanout.rs) on every send of a datagram on a UDP association self.flow.toward(to), the association’s user and source with the datagram’s destination and no sniffed domain, with the association’s FlowContext, through Plane::route
RoutedDialer::dial (supervisor/src/topology/outbound/dns.rs) once per connection to an upstream DNS server of the split resolver a TCP flow to the server’s IP and port with anonymous_user() and FlowContext { inbound_tag: "dns", source: None } (DNS_FLOW_TAG), through Plane::route_upstream, so a rule can match the resolver’s traffic by the inbound tag dns
The TUN IPv6 screen (supervisor/src/serve.rs → ipv6_unreachable) once per IPv6 TCP connection a TUN client opens, before the device’s stack answers its SYN a TCP target to the IPv6 destination with no sniffed domain, the TUN inbound’s tag and the client as source, through Plane::ipv6_unreachable and CompiledRoutes::every_outcome rather than decide
Supervisor::close_rerouted (supervisor/src/supervisor.rs) when a front end calls it, typically after a route switch every live flow the tracker holds, through Plane::reroutes → CompiledRoutes::decide_tracked; a flow to port 53 goes to the DNS service first when the plane has one, as in Plane::route

A UDP flow passes through connect once, to become a FanOutLink, without reading the plane: an association is never routed as a whole. Two connections an inbound opens on its own never ask the table: a REALITY inbound’s connection to its cover site (protocols/src/transports/reality.rs → RealityServer::dial_dest) and an sss inbound’s fallback (protocols/src/sss/server.rs → Rejection::run). Both are dialed directly from this host, outside the routing plane; see Dialers. Plane::route returns Routed { target: &Arc<Target>, rule }, borrowed from the plane. connect resolves a balancer target with Target::resolve(None); the fan-out calls resolve(prefer), where prefer is the member a sub-link filed under that balancer (Sub::via) already runs on (Sub::id).

With DnsSpec::Split, Plane::route sends every flow to port 53 (DNS_PORT), TCP and UDP alike, to the supervisor’s DNS service with rule: None, before the table is asked. route_upstream skips that check, so the service’s own questions are never sent back to it.

RouteTable::every_outcome(target, geo, may_sniff, f) answers a question pick cannot: whether f holds for every output target may be routed to once a domain sniffed from its payload is known. It walks the rules as pick does, and at the first rule that matches now it returns f of that rule’s output. Before that rule, when may_sniff is set and the target has no sniffed domain yet, each rule with a domain matcher (RouteMatch::reads_domain: GeoSite, DomainSuffix, DomainKeyword, DomainFull or DomainRegex) is a possible outcome too, and f is checked on its output. When no rule matches, the default is the last outcome. The walk stops at the first false. A sniffed domain only ever adds matches, to domain matchers, so the rule that matches now still matches then and nothing after it can be reached; without may_sniff, or with a sniffed domain already set, the result is f of what pick returns.

Its one caller is the TUN inbound’s IPv6 screen. run_tun_inbound hands the TUN inbound the closure supervisor/src/serve.rs → ipv6_unreachable builds, through TunInbound::screening_ipv6. For each IPv6 TCP connection, the closure loads the current plane and calls Plane::ipv6_unreachable(destination, ctx, may_sniff, own), with the inbound’s tag and the client as ctx, may_sniff from TunInbound::sniffs, and own the device’s own addresses:

  • A flow to port 53 is always reachable when the plane has a DNS service, since the service answers it.
  • Otherwise the plane calls CompiledRoutes::every_outcome and checks every slot the flow may reach with Target::lacks_ipv6. Only a direct or WireGuard outbound can be known to lack IPv6: a freedom outbound whose address_family rules IPv6 out, or whose host has no route there (FreedomConnector::lacks_ipv6, which asks the kernel through UdpDialer::source_toward; see Dialers), or a WireGuard outbound whose address_family or tunnel-local addresses rule it out (WgConnector::reaches). A balancer lacks IPv6 when every member does. A proxy outbound is assumed to reach what its protocol can address.

When every outcome lacks IPv6, the screen refuses the connection and the closure logs inbound {tag}: refusing {source} -> {destination}: no route to IPv6 from any egress it may take at debug level. How the device refuses it is on TUN.

Whatever reads the plane after an apply publishes a new one is routed on the new table; whatever does not is not routed again. A client that switched a node calls Supervisor::close_rerouted after the apply to close the live flows the new table sends to another outbound (see Closing what a route change moved). Publishing, epochs, what open flows keep and drains are on The plane: routing each flow; sub-links and balancers per packet on Outbounds, UDP fan-out and balancers; the DNS service and RoutedDialer on Name resolution and the DNS service.

katana adds a policy of its own on top. After an apply commits, the node closes every session with supervisor.close(Selector::All) (src/manager/node.rs → reconcile) when a local rebuild is pending or the panel’s node changed in more than what reaches new connections alone (disruptive_part, which leaves out an AnyTLS padding scheme and a Hysteria 2 node’s rates and UDP idle timeout). A local rebuild is set by an edit to [node.route], to listen_ip, disable_sniffing or the cert table of [node.controller], or to [node.hysteria] (apply_static), and by a change to the global [[outbound]] pool or [dns]. route_change_drops_connections in katana tests/unit/e2e.rs pins the route case as a business requirement. An edit to disable_vmess_clock_check, to real_ip_header or real_ip_from, to the guard keys of [node.controller] (enable_device_limit, ban_max_failures, ban_window_secs, ban_secs, carrier_max_failures), or to handoff_dir or handoff_group resyncs the node at once without a rebuild, so no session is closed for it. A change to the audit rules republishes the plane with the new audit routes and their outbounds, and closes no session. See The node manager.

Invariant Enforced by Pinned by
The first matching rule wins; later rules are not consulted after a hit. the early return in RouteTable::pick first_matching_rule_wins
A rule matches when any one of its matchers matches. item.matchers.iter().any(...) any_matcher_within_a_rule_matches
With no hit, the default is returned. the final self.default.clone() default_fallback_when_no_rule_matches
A matcher whose field was not supplied does not match. Option comparisons and is_some_and in matches source_cidr_matches_the_client_address, network_matches_the_declared_transport, inbound_tag_matches_the_declared_inbound
Domain matchers never match an IP target unless a sniffed domain is supplied. Domains::of yields None for an IP remote domain_matchers_never_match_ip_dests, a_sniffed_domain_makes_an_ip_target_match_domain_rules
Geosite also sees the sniffed domain. GeoSite goes through domains.any a_sniffed_domain_feeds_geosite_too
Cidr and GeoIp never match a domain target. the Remote::Domain(_) => false arms cidr_matches_the_destination_only (covers Cidr only)
Domain comparison ignores ASCII case for lowercase rules. Domains::of folds the target; the front ends fold the rule side domain_matching_is_case_insensitive; app a_server_config_lowers_to_its_spec
A suffix matches only on a label boundary. is_subdomain_of domain_suffix_matches_parents_not_lookalikes
A rule’s regexes are one matcher that matches when any pattern does. parse_domain_regexes, RegexSets::is_match domain_regex_matches_any_of_its_patterns
A pattern list too big for one set still builds, every pattern still matches, and the order is kept. the split in RegexSets::compile regexes_too_big_for_one_set_still_build
An invalid regex fails the rule instead of becoming a dead rule, and the error names it. DomainRegexSet::new, the only constructor invalid_domain_regex_is_rejected
Two regex sets are equal when their patterns are, in order. impl PartialEq for DomainRegexSet domain_regex_equality_is_by_pattern
An invalid geosite regex drops only itself; the code’s valid regexes still match. geosite_regex_set an_invalid_geosite_regex_skips_only_itself
Port ranges are inclusive; an inverted, non-numeric or out-of-range spec is rejected. parse_port_match port_ranges_are_inclusive, port_parser_rejects_an_inverted_range
Before a sniff, every earlier rule a sniffed domain could still make match is an outcome, and nothing after the rule that matches now is. the domain-rule check and the early return in RouteTable::every_outcome every_outcome_counts_the_domain_rules_a_sniff_could_still_reach
An IPv6 TUN connection is refused only when every target it may reach lacks IPv6, and a port-53 flow never is while the DNS service exists. Plane::ipv6_unreachable over CompiledRoutes::every_outcome and Target::lacks_ipv6 ipv6_is_unreachable_only_when_every_possible_target_lacks_it (supervisor/tests/unit/plane.rs)
Rules naming one tag share its slot, and each decision names its own rule. slot_of and one Arc<Decision> per rule in CompiledRoutes::new every_rule_naming_a_tag_shares_that_tags_slot
A live flow is asked about with the inputs it was routed by at open. FlowMeta::of keeps the destination, sniffed domain, flow.source.or(listener_source) and inbound tag; decide_tracked passes them to target_of close_rerouted_closes_only_the_flows_a_route_change_moves (supervisor/tests/hot_swap.rs), where a port rule keeps one live flow on its outbound across a change of the default
A plane holds exactly one target per slot. Actor::commit maps targets() in order; debug_assert_eq! in Plane::new no dedicated test; the assertion runs whenever a debug build publishes a plane
A flow’s own source wins over the listener’s. flow.source.or(ctx.source) in route_target the_circuits_own_source_wins_over_the_listeners, without_one_the_listeners_source_is_used, with_neither_there_is_no_source_to_match_on, a_circuit_source_works_with_no_listener_source
Every rule and the default name an outbound or balancer that exists. validate a_route_rule_must_name_a_known_outbound_or_balancer, the_route_default_must_name_a_known_outbound_or_balancer, a_route_may_name_a_balancer, an_invalid_spec_is_refused_without_a_plan
A route change alone rebuilds only the route table. the planner’s Step::Build(Resource::Route) a_route_change_alone_rebuilds_only_the_route_table
Every context field the app’s config accepts reaches the table. route_target inbound_tag_selects_the_route, source_cidr_matches_the_client_address, network_separates_tcp_from_udp in app/tests/integration/e2e_route_context.rs
A sniffed domain changes the route end to end. route_target passes flow.sniffed app/tests/integration/e2e_sniff.rs, katana tests/integration/sniff.rs
UDP is routed per datagram, not per association. FanOutLink::poll_send_to one_association_routes_each_peer_separately, replies_from_several_peers_merge_back_correctly
katana’s audit routes come first, one blackhole per rule id, and audit# is reserved. shared_spec, audit_routes, lower_outbounds audit_rules_route_first_to_one_blackhole_per_rule_id, an_audit_tag_is_reserved
A reference takes the first entry whose code matches, ignoring ASCII case; a later entry with the same code is not merged in, and an entry’s last code counts. load_geo_sets, scan_entry geo_data_builds_each_ref_from_the_first_entry_with_its_code
A referenced geo code must exist. load_geo_sets a_missing_geo_code_is_not_found
A used geo kind must have a configured, readable file. build_geo_data, for_each_entry no unit test; checked by the --test dry run
Malformed data anywhere in a geo file fails the load, even in an entry no rule names. scan_entry decodes every record malformed_geo_data_fails_even_in_an_unused_entry
The streaming load accepts and refuses what a prost decode of the whole list does, and builds the same sets. routing/dat.rs parses the outer levels to prost’s rules streaming_geo_data_matches_a_whole_decode

Unit tests listed without a file live in environment/tests/unit/routing.rs. That file is compiled into environment/src/routing.rs as mod tests through #[path = "../tests/unit/routing.rs"], so it can reach private items such as RegexSets, DomainSet, DomainMatcher, DomainSetBuilder, CidrSetBuilder and geosite_ref. supervisor/tests/unit/router.rs is included into router.rs the same way.

pick, every_outcome, Router::route and CompiledRoutes::decide are infallible. Every failure happens while a spec is lowered, validated or compiled, and each one in the table below refuses the whole spec. The table lists the texts as --test prints them. etemenanki-app prefixes each with configuration invalid: and exits with status 1; katana prints configuration error: node <id>: followed by the text and exits with status 1. A TOML parse error, such as a misspelled rule key, comes before any node is lowered: its first line is configuration invalid: TOML parse error at line <n>, column <m> in the app and configuration error: config parse error: TOML parse error at line <n>, column <m> in katana.

Stage Condition io::ErrorKind Text
Lowering Port spec is not a u16 or a range of them InvalidInput invalid port spec: "70000"
Lowering Inverted port range InvalidInput invalid port spec: "2000-1000" has a lower bound above its upper bound
Lowering A regex does not compile, or is too big on its own InvalidInput invalid domain regex "(unclosed": regex parse error: (multi-line), invalid domain regex "<pattern>": Compiled regex exceeds size limit of 10485760 bytes.
Lowering Every regex compiles alone but the set does not InvalidInput domain regex set of <n> patterns: <error>
Lowering Bad cidr or source_cidr InvalidInput invalid cidr "192.0.2.1/24": host part of address was not zero
Lowering (app) Bad network InvalidInput invalid rule network "tcp,udp" (expected "tcp" or "udp")
Lowering (app, subscribe) Strict built-in check fails InvalidInput subscribe: "direct" is routed to, but the outbound tagged "direct" is "blackhole", not "freedom"
Lowering (katana) An [[outbound]] takes a built-in, repeated or audit# tag InvalidInput duplicate/reserved outbound tag audit#1
Validation A rule or the default names a tag that is neither an outbound nor a balancer none (ApplyError::UnknownReference) route references unknown outbound nowhere
Build Geosite matcher without a geosite file InvalidInput building route failed: a geosite matcher is used but no geosite file is configured
Build Geoip matcher without a geoip file InvalidInput building route failed: a geoip matcher is used but no geoip file is configured
Build A .dat file cannot be read the read error’s kind building route failed: …
Build A .dat file is malformed anywhere, even in an entry no rule names InvalidData building route failed: geosite decode: failed to decode Protobuf message: … or geoip decode: …
Build Code not in the file NotFound building route failed: geosite code not found: nosuchcode (for nosuchcode@ads), building route failed: geoip code not found: nosuchcode (for !nosuchcode), building route failed: geosite code not found: !cn
Build A geosite code’s regexes still fail after the invalid ones are dropped InvalidData building route failed: geosite <code>: regex entries: <error>
Build Malformed geoip CIDR in an entry a rule names InvalidData building route failed: geoip cidr: … (Geoip entries)

Two geosite problems are logged at WARN (target etemenanki_environment::routing) and skipped rather than refused: skipping unknown geosite domain type <n> and skipping invalid geosite regex "<pattern>": <error>. katana logs an audit rule id whose set does not compile as audit rule <id> skipped: <error> and lowers the node without it.

At run time the same texts appear inside the front end’s own messages:

  • etemenanki-app logs failed to start: <e> and exits when the first spec fails, and reload: <e>; keeping the running config when a reload’s spec fails; the running plane stays published (etemenanki-app: running, reloading and shutting down).
  • katana checks each node’s test_spec before it builds the node and before it applies a reload that changes it or the global outbounds and DNS (Runtime and config reload); the panel-driven applies of a running node are on The node manager.

There is nothing to cancel in the module itself: it spawns nothing and has no futures. A compiled table is never mutated. A connector, a fan-out link, RoutedDialer or the TUN IPv6 screen reads the plane through a load() guard it drops before it returns. An old plane is freed once the cell has been swapped and no guard still holds it. The compiled table inside it lives on while a later plane or Actor::routes still shares its Arc.

Item Value Where
Matchers stored inline per rule 3; more are stored on the heap, with no cap RouteItem::matchers, SmallVec<[RouteMatch; 3]>
Rules per compiled table fewer than 2^32; compiling more panics with fewer than 2^32 rules CompiledRoutes::new, RuleId is a u32
Compiled size of one regex set 10 MiB (10485760 bytes), the regex crate’s default; a longer list is split into several sets, but each pattern must fit alone RegexSets::compile
Regex searches per DomainRegex evaluation one per compiled set, per domain (request and sniffed) RegexSets::is_match
Allocations per pick up to two Strings, the folded request and sniffed domains, made even when the table has no domain rule Domains::of
Rule lookup linear in the number of rules, and linear in the matchers of each geosite set or the CIDRs of each geoip set it reaches pick, DomainSet::matches, CidrSet::matches
Geodata file read from disk once per build_geo_data call through a 64 KiB buffer and never held whole; every record is decoded once, and a referenced entry’s records once more per distinct reference; only referenced sets survive build_geo_data, routing/dat.rs → for_each_entry
Group nesting in a skipped .dat field 100 levels from the list, as in prost routing/dat.rs → LIST_DEPTH, ENTRY_DEPTH
Room in a geodata set one slot per record of the entry; a geosite set that keeps fewer than half is shrunk to fit DomainSetBuilder::new, CidrSetBuilder::new, DomainSetBuilder::finish
Sniffed name at most 253 bytes after trailing dots are trimmed protocols/src/sniff/mod.rs → MAX_DOMAIN_LEN

For UDP, the table is asked on every send of a datagram, so its per-call cost is paid per packet.

Test File Behaviour
any_matcher_within_a_rule_matches environment/tests/unit/routing.rs a rule is an OR of its matchers
first_matching_rule_wins same order is priority
default_fallback_when_no_rule_matches same an empty table returns the default
domain_suffix_matches_parents_not_lookalikes same label-boundary suffix matching
domain_keyword_matches_any_substring same substring matching
domain_full_matches_only_the_exact_name same exact matching
domain_regex_matches_any_of_its_patterns same one regex matcher hits when any of its patterns does
invalid_domain_regex_is_rejected same one bad pattern fails the rule, and the error names it
domain_regex_equality_is_by_pattern same DomainRegexSet equality and patterns() order
regexes_too_big_for_one_set_still_build same four patterns that each fit a size limit alone split into more than one set, keep their order and all match (the limit is found by binary search with min_size_limit)
domain_matching_is_case_insensitive same target domains are folded
domain_matchers_never_match_ip_dests same an IP target has no domain
a_sniffed_domain_makes_an_ip_target_match_domain_rules same the sniffed domain reaches domain rules
a_sniffed_domain_feeds_geosite_too same the sniffed domain reaches geosite
an_invalid_geosite_regex_skips_only_itself same DomainSetBuilder, fed by the test helper domain_set, drops the invalid regex entry and keeps the two valid ones
geo_data_builds_each_ref_from_the_first_entry_with_its_code same from a hand-built geosite.dat and geoip.dat with unknown fields at both levels, records before a code, an entry whose code is written twice and a later entry reusing a code: cn, cn@ads, geo, !cn, private and TEST build from the first entry with their code, the later entry is not merged in, and an entry’s last code counts
a_missing_geo_code_is_not_found same nope@ads and !nope fail as NotFound with geosite code not found: nope and geoip code not found: nope
malformed_geo_data_fails_even_in_an_unused_entry same a record that does not decode in an entry no reference names, and a geoip file one byte short, fail as InvalidData with texts starting geosite decode: failed to decode Protobuf message: and geoip decode: failed to decode Protobuf message:
streaming_geo_data_matches_a_whole_decode same every truncation of each sample file, and up to 14 byte substitutions at every offset, give the same sets, or the same error kind, as a prost decode of the whole GeoSiteList or GeoIpList followed by a lookup of each reference; more than 100 variants must load and more than 100 must fail, so both outcomes are compared
cidr_matches_the_destination_only same Cidr reads IP remotes only
source_cidr_matches_the_client_address same the source is separate from the destination and inert when absent
port_ranges_are_inclusive same inclusive bounds
port_parser_rejects_an_inverted_range same inverted, non-numeric and out-of-range specs are rejected
network_matches_the_declared_transport same the network matcher, inert without context
inbound_tag_matches_the_declared_inbound same the inbound-tag matcher, inert without context
every_outcome_counts_the_domain_rules_a_sniff_could_still_reach same an IP flow before its sniff may reach every earlier domain rule and the rule it matches now, nothing past it; without a sniff to come, or with one done, only the rule it matches; the walk stops at the first false
the_circuits_own_source_wins_over_the_listeners, without_one_the_listeners_source_is_used, with_neither_there_is_no_source_to_match_on, a_circuit_source_works_with_no_listener_source supervisor/tests/unit/router.rs source precedence in route_target
every_rule_naming_a_tag_shares_that_tags_slot supervisor/tests/unit/router.rs slots per tag, decisions per rule
ipv6_is_unreachable_only_when_every_possible_target_lacks_it supervisor/tests/unit/plane.rs with an IPv4-only freedom as default and a domain rule to another target, an IPv6 connection is unreachable without a sniff to come and reachable with one; port 53 is reachable while the DNS service exists; a balancer is unreachable only when every member is
reroutes_compares_where_a_flow_goes_now_with_what_carries_it supervisor/tests/unit/plane.rs a flow on outbound a is rerouted by a plane routing to b, not by a new version of a or a balancer with a among its members; a port-53 flow follows the DNS service when the plane has one
a_route_change_alone_rebuilds_only_the_route_table, an_invalid_spec_is_refused_without_a_plan supervisor/tests/unit/plan.rs what a route change builds; an unknown tag refused before planning
a_route_rule_must_name_a_known_outbound_or_balancer, the_route_default_must_name_a_known_outbound_or_balancer, a_route_may_name_a_balancer supervisor/tests/unit/validate.rs route tag validation
route_rules_accept_every_matcher app/tests/unit/config.rs every matcher key parses into its own field
direct_and_blackhole_exist_when_a_route_names_them, a_plain_configs_own_outbound_keeps_its_builtin_tag app/tests/unit/config.rs built-in direct and blackhole without a subscribe file
a_server_config_lowers_to_its_spec, semantic_problems_are_left_to_the_supervisor app/tests/unit/lower.rs the first outbound is the default, domains are lowercased, kinds keep their order; unknown tags are left to validation
inbound_tag_selects_the_route, source_cidr_matches_the_client_address, network_separates_tcp_from_udp app/tests/integration/e2e_route_context.rs the context matchers work end to end
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 app/tests/integration/e2e_sniff.rs sniffed domains change the route end to end
one_association_routes_each_peer_separately, replies_from_several_peers_merge_back_correctly app/tests/integration/e2e_udp_route.rs per-datagram UDP routing through the app’s own SOCKS inbound, and reply merging
audit_rules_route_first_to_one_blackhole_per_rule_id, an_audit_tag_is_reserved katana tests/unit/lower/spec.rs audit routes spliced first, grouped by rule id (ids 7, 9, 7 give audit#7, audit#9, then the node’s own rule); audit# refused as an outbound tag
route_change_drops_connections katana tests/unit/e2e.rs a [node.route] edit closes the node’s live connections
a_sniffed_host_reaches_a_domain_rule, disable_sniffing_stops_the_domain_rule_matching katana tests/integration/sniff.rs katana’s flows reach a domain rule through the sniffed name

The two sniff suites drive an Xray client, which their support code (app/tests/support/mod.rs, katana tests/support/mod.rs) builds with Go from the Etemenanki/Xray-core source tree. XRAY_BIN is a LazyLock initialised by build_xray, so the build runs once per test binary, for the first test that reaches it. When go is missing or the build fails, that first test prints one SKIP: line (SKIP: `go` not available; skipping xray interop test or SKIP: failed to build xray-core); katana’s copy also prints SKIP: <path> not found; skipping xray interop test when the Xray-core tree is missing. XRAY_BIN is then None, each suite’s run helper returns None through XRAY_BIN.as_ref()?, and every sniff test returns early without asserting, so a green run on a machine without Go or the tree has not exercised them.

The geodata tests build their .dat files field by field with helpers (field, entry, dom, cidr, unknown_fields, geosite_sample, geoip_sample) and write each to the system’s temporary directory as a DatFile, removed when it is dropped. Those files are small and hand-built, so after changing the loader, etemenanki-app --test against real geoip.dat and geosite.dat files is still the check on real data, including code@attr, !code and the missing-code error. The routing unit tests run with cargo test -p etemenanki-environment; see Testing for the rest of the suite.