DNS resolver
Source files: 51 · checked against Etemenanki 46c12e4 · katana v6.0.0
Etemenanki/protocols/src/dns/mod.rsEtemenanki/protocols/src/dns/message.rsEtemenanki/protocols/src/dns/hosts.rsEtemenanki/protocols/src/dns/serve.rsEtemenanki/protocols/src/error.rsEtemenanki/protocols/src/helpers/parse.rsEtemenanki/protocols/src/helpers/address_family.rsEtemenanki/protocols/src/transports/tls/config.rsEtemenanki/protocols/src/transports/tls/platform_roots.rsEtemenanki/protocols/src/transports/connect.rsEtemenanki/protocols/src/transports/reality.rsEtemenanki/protocols/src/hysteria/connector.rsEtemenanki/protocols/src/hysteria/connection.rsEtemenanki/protocols/src/wireguard/config.rsEtemenanki/protocols/src/wireguard/connector.rsEtemenanki/protocols/src/wireguard/device.rsEtemenanki/environment/src/dial/mod.rsEtemenanki/environment/src/dial/socket.rsEtemenanki/environment/src/dial/tcp.rsEtemenanki/environment/src/dial/udp.rsEtemenanki/supervisor/src/build/dns.rsEtemenanki/supervisor/src/build/outbound.rsEtemenanki/supervisor/src/build/inbound.rsEtemenanki/supervisor/src/build/apply.rsEtemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/topology/spec_plan/dns.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/topology/outbound/dns.rsEtemenanki/supervisor/src/topology/outbound/freedom.rsEtemenanki/supervisor/src/topology/plane.rsEtemenanki/supervisor/src/topology/balancer.rsEtemenanki/app/src/config.rsEtemenanki/app/src/lower.rsEtemenanki/app/src/instance.rsEtemenanki/app/src/main.rsEtemenanki/subscribe/src/dns.rsEtemenanki/ffi/src/platform.rsEtemenanki/protocols/tests/unit/dns/mod.rsEtemenanki/protocols/tests/unit/dns/message.rsEtemenanki/protocols/tests/unit/dns/hosts.rsEtemenanki/protocols/tests/unit/dns/serve.rsEtemenanki/protocols/tests/pipeline/dns_secure.rsEtemenanki/protocols/tests/support/mod.rsEtemenanki/supervisor/tests/unit/dns_outbound.rsEtemenanki/app/tests/unit/lower.rsEtemenanki/app/tests/integration/e2e_dns.rsEtemenanki/app/tests/support/mod.rskatana/src/config.rskatana/src/lower/outbound.rskatana/src/runtime.rskatana/src/main.rs
etemenanki_protocols::dns turns a domain name into the addresses an outbound dials, and, on a client, answers the DNS queries applications send. A Resolver puts an optional hosts table and a bounded, TTL-aware cache in front of an ordered list of servers. Each server is one of four backends: the host resolver (getaddrinfo), plain DNS (over UDP, or over TCP when a dialer carries the connection), DNS over TLS (RFC 7858) or DNS over HTTPS (RFC 8484). For the three protocol backends the module carries its own small wire codec. It encodes one A or AAAA question, reads the address records out of the response, and, for the DNS service in serve.rs, reads a client’s question and builds an answer to it.
This page is for contributors who change the resolver, its codec, the hosts table or the DNS service. The module is always compiled; it has no Cargo feature of its own. Which resolver each outbound gets, how the supervisor intercepts port 53, and how the through-proxy resolver’s connections are routed are on Name resolution and the DNS service. The operator view of the app’s [dns] table is the DNS guide page. The subscribe file’s [dns] table is described on Subscribe files, and the user guide’s Subscribe files page describes it for operators.
Responsibilities
Section titled “Responsibilities”| Component | File → symbol | Owns |
|---|---|---|
| Config parsing | dns/mod.rs → Backend::from_spec, Backend::from_url, Backend::https, ServerAddr |
What "udp", "tls", "https" and the udp://, tls://, https:// URL forms mean, and refusing what is missing |
| Construction | dns/mod.rs → Resolver::with_upstreams, Resolver::system, Resolver::new, Resolver::from_spec, Upstream::new |
Refusing servers the resolver could never use, and building each server’s TLS client configuration once |
| Lookups | dns/mod.rs → Resolver::resolve_with_ttl, lookup, query_both |
Literals, hosts entries, the cache, then the servers in order, A and AAAA together |
| Cache | dns/mod.rs → cache, Cached |
A moka cache bounded to CACHE_CAPACITY names, each entry with its own deadline |
| Relaying | dns/mod.rs → Resolver::relay |
Sending a client’s raw query to each server in turn and returning the first response whose id matches |
| Exchanges | dns/mod.rs → exchange, exchange_udp, exchange_framed, exchange_https_over, server_addr |
One message to one server under QUERY_TIMEOUT, over the backend’s transport |
| Hosts table | dns/hosts.rs → Hosts |
Reading the system hosts file into a case-insensitive name map |
| DNS service | dns/serve.rs → Service, Transport |
Deciding what an application’s query gets: a relayed response, an answer built here, or nothing |
| Wire codec | dns/message.rs |
Encoding queries and answers, decoding responses and client queries, from untrusted bytes without panicking |
What it leaves to others:
- Address-family policy. The resolver returns every address it learned.
protocols/src/helpers/address_family.rs→resolve_candidatesanddestination_to_socketaddrsapply the outbound’sAddressFamilyStrategyand the caller’s socket capabilities (see From addresses to dial candidates). - Which resolver a consumer gets.
supervisor/src/build/dns.rs→build_dnsbuilds the resolvers a spec describes, andsupervisor/src/build/outbound.rs→build_outboundhands them out. See Name resolution and the DNS service. - Routing the resolver’s own connections. A resolver built with a
StreamDialeropens every server connection through it. The supervisor’s dialer,RoutedDialer, sends them through the route table; it is described on the supervisor page. - Configuration formats. Front ends read their own files and hand this module strings (
ResolverSpec) or URLs. The module never reads a config file, and it reads a CA only as PEM bytes the caller passes in. - Routing decisions. Route rules match a domain destination as a name (
supervisor/src/topology/router.rs→route_targetpasses it on asrouting::Remote::Domain), and no rule makes the supervisor call the resolver. See The plane: routing each flow.
Key types
Section titled “Key types”Constants
Section titled “Constants”pub const SYSTEM_TTL: Duration = Duration::from_secs(60);pub const MIN_TTL: Duration = Duration::from_secs(5);pub const MAX_TTL: Duration = Duration::from_secs(3600);pub const QUERY_TIMEOUT: Duration = Duration::from_secs(5);const CACHE_CAPACITY: u64 = 8192;const UDP_BUF: usize = 512;const RELAY_UDP_BUF: usize = 65535;The doc comments give the reasons. getaddrinfo reports no TTL, so a fixed, short SYSTEM_TTL bounds how long a moved name keeps resolving to its old address. MIN_TTL stops a zero-TTL answer from defeating the cache, and MAX_TTL stops a very long TTL from pinning a stale address for hours. CACHE_CAPACITY is a bound because the key is attacker-influenced: a client can ask a proxy to reach any name it likes. UDP_BUF is the receive buffer for the resolver’s own queries, which carry no EDNS and ask only for A or AAAA. RELAY_UDP_BUF is the receive buffer for a relayed client query, which may carry EDNS and so draw a response of any size a datagram can hold. The Limits section lists them with the codec constants.
ServerAddr
Section titled “ServerAddr”#[derive(Debug, Clone, PartialEq, Eq)]pub enum ServerAddr { Ip(SocketAddr), Name { host: CompactString, port: u16 },}
impl ServerAddr { pub fn new(host: &str, port: u16) -> Self;}impl From<SocketAddr> for ServerAddr { /* ServerAddr::Ip */ }impl fmt::Display for ServerAddr { /* "<addr>" or "<host>:<port>" */ }Where a DNS server listens. ServerAddr::new returns Ip when host parses as an IpAddr, and Name otherwise. A Name is looked up through the bootstrap resolver, and its cache, on each exchange with that server (see Server names and the bootstrap); a resolver without a bootstrap refuses it when it is built.
Backend
Section titled “Backend”#[derive(Debug, Clone, PartialEq, Eq)]pub enum Backend { System, Udp(ServerAddr), Tls { server: ServerAddr, server_name: CompactString, ca_pem: Option<Vec<u8>>, }, Https { server: ServerAddr, host: CompactString, path: CompactString, ca_pem: Option<Vec<u8>>, },}
impl Backend { pub fn https(server: impl Into<ServerAddr>, url: &str, ca_pem: Option<Vec<u8>>) -> io::Result<Self>; pub fn from_url(url: &str) -> io::Result<Self>; pub fn from_spec(spec: ResolverSpec<'_>) -> io::Result<Self>; fn server(&self) -> Option<&ServerAddr>; // None for System}| Variant | Server | What travels |
|---|---|---|
System |
none | getaddrinfo, through tokio::net::lookup_host |
Udp(server) |
server |
Plain DNS: one datagram each way, or DNS-over-TCP framing when a StreamDialer carries the connection or the UDP response came back truncated |
Tls { .. } |
server |
DNS-over-TCP framing inside TLS, verified against server_name |
Https { .. } |
server |
One RFC 8484 POST inside TLS. host is both the verified name and the Host header; path is the request path. |
Backend derives PartialEq and Eq, so two backends compare by server, TLS name, DoH host and path, and the bytes of any configured CA. The supervisor’s DnsSpec holds Backend values and relies on this equality to decide whether an apply rebuilds the resolvers.
The DoH address is given apart from the URL on purpose. The doc comment explains: taking it from the URL’s host would mean resolving the resolver, which only a resolver with a bootstrap can do.
ResolverSpec and Backend::from_spec
Section titled “ResolverSpec and Backend::from_spec”#[derive(Debug, Default, Clone, Copy)]pub struct ResolverSpec<'a> { pub backend: Option<&'a str>, pub server: Option<&'a str>, pub server_name: Option<&'a str>, pub url: Option<&'a str>, pub ca_pem: Option<&'a [u8]>,}ResolverSpec holds the strings a configuration file carries for one resolver. It is a struct rather than a parameter list, so a backend that needs one more field does not break every consumer’s call site. ca_pem is PEM bytes, not a path: the caller reads the file. from_spec lives in this crate so that "udp" means the same thing, and a missing server is refused the same way, in every front end that uses it.
from_spec matches backend exactly. The match is case-sensitive ("UDP" is an unknown backend), and None means "system".
backend |
Requires | Returns |
|---|---|---|
None or "system" |
nothing | Backend::System |
"udp" |
server |
Backend::Udp(ServerAddr::Ip(addr)) |
"tls" |
server, server_name |
Backend::Tls { server, server_name, ca_pem } |
"https" |
server, url |
Backend::https(server, url, ca_pem) |
| anything else | dns: unknown backend "<name>" (expected "system", "udp", "tls" or "https") |
server is parsed as a SocketAddr ("192.0.2.53:53", "[2001:db8::53]:853"), so it needs an explicit port and is never a host name. A name or a missing port is refused with dns: invalid server address: invalid socket address syntax. from_spec therefore only ever produces ServerAddr::Ip, and the resolver it goes into needs no bootstrap. Every refusal is io::ErrorKind::InvalidInput, and none of them falls back to the host resolver. The doc comment states the rule: an operator who asked for a particular resolver must not silently get a different one. The server_name refusal has its own comment: the name is refused rather than guessed, because verifying a resolver’s certificate against the wrong name is the failure DNS over TLS exists to avoid.
Backend::from_url
Section titled “Backend::from_url”from_url parses a server written as one URL string. Subscribe files write their DNS servers this way (subscribe/src/dns.rs → DnsConfig, whose pre_proxy and through_proxy are arrays of such strings, stored as written).
| Form | Returns | Defaults |
|---|---|---|
system (exactly) |
Backend::System |
|
udp://host[:port] |
Backend::Udp(ServerAddr::new(host, port)) |
port 53 |
tls://host[:port][#name] |
Backend::Tls { server, server_name, ca_pem: None } |
port 853; server_name is the fragment, or else the host (a name) or the IP address as text |
https://host[:port][/path] |
Backend::https(ServerAddr::new(host, port), url, None) |
port 443; path /dns-query |
Unlike from_spec, from_url accepts a host name in every form. The resulting ServerAddr::Name is usable only by a resolver with a bootstrap. ca_pem is always None, so a server read from a URL verifies against the system roots. Scheme matching is case-sensitive. Every refusal is InvalidInput:
| Input | Error |
|---|---|
No :// and not system |
dns: server "<url>": expected "system" or a udp://, tls:// or https:// url |
Another scheme, such as tcp:// |
dns: server "<url>": unknown scheme "tcp" |
udp:// with a # anywhere |
dns: server "<url>": a udp server has no name to verify |
tls://…# with an empty fragment |
dns: server "<url>": empty server name |
udp:// or tls:// authority errors |
dns: server "<url>": has no host, … has an invalid port, … has an unclosed [, … has junk after ] |
https:// URL errors |
as for Backend::https below, without the server "<url>": prefix |
Backend::https and URL splitting
Section titled “Backend::https and URL splitting”Backend::https splits the URL itself instead of pulling in a URL parser. Two private helpers do the work:
fn split_https_url(url: &str) -> io::Result<(&str, Option<u16>, &str)>; // host, port, pathfn split_host_port(authority: &str) -> Result<(&str, Option<u16>), &'static str>;fn parse_authority(authority: &str, default_port: u16) -> Result<ServerAddr, &'static str>;split_https_url:
- The URL must start with
https://, or it is refused withdns: "…" is not an https:// url. - The authority runs up to the first
/. The rest, starting at the/, is the path. With no/, the path is/dns-query. - An empty authority, or one with userinfo (
@), is refused as having no usable host. The code comment gives the reason for the userinfo case: userinfo has no meaning for a resolver URL and would silently become part of the verified name. split_host_portsplits the authority. It acceptshost,host:port,[v6]and[v6]:port. Its refusals arehas an unclosed [,has junk after ](anything after]other than:port),has no hostandhas an invalid port(not au16).split_https_urlreports them asdns: "…" <why>.
Backend::https stores the host and the path. host never includes a port, so a port cannot reach the certificate name. The address dialed is server: under from_spec it comes from the server key; under from_url it is built from the URL’s own host and port. parse_authority is split_host_port plus ServerAddr::new with the scheme’s default port; from_url uses it for udp:// and tls://.
ResolverOptions and StreamDialer
Section titled “ResolverOptions and StreamDialer”pub trait DnsStream: AsyncRead + AsyncWrite + Send {}impl<T: AsyncRead + AsyncWrite + Send> DnsStream for T {}
pub type BoxedDnsStream = Pin<Box<dyn DnsStream>>;pub type DialFuture = Pin<Box<dyn Future<Output = io::Result<BoxedDnsStream>> + Send>>;
pub trait StreamDialer: Send + Sync { fn dial(&self, server: SocketAddr) -> DialFuture;}
#[derive(Clone, Default)]pub struct ResolverOptions { pub hosts: Option<Arc<Hosts>>, pub dialer: Option<Arc<dyn StreamDialer>>, pub bootstrap: Option<Resolver>, pub socket: SocketOptions,}| Field | Effect |
|---|---|
hosts |
Answer from these entries before the cache and before any server. Resolver::hosts() returns them, and the DNS service consults them. |
dialer |
Open every server connection through this instead of from this host. Plain DNS then goes over TCP (RFC 7766) from the start, since not every tunnel carries datagrams. A system server is refused. |
bootstrap |
Look up servers written by name. Without one, a named server is refused. |
socket |
The policy for every socket this resolver opens from this host itself, when it has no dialer. The doc comment’s example is a mobile VPN’s protect hook. |
DnsStream is implemented for every AsyncRead + AsyncWrite + Send type, so a dialer can return a TCP socket or a proxied stream. BoxedDnsStream is Unpin, which is what ClientConfig::wrap and the exchange functions need.
Resolver, Inner, Upstream and Cached
Section titled “Resolver, Inner, Upstream and Cached”#[derive(Clone)]pub struct Resolver { inner: Arc<Inner>,}
struct Inner { upstreams: Vec<Upstream>, // tried in order; the first to answer wins hosts: Option<Arc<Hosts>>, dialer: Option<Arc<dyn StreamDialer>>, bootstrap: Option<Resolver>, local: Dialer, // opens the sockets of a resolver without a dialer min_ttl: Duration, max_ttl: Duration, cache: moka::future::Cache<CompactString, Cached>,}
struct Upstream { backend: Backend, tls: Option<ClientConfig>,}
#[derive(Clone)]struct Cached { addresses: Arc<Vec<IpAddr>>, expires_at: Instant, // tokio::time::Instant}
impl Resolver { pub fn system() -> Self; pub fn new(backend: Backend) -> io::Result<Self>; pub fn with_upstreams(backends: Vec<Backend>, options: ResolverOptions) -> io::Result<Self>; pub fn from_spec(spec: ResolverSpec<'_>) -> io::Result<Self>; pub fn with_ttl_bounds(self, min: Duration, max: Duration) -> Self; pub fn hosts(&self) -> Option<&Hosts>; pub async fn resolve(&self, host: &str) -> io::Result<Vec<IpAddr>>; pub async fn resolve_with_ttl(&self, host: &str) -> io::Result<(Vec<IpAddr>, Duration)>; pub async fn relay(&self, query: &[u8]) -> io::Result<Vec<u8>>;}A Resolver is one Arc. Cloning it shares the servers, their TLS configurations, the hosts table, the dialer, the bootstrap and the cache. The doc comment states the design: one cache serving every outbound is the point, since outbounds resolve overlapping sets of names.
| Constructor | Builds |
|---|---|
system() |
One System upstream with no TLS config and ResolverOptions::default(). impl Default for Resolver calls it, so each Resolver::default() is a new system resolver with its own cache. |
new(backend) |
with_upstreams(vec![backend], ResolverOptions::default()) |
with_upstreams(backends, options) |
Checks each backend in list order, builds its Upstream, then build |
from_spec(spec) |
Backend::from_spec(spec), then system() for System and new(backend) for anything else |
with_ttl_bounds(min, max) |
A new Inner with the same upstreams (TLS configs cloned), hosts, dialer, bootstrap, local dialer and moka handle, and the given clamp |
with_upstreams refuses, with InvalidInput, and stops at the first backend that fails:
dns: the system resolver cannot be reached through a proxyfor aSystembackend whenoptions.dialeris set.getaddrinfotakes a name, not a connection, so there is nothing a dialer could carry.dns: server "<host>" is a name, and nothing resolves it; write its addressfor aServerAddr::Namewhenoptions.bootstrapisNone. The test’s comment puts it as a config error rather than a lookup that fails forever.- Any error from
Upstream::new.
An empty list is accepted. Such a resolver answers only from its hosts table and address literals.
Upstream::new builds the TLS client configuration once per server. Its doc comment gives the reason: a handshake per query is expensive enough without also rebuilding the connector. It calls protocols/src/transports/tls/config.rs → ClientConfig::with_verify_mode, described in TLS configuration and CA handling; Udp and System get no TLS configuration.
build (private) creates the cache (max_capacity(CACHE_CAPACITY), time_to_live(MAX_TTL)), sets min_ttl and max_ttl to MIN_TTL and MAX_TTL, and turns options.socket into local = Dialer::new(socket).
with_ttl_bounds keeps the same moka handle, and a moka handle clones into the same cache, so anything already cached carries over. Only the clamp changes: moka’s time_to_live backstop stays at the MAX_TTL the cache was built with. No front end calls it at the pinned revision; the tests use it to force expiry.
The lookup machinery is private:
fn build(upstreams: Vec<Upstream>, options: ResolverOptions) -> Self;async fn lookup(&self, host: &str) -> io::Result<(Vec<IpAddr>, Option<Duration>)>;async fn query_both(&self, upstream: &Upstream, host: &str) -> io::Result<(Vec<IpAddr>, Option<Duration>)>;async fn query(&self, upstream: &Upstream, host: &str, qtype: u16) -> io::Result<Answer>;async fn exchange(&self, upstream: &Upstream, query: &[u8], udp_buf: usize) -> io::Result<Vec<u8>>;fn server_addr<'a>(&'a self, server: &'a ServerAddr) -> Pin<Box<dyn Future<Output = io::Result<SocketAddr>> + Send + 'a>>;async fn connect(&self, server: SocketAddr) -> io::Result<BoxedDnsStream>;
// free functions in the same modulefn cache() -> moka::future::Cache<CompactString, Cached>;async fn lookup_system(host: &str) -> io::Result<(Vec<IpAddr>, Option<Duration>)>;async fn exchange_framed(stream: impl AsyncRead + AsyncWrite + Unpin, query: &[u8]) -> io::Result<Vec<u8>>;async fn exchange_https_over(stream: impl AsyncRead + AsyncWrite + Unpin, host: &str, path: &str, query: &[u8]) -> io::Result<Vec<u8>>;async fn exchange_udp(local: &Dialer, server: SocketAddr, query: &[u8], buf_len: usize) -> io::Result<Vec<u8>>;#[cfg(windows)]const SYSTEM_PATH: &str = r"C:\Windows\System32\drivers\etc\hosts";#[cfg(not(windows))]const SYSTEM_PATH: &str = "/etc/hosts";
#[derive(Debug, Default, Clone, PartialEq, Eq)]pub struct Hosts { names: HashMap<CompactString, Vec<IpAddr>>,}
impl Hosts { pub fn system() -> io::Result<Self>; pub fn parse(text: &str) -> Self; pub fn get(&self, name: &str) -> Option<&[IpAddr]>;}systemreadsSYSTEM_PATHwithstd::fs::read_to_stringand parses it. A missing file (NotFound) is an empty table; the doc comment says a host without one has nothing to say. Any other read error is returned.parsereads oneaddress name [alias...]entry per line. Everything from the first#to the end of a line is a comment. A line whose first field does not parse as anIpAddris skipped, including a scoped address such asfe80::1%lo0or a typo. The doc comment explains that the file belongs to the system, and one line this parser does not understand must not take every other entry down with it. Each name and alias is stored with trailing dots removed and lowercased. Several lines naming one host merge in file order, and an address is not repeated for a name.getremoves trailing dots fromnameand looks it up as given. Only on a miss does it look up the lowercased form, since names reaching it are almost always lowercase already. It returns every address for the name, both families, in file order.
Service and Transport
Section titled “Service and Transport”#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Transport { Udp, Tcp,}
#[derive(Clone, Debug)]pub struct Service { resolver: Resolver, ipv6: bool,}
impl Service { pub fn new(resolver: Resolver, ipv6: bool) -> Self; pub async fn answer(&self, query: &[u8], transport: Transport) -> Option<Vec<u8>>; async fn respond(&self, query: &Query<'_>, raw: &[u8]) -> Vec<u8>; async fn resolve(&self, query: &Query<'_>) -> Vec<u8>;}
fn ttl_secs(ttl: Duration) -> u32; // whole seconds, saturating at u32::MAX, at least 1Service is what a process acting as the DNS server for the applications behind it does with each query. It relays queries to its resolver’s servers as the client wrote them, so every record type, RCODE, TTL and EDNS option survives, and it answers three kinds of question itself. Transport says how the query arrived, one datagram each way (Udp) or length-prefixed messages on a stream (Tcp), and so whether answer may replace an oversized response with a truncated one. The decision order is in The DNS service. It is cheap to clone: the resolver is an Arc.
Data flow
Section titled “Data flow”resolve_with_ttl: literal, hosts, cache, servers
Section titled “resolve_with_ttl: literal, hosts, cache, servers”flowchart TB
start["resolve_with_ttl(host)"] --> lit{"host parses as IpAddr?"}
lit -- yes --> retlit["([ip], max_ttl)"]
lit -- no --> hosts{"hosts table has host?"}
hosts -- yes --> reth["(entries, SYSTEM_TTL), not cached"]
hosts -- no --> hit{"cache entry with expires_at > now?"}
hit -- yes --> rethit["(addresses, time left)"]
hit -- no --> look["lookup: servers in order"]
look -- error --> err["Err, cache untouched"]
look --> empty{"no addresses?"}
empty -- yes --> nf["Err NotFound: did not resolve"]
empty -- no --> ttl["ttl or SYSTEM_TTL, clamped to min..max"]
ttl --> ins["cache.insert, return (addresses, ttl)"]
resolve(host) is resolve_with_ttl(host) with the TTL dropped. Details the diagram leaves out:
- Literals. An address literal is returned as-is with
max_ttl(3600 s by default), without touching the hosts table, the cache or a server. - Hosts entries come before the cache and are never cached.
Hosts::getdecides the match, case-insensitively. The answer carriesSYSTEM_TTL(60 s), unclamped, and holds both families as the file lists them. - The key is lowercased, the query is not. The cache key is
host.to_ascii_lowercase(), butlookup(host)sends the name as the caller spelled it.Example.COMandexample.comshare one entry. - Expiry is per entry. moka’s
time_to_liveis one value for the whole cache and serves only as a backstop atMAX_TTL; the code comment says so. The real deadline isCached.expires_at, compared withtokio::time::Instant::now(). A hit returns the remaining time (saturating_duration_since), so repeated answers carry a decreasing TTL. An expired entry is not removed on read. The next successful lookup overwrites it, or moka evicts it. - The deadline cannot overflow.
Instant::now().checked_add(ttl)falls back toInstant::now(), so the entry is already stale, which fails safe. - Empty is an error. A lookup that returns no address becomes
dns: <host> did not resolve(NotFound).resolvenever returnsOkwith an empty list. - Failures are not cached here. An error from
lookup, and theNotFoundfor an empty answer, return without touching this cache. The next call asks the servers again. - Concurrent misses are not merged.
resolve_with_ttlcallscache.getand latercache.insert, not a get-or-insert-with. Two callers that miss on the same name at the same moment each run a lookup, and the later insert wins. - A hit returns a copy. The cached
Arc<Vec<IpAddr>>is cloned into a freshVecfor the caller.
lookup: servers in order
Section titled “lookup: servers in order”lookup walks Inner.upstreams in order. For a System upstream it calls lookup_system; for any other it calls query_both. The first upstream whose lookup returns Ok ends the walk, even with no addresses: the doc comment calls an answer with no addresses an answer, which the next server is not asked to contradict. An upstream whose lookup returns an error hands over to the next, and its error is kept. When every upstream failed, lookup returns the last error. When there is no upstream at all, it returns dns: <host> is not in the hosts file and no server is configured (NotFound).
lookup_system calls tokio::net::lookup_host((host, 0)), which runs getaddrinfo on tokio’s blocking pool. Port 0 is a placeholder; only the address matters. It keeps the first occurrence of every IP and reports no TTL, so SYSTEM_TTL applies. The module doc comment explains why the host resolver stays the default: it is the only backend that honours /etc/hosts, nsswitch.conf and search domains, so a protocol client as the default would change what names resolve to on every existing deployment. What the resolver adds on the default path is the cache, since each getaddrinfo otherwise occupies a blocking-pool thread for the duration of the lookup.
query_both: A and AAAA concurrently
Section titled “query_both: A and AAAA concurrently”Every protocol upstream is asked two independent questions with tokio::join!. query gives each a fresh random 16-bit ID (rand::random), encodes it with encode_query, runs one exchange with UDP_BUF, and decodes the response with decode_answer.
flowchart TB
qb["query_both(upstream, host)"] --> join["tokio::join!"]
join --> ea["query TYPE_A: own id, own exchange"]
join --> e6["query TYPE_AAAA: own id, own exchange"]
ea --> merge["walk v4 then v6: dedupe addresses, min TTL, keep last error"]
e6 --> merge
merge --> none{"no address and an error?"}
none -- yes --> err["Err(last error)"]
none -- no --> ok["Ok((addresses, ttl))"]
query_both walks the results in the order [v4, v6]:
- A successful
Answercontributes its addresses, skipping duplicates, and itsttl. The combined TTL is the minimum over both answers. - A failed query only records its error. A response with a non-zero RCODE is a failed query (
decode_answerreturnsdns: server returned rcode <n>). - The call fails only when no address came back and at least one query failed. It then returns the last error, which is the AAAA error when both failed. The doc comment gives the reason: a host with only an A record must still resolve when the AAAA query returns nothing.
- When both queries succeed with no records, the result is
Ok((vec![], ttl)).lookupstops there, andresolve_with_ttlturns it intodns: <host> did not resolve.
Two consequences follow from the ordering and the merge:
- With a protocol upstream, IPv4 addresses always come before IPv6 addresses.
AddressFamilyStrategy::Autokeeps the resolver’s order, so such an outbound tries IPv4 first. - A lookup in which one family failed is cached like any other. It stays single-family until its TTL runs out.
exchange: one message to one server
Section titled “exchange: one message to one server”exchange(upstream, query, udp_buf) sends one message and returns the response bytes. It is wrapped in tokio::time::timeout(QUERY_TIMEOUT, ..); on expiry the error is dns: query timed out (TimedOut). Timeout scope lists the resolver’s own steps that count against it.
flowchart TB
ex["exchange(upstream, query, udp_buf)"] --> addr["server_addr: the address, or a bootstrap lookup"]
addr --> kind{"backend and dialer"}
kind -- "Udp, no dialer" --> udp["exchange_udp on a local socket"]
udp --> tc{"TC bit set?"}
tc -- yes --> tcp["local TCP connect, exchange_framed"]
tc -- no --> done["response bytes"]
kind -- "Udp, dialer" --> dial["dialer.dial, exchange_framed"]
kind -- Tls --> tls["connect, TLS wrap, exchange_framed"]
kind -- Https --> doh["connect, TLS wrap, exchange_https_over"]
tcp --> done
dial --> done
tls --> done
doh --> done
connect(server) opens a TCP stream: through Inner.dialer when there is one, otherwise with Inner.local.tcp.connect(server). Two arms cannot be reached through the public API and exist as guards: a System upstream has no server and fails with dns: the system resolver takes no messages (Unsupported), and a Tls or Https upstream without a TLS configuration fails with dns: backend has no tls config (InvalidInput). query_both is never called for System, relay skips it, and Upstream::new always builds the configuration for Tls and Https.
exchange_udp(local, server, query, buf_len):
local.udp.bind(AddressFamily::of(&server)): a new socket of the server’s family on an ephemeral port, under the resolver’s socket policy, so an IPv6 resolver is reachable. The IPv6 socket is v6-only (environment/src/dial/udp.rs→UdpDialer::bind).connect(server), so the kernel delivers only datagrams from the server’s address and port.sendthe query once.recvone datagram into a buffer ofbuf_lenbytes (UDP_BUF, 512, for the resolver’s own queries;RELAY_UDP_BUF, 65535, for relayed ones) and truncate it to the length received.
There is no retransmission. A lost datagram surfaces as dns: query timed out after QUERY_TIMEOUT.
Back in exchange, message::is_truncated checks the TC bit. A truncated response is the server asking for TCP (RFC 7766); the code comment says passing it on would leave the asker with a partial answer or none. The query is then sent again over local.tcp.connect(server) with exchange_framed, inside the same QUERY_TIMEOUT.
Plain DNS goes over TCP in two cases: after a truncated UDP response, and always when the resolver has a StreamDialer. exchange_framed uses the DNS-over-TCP framing of RFC 1035 §4.2.2, which DNS over TLS reuses:
| Field | Size | Meaning |
|---|---|---|
| Length | 2 | big-endian length of the message that follows |
| Message | Length | the DNS query or response |
- Write the 2-byte length and the query, then flush. A query over 65535 bytes fails with
dns: query too long(InvalidInput). read_exactthe 2-byte length, thenread_exactexactly that many bytes. That one message is the response.- Return. The caller drops the stream, so a connection carries a single query.
connect(server), then Upstream.tls.wrap(stream): a TLS handshake with SNI and certificate name server_name, and no ALPN (Alpn::None). ClientConfig::wrap is generic over any AsyncRead + AsyncWrite + Unpin stream, so the handshake runs over a local TCP socket or over whatever a StreamDialer returned. An IP-literal server_name is handled as TLS configuration and CA handling describes. The query then goes through exchange_framed, exactly as over TCP.
connect(server) and wrap exactly as for DoT, but the ClientConfig offers http/1.1 as its only ALPN protocol (Alpn::Http1). The code comment states the intent: a server that will not speak HTTP/1.1 fails the handshake loudly instead of answering something this client cannot read. exchange_https_over then sends one RFC 8484 POST:
POST {path} HTTP/1.1Host: {host}Accept: application/dns-messageContent-Type: application/dns-messageContent-Length: {query.len()}Connection: close
{query bytes}The response is read in four steps:
read_to_enduntil the server closes the connection, as the request’sConnection: closeasked.- Find the first
\r\n\r\n. Without one, the error isdns: no http header(InvalidData). The bytes before it are the head, decoded withString::from_utf8_lossy. - Take the second whitespace-separated token of the head’s first line, the status line. Anything other than
200fails withdns: doh server answered "<status line>"(InvalidData), so an error page is never decoded as DNS. - Return every byte after that first blank line unchanged.
querythen decodes them withdecode_answer, andrelayreturns them when their id matches.
The doc comment explains why nothing is pooled: a resolver is consulted rarely once the cache is warm, and a connection held open would have to be revalidated anyway.
One connection per exchange
Section titled “One connection per exchange”No transport pools anything. Each exchange over TCP, TLS or HTTPS opens its own connection and, for TLS, completes its own handshake. Because A and AAAA run concurrently, one cache miss against a DoT server costs two connections:
sequenceDiagram participant A as query(TYPE_A) participant B as query(TYPE_AAAA) participant S as DoT server A->>S: connect, TLS handshake (SNI server_name) B->>S: connect, TLS handshake (SNI server_name) A->>S: u16 length, A query B->>S: u16 length, AAAA query S-->>A: u16 length, response S-->>B: u16 length, response Note over A,B: each stream is dropped after its one response
DoH has the same shape, with the POST in place of the length prefix and read_to_end in place of the length-delimited read. Plain DNS through a StreamDialer has it too, without the handshake. What the exchanges share is the SslConnector inside each Upstream.tls, built once in Upstream::new. Pooling, if it is added, has to keep the whole exchange inside QUERY_TIMEOUT and one response per request ID.
Server names and the bootstrap
Section titled “Server names and the bootstrap”server_addr(server) returns the address to dial:
ServerAddr::Ip(addr)is returned as it is.ServerAddr::Name { host, port }is looked up withbootstrap.resolve(host), and the first address, withport, is dialed. No address-family policy is applied here. Without a bootstrap the error would bedns: nothing resolves the server name "<host>"(InvalidInput), and with an empty resultdns: server <host> did not resolve(NotFound). Neither is reachable in practice:with_upstreamsrefuses a named server without a bootstrap, andresolvenever returns an empty list. The bootstrap’s own errors are passed up unchanged.
The bootstrap lookup runs inside the calling exchange, so it counts against that exchange’s QUERY_TIMEOUT. It goes through the bootstrap’s cache, so only the first exchanges after a miss wait for a real lookup. The future is boxed and declared Send, because the bootstrap is a Resolver too: without the box this future would contain its own type, and whether it is Send could not be settled.
relay: a client’s query, untouched
Section titled “relay: a client’s query, untouched”relay(query) serves the DNS service:
- The first two bytes are the query’s id. A shorter query fails with
dns: query shorter than its id(InvalidData). - Each upstream is tried in order.
Systemupstreams are skipped, becausegetaddrinfotakes a name, not a message. - The query goes out as written through
exchange(upstream, query, RELAY_UDP_BUF), over the upstream’s transport as above, including the retry over TCP when a UDP response is truncated. - The first response whose first two bytes equal the query’s id is returned untouched. A response with another id records
dns: relayed response does not match the query id(InvalidData), and any other failure records its error. Either way the next upstream is tried. - When every upstream failed, the last error is returned. When no upstream was tried at all, because there are none or all are
System, the error isdns: no server that a query can be relayed to(Unsupported).
relay decodes nothing, so it keeps every record type, RCODE, TTL and EDNS option of the server’s response.
The DNS service
Section titled “The DNS service”Service::answer(query, transport) first runs message::decode_query. Bytes that do not decode are dropped: answer returns None, logs dns service: dropping an undecodable query: <error> at debug (target etemenanki_protocols::dns::serve), and the caller sends nothing. Its doc comment puts it as garbage getting no reply, as from any server. Otherwise the private respond decides:
flowchart TB
q["respond(query, raw)"] --> op{"opcode 0?"}
op -- no --> notimp["NOTIMP, no records"]
op -- yes --> aaaa{"AAAA in IN, ipv6 off?"}
aaaa -- yes --> empty["NOERROR, no records"]
aaaa -- no --> hosts{"A or AAAA in IN, name in hosts?"}
hosts -- yes --> h["NOERROR from the hosts entry, TTL 60"]
hosts -- no --> relay["Resolver::relay(raw)"]
relay -- Ok --> raw["server's response, untouched"]
relay -- "no relayable server" --> own["A or AAAA: own lookup; else empty NOERROR"]
relay -- "other failure" --> sf["SERVFAIL"]
| Question | Response |
|---|---|
| Opcode other than 0 (a standard query) | NOTIMP (4), no records |
AAAA in class IN, service built with ipv6 false |
Empty NOERROR, without asking anyone. The module comment says why: the application settles on IPv4 without waiting on a timeout. |
A or AAAA in class IN, name in the resolver’s hosts table |
NOERROR with the entry’s addresses of the asked family, TTL SYSTEM_TTL (60). A name the table lists only with the other family gets an empty NOERROR. |
| Anything else | Resolver::relay with the raw bytes. A response is returned as the server sent it. |
The resolver has no server a query can be relayed to (none, or only system servers) |
A or AAAA in class IN: an answer from resolve_with_ttl (below). Any other question: an empty NOERROR. |
relay fails in another way, for example when the servers it tried failed |
SERVFAIL (2), and dns service: <name> failed: <error> at debug |
The module doc states the case the own-lookup row is for: an A or AAAA question when every server is system, which takes a name rather than a message. A resolver with no servers at all, such as one built from hosts entries only, takes the same path.
The private resolve builds an A or AAAA answer from resolve_with_ttl(&query.name):
Ok((addresses, ttl))isNOERRORwith the addresses of the asked family and TTLttl_secs(ttl): whole seconds, at least 1. A cache hit carries the time it has left.- An error of kind
NotFoundisNXDOMAIN(3), with no records. - Any other error is
SERVFAIL, with the same debug line.
After respond, the transport is applied. Over Transport::Udp, a response longer than Query::udp_limit() is replaced by encode_truncated: a response header with the TC bit set, the client’s question, and no records. udp_limit is the EDNS payload size the client advertised, and never less than CLASSIC_UDP_LIMIT (512). The client then asks again over TCP. This applies to relayed responses as well as to answers built here. Over Transport::Tcp, answer does not truncate the response.
The service holds nothing but its resolver and the ipv6 flag, and spawns nothing. Its consumer in the workspace is the supervisor’s DNS outbound (supervisor/src/topology/outbound/dns.rs → DnsUdpLink and DnsTcpStream), which frames queries and answers for the flows the plane intercepts on port 53; see Name resolution and the DNS service.
From addresses to dial candidates
Section titled “From addresses to dial candidates”Outbounds do not call resolve directly. They go through protocols/src/helpers/address_family.rs:
pub async fn resolve_candidates( context: &str, dest: &Destination, strategy: AddressFamilyStrategy, support: FamilySupport, resolver: &Resolver,) -> io::Result<Vec<IpAddr>>;
pub async fn destination_to_socketaddrs( dest: &Destination, strategy: AddressFamilyStrategy, resolver: &Resolver,) -> io::Result<Vec<SocketAddr>>;resolve_candidates passes a Remote::IpAddr through as it is and resolves a Remote::Domain with resolver.resolve, keeping every address. An empty list at this point fails with <context>: destination did not resolve (NotFound); the guard cannot fire with Resolver::resolve, which never returns an empty Ok. select_candidate_ips then drops addresses the strategy or the family support rules out and, for PreferIpv4 or PreferIpv6, sorts the preferred family first with a stable sort. An empty result is <context>: no usable <strategy> destination address for <remote>:<port> (AddrNotAvailable), built by no_candidate_error, with (local address supports <IPv4 only|IPv6 only|no address family>) appended whenever the caller’s FamilySupport is not both families. Only WireGuard passes a narrower one. destination_to_socketaddrs uses the context dial and FamilySupport::both(), and pairs each candidate with the destination’s port. The strategy values and their parsing are on Protocol crate foundations.
| Consumer | Call | What it resolves |
|---|---|---|
protocols/src/transports/connect.rs → TransportConnector::dial |
destination_to_socketaddrs, then TcpDialer::connect_any |
The upstream proxy server of every stream-based proxy outbound |
protocols/src/hysteria/connection.rs → Hy2Conn::connect |
destination_to_socketaddrs, each candidate tried in turn; with port hopping, each candidate’s host is dialed over the configured ports through a HoppingSocket |
The Hysteria 2 server, through the resolver given to Hy2Connector::with_resolver |
protocols/src/wireguard/device.rs → resolve_endpoint |
destination_to_socketaddrs with the configured strategy, first address |
The peer endpoint, when WgConfig::endpoint_resolution is set |
protocols/src/wireguard/connector.rs → WgConnector::dial |
resolve_candidates("wireguard", …) with FamilySupport::from_addrs of the tunnel addresses; a UDP association (WgDatagramLink) keeps an address it found for the association’s life, and a failed lookup for only FAILED_LOOKUP_TTL (10 s), after which it looks the name up again (Lookups) |
Destinations reached inside the tunnel, through the resolver given to with_resolver |
supervisor/src/topology/outbound/freedom.rs → FreedomConnector::dial, ResolvingUdp |
destination_to_socketaddrs for TCP flows, then TcpDialer::connect_any, and for UDP packets to a domain |
Destinations dialed directly |
supervisor/src/topology/balancer.rs → Balancer::spawn_probe |
destination_to_socketaddrs with AddressFamilyStrategy::Auto |
Each balancer member’s upstream |
protocols/src/transports/reality.rs → RealityServer::dial_dest |
destination_to_socketaddrs, then TcpDialer::connect_any |
A REALITY inbound’s cover site (dest), through the resolver given to dial_with |
What happens after resolution belongs to the consumer. environment/src/dial/tcp.rs → TcpDialer::connect_any tries the addresses one after another and, when every attempt fails, returns failed to connect to any address (<addr>: <error>; …) (ConnectionRefused), naming each failure. Hy2Conn::connect reports its candidates the same way, as hysteria2: no address answered (…); see Hysteria 2: protocol and client. How freedom sends UDP packets to a domain is on Outbounds, UDP fan-out and balancers.
Wire codec
Section titled “Wire codec”protocols/src/dns/message.rs is a stub resolver’s codec plus the part of a server’s it needs: one question out and the address records of the answer in, and a client’s question in and an answer out. It reads every field through crate::helpers::parse::{take, take_array} and uses checked arithmetic for every offset, so hostile input ends in an error, never a panic, a loop or an out-of-bounds read. The module comment states that both a response and a client’s query may be adversarial. ProtocolError and the parsing helpers are described in Protocol crate foundations.
pub const TYPE_A: u16 = 1;pub const TYPE_AAAA: u16 = 28;const TYPE_OPT: u16 = 41;pub const CLASS_IN: u16 = 1;const HEADER_LEN: usize = 12;const FLAG_QR: u16 = 0x8000;const OPCODE_MASK: u16 = 0x7800;const FLAG_TC: u16 = 0x0200;const FLAG_RD: u16 = 0x0100;const FLAG_RA: u16 = 0x0080;const RCODE_MASK: u16 = 0x000F;pub const RCODE_NOERROR: u8 = 0;pub const RCODE_SERVFAIL: u8 = 2;pub const RCODE_NXDOMAIN: u8 = 3;pub const RCODE_NOTIMP: u8 = 4;pub const CLASSIC_UDP_LIMIT: usize = 512;const RR_FIXED_LEN: usize = 12;const MAX_POINTER_HOPS: usize = 16;const MAX_NAME_LEN: usize = 255;
#[derive(Debug, Clone, PartialEq, Eq)]pub struct Answer { pub addresses: Vec<IpAddr>, pub ttl: Option<Duration>,}
pub fn encode_query(id: u16, name: &str, qtype: u16) -> io::Result<Vec<u8>>;pub fn decode_answer(id: u16, data: &[u8]) -> io::Result<Answer>;pub fn decode_query(data: &[u8]) -> io::Result<Query<'_>>;pub fn encode_response(query: &Query<'_>, rcode: u8, addresses: &[IpAddr], ttl: u32) -> Vec<u8>;pub fn encode_truncated(query: &Query<'_>) -> Vec<u8>;pub fn is_truncated(response: &[u8]) -> bool;fn u16_at(b: &[u8], at: usize) -> Result<u16, ProtocolError>;fn skip_name(data: &[u8], at: usize) -> Result<usize, ProtocolError>;fn response_head(query: &Query<'_>, flags: u16, answers: u16, capacity: usize) -> Vec<u8>;Structural failures are ProtocolError values converted to io::Error (protocols/src/error.rs): Truncated becomes UnexpectedEof with the text truncated input: <field>, and Overflow becomes InvalidData with integer overflow: <field>. take_array reports a short read as truncated input: fixed-size field and an overflowing offset as integer overflow: field offset.
Query layout
Section titled “Query layout”encode_query writes a standard recursive query. All integers are big-endian.
| Field | Size | Value written |
|---|---|---|
| ID | 2 | id, random per query |
| Flags | 2 | FLAG_RD (0x0100): a standard query with recursion desired |
| QDCOUNT | 2 | 1 |
| ANCOUNT, NSCOUNT, ARCOUNT | 6 | 0 |
| QNAME | variable | one length byte plus the label bytes for each non-empty label, then a 0 root label |
| QTYPE | 2 | TYPE_A (1) or TYPE_AAAA (28) |
| QCLASS | 2 | CLASS_IN (1) |
Encoding rules:
- Name length. The textual name may be at most
MAX_NAME_LEN(255) bytes, or the call fails withdns: name too long (<n> bytes)(InvalidInput). - Label length. Each label may be at most 63 bytes, or the call fails with
dns: label longer than 63. A separatedns: label longer than 255guards theu8conversion; the name check makes it unreachable. - Empty labels. The encoder drops them, so
example.com.andexample.comencode identically. - No escaping or IDNA. Label bytes are copied as given.
- No EDNS. The query has no OPT record, which is why the resolver’s own UDP exchanges use the classic 512-byte
UDP_BUF.
The module comment explains why CNAME chains are not followed: every query sets the recursion-desired bit, so the server returns the addresses along with the aliases.
Response parsing
Section titled “Response parsing”decode_answer(id, data) reads the header, walks past the questions, and then reads ANCOUNT resource records. It never reads the authority and additional sections.
| Field | Size | What decode_answer does |
|---|---|---|
| ID | 2 | must equal id, or dns: response id <got> does not match query <id> (InvalidData) |
| Flags | 2 | QR must be set, or dns: not a response (InvalidData). The RCODE (low 4 bits) must be 0, or dns: server returned rcode <n> (NotFound). |
| QDCOUNT | 2 | the number of questions before the answers |
| ANCOUNT | 2 | the number of records to read |
| NSCOUNT, ARCOUNT | 4 | not needed: the parser stops after the answer records |
| Question × QDCOUNT | variable | each one’s extent: skip_name, then 4 bytes (QTYPE, QCLASS), with checked offsets |
| RR NAME | variable | its extent, through skip_name |
| RR TYPE, CLASS | 4 | TYPE decides the record’s use: TYPE_A and TYPE_AAAA are read, anything else is skipped |
| RR TTL | 4 | seconds; the minimum over all A and AAAA records becomes Answer.ttl |
| RDLENGTH | 2 | the RDATA range must lie inside the buffer, or truncated input: dns rdata |
| RDATA | RDLENGTH | 4 bytes for A, 16 for AAAA; any other length is skipped |
The record loop is lenient on purpose:
- Unusable records are skipped, not fatal. A CNAME, an unknown type, or an A record with the wrong RDLENGTH is stepped over (
at = rdata_at + rdlen), and the next record is read. The code comment gives the reason: an answer with one odd record and one good address is still a usable answer. - Every A or AAAA record counts toward the TTL, including one skipped for a bad length.
- The result can be empty.
Answer.addressesmay be empty, withttlset orNone.query_bothandresolve_with_ttldecide what an empty result means.
A structural failure in the header, the question section or a record boundary fails the whole response.
Names and compression pointers
Section titled “Names and compression pointers”The response decoder never needs a name’s text, only where the name ends, so skip_name walks a name in place and never follows a compression pointer. It returns the offset after the name as encoded at that position: a pointer is two bytes however long the name it names.
| First byte of a label | Meaning | skip_name does |
|---|---|---|
0x00 |
root label | returns the offset after it |
0b11xx_xxxx |
compression pointer (2 bytes) | returns the offset after the pointer, without dereferencing it |
0b01xx_xxxx or 0b10xx_xxxx |
reserved label types | fails with truncated input: dns label type |
0b00xx_xxxx (1 to 63) |
literal label | advances by 1 plus the label length (checked) and loops |
The loop is bounded by MAX_POINTER_HOPS (16) iterations; when it runs out, the error is truncated input: dns name pointer chain. A pointer ends the walk and is never followed, so a pointer cycle cannot loop.
Reading a client’s query
Section titled “Reading a client’s query”#[derive(Debug, Clone, PartialEq, Eq)]pub struct Query<'a> { pub id: u16, flags: u16, pub name: String, // dotted, without the root label pub qtype: u16, pub qclass: u16, question: &'a [u8], // the question section as written, echoed back verbatim udp_payload: Option<u16>,}
impl Query<'_> { pub fn opcode(&self) -> u8; // (flags & OPCODE_MASK) >> 11 pub fn udp_limit(&self) -> usize; // max(udp_payload or 0, CLASSIC_UDP_LIMIT)}decode_query(data) accepts exactly one question and nothing that is a response:
- Read the id and flags.
QRset fails withdns: a response, not a query. - QDCOUNT other than 1 fails with
dns: a query must ask exactly one question. - Read the question name label by label. A length byte above 63 fails with
dns: compressed or oversized label in a question. The doc comment says why pointers are refused rather than followed: a query has nothing earlier to point at. Label bytes become text throughString::from_utf8_lossy, so each byte sequence that is not UTF-8 becomes U+FFFD; that text is theQuery::namewhichHosts::getand, on the service’s own-lookup path,resolve_with_ttlreceive. A dotted name longer than 255 bytes fails withdns: name too long. A label that runs past the buffer istruncated input: dns label. - Read QTYPE and QCLASS, and keep the question bytes from offset 12 to the end of QCLASS as
question, so an answer names exactly what was asked, case included. - Walk the answer, authority and additional sections with
skip_nameand each record’s fixed 10 bytes plus RDLENGTH. An OPT record (TYPE_OPT, 41) setsudp_payloadto its class field, which EDNS uses for the UDP payload size, only when it sits in the additional section (section index 2 of the loop); each such record overwrites the value, so with several the last one counts. Everything else is stepped over.
All of these errors are InvalidData or come from the parse helpers. decode_query does not look at the opcode; Service::respond does.
Building answers
Section titled “Building answers”response_head writes the header every answer starts with: the query’s id; flags QR | RA, the query’s opcode and RD bits, and any extra flags; QDCOUNT 1; the answer count; NSCOUNT and ARCOUNT 0; then the client’s question bytes verbatim.
encode_response(query, rcode, addresses, ttl)setsrcode & RCODE_MASK. It writes one record for each address of the family the question asked for, and none for any other question: A records for an A question and AAAA records for an AAAA one, only when the class isIN. The count is capped atu16::MAX. Each record is a compression pointer to the question name (0xC0 0x0C), the question’s type,CLASS_IN,ttl, and RDLENGTH 4 or 16 with the address.RR_FIXED_LEN(12) is used only for the capacity hint.encode_truncated(query)is the header withFLAG_TCand no records.is_truncated(response)reads the flags word and checksFLAG_TC. A response shorter than 4 bytes counts as not truncated.
Answers built here carry no authority or additional records, so no OPT record either.
TLS configuration and CA handling
Section titled “TLS configuration and CA handling”Upstream::new calls protocols/src/transports/tls/config.rs → ClientConfig::with_verify_mode:
pub fn with_verify_mode(sni: impl AsRef<str>, verify_mode: VerifyMode, alpn: Alpn) -> io::Result<Self>;pub async fn wrap<S>(&self, tcp: S) -> io::Result<SslStream<S>>where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin;| Backend | sni |
verify_mode |
alpn |
|---|---|---|---|
Tls |
server_name |
VerifyMode::CustomCa(pem) when ca_pem is set, otherwise VerifyMode::System |
Alpn::None |
Https |
host |
same | Alpn::Http1 |
Both modes verify the chain and the host name, and with_verify_mode requires TLS 1.2 or newer. It also turns OpenSSL’s read-ahead on, so a DoT or DoH answer is pulled off its stream in as few reads as the stream holds it, rather than one read for each record’s header and one for its body; records read ahead come out of the next SSL_read (see Read-ahead). The resolver never uses VerifyMode::Insecure. wrap hands the name to OpenSSL’s into_ssl, so a name that parses as an IP address (a server_name such as 192.0.2.53, a tls:// URL without a fragment written with an IP, or an IP host in a DoH URL) is sent without SNI and verified against the certificate’s IP address entries.
Both modes start from the system roots through transports/tls/config.rs → trust_system. It calls set_default_verify_paths() and, on Android, iOS, Windows and macOS, also adds every certificate of the platform roots, which the default paths of an OpenSSL built from source do not reach (transports/tls/platform_roots.rs → ROOTS, built once per process). A certificate the store refuses, such as one it already holds, is skipped. On Android that is the system store, read file by file from /apex/com.android.conscrypt/cacerts or, when that holds no certificate, /system/etc/security/cacerts; if neither yields a certificate it logs tls: no system CA certificate could be read from ["/apex/com.android.conscrypt/cacerts", "/system/etc/security/cacerts"] at warn and trusts the default paths alone. iOS gives an app no store to read, so there it is Mozilla’s roots as the webpki-root-certs crate ships them: a CA that a user or an MDM profile installed is not trusted, and a resolver behind such a CA needs its ca_pem. On Windows and macOS such an OpenSSL looks under a build-time OPENSSLDIR the system does not have, so there it is the platform’s own store, the Windows certificate store or the macOS keychains, read through rustls-native-certs (platform_roots::native). A certificate that cannot be read or converted is skipped; each read error is logged at warn as tls: reading the system's CA certificates: <error>, and an empty result as tls: no system CA certificate could be read.
VerifyMode::CustomCa trusts the configured CA in addition to the system roots. It calls trust_system first and then adds every certificate parsed from the PEM to the connector’s own store; the host’s trust store is not modified. A private resolver with its own CA therefore works, and a public resolver still verifies against the system roots. A PEM with no certificate in it fails with no certificate in CA PEM bundle (InvalidInput). A certificate block that does not parse fails with the OpenSSL error from X509::stack_from_pem (kind Other); its text comes from the OpenSSL library the crate is linked against, the system one or the one built by the vendored-openssl feature.
Socket policy on resolver sockets
Section titled “Socket policy on resolver sockets”Every socket a resolver opens from this host goes through Inner.local, a Dialer built from ResolverOptions::socket (environment/src/dial/mod.rs):
| Socket | Opened by | Policy |
|---|---|---|
| UDP query socket | exchange_udp → local.udp.bind(AddressFamily::of(&server)) |
SocketOptions::apply before the bind, then a bind to the policy’s bind_address_for(family), or to the unspecified address of the family when the policy sets none (UdpDialer::bind) |
| TCP retry after a truncated UDP response | exchange → local.tcp.connect(server) |
SocketOptions::apply, TCP keepalive (tcp_keepalive) if the policy sets it, a bind to the policy’s bind_address_for(family) if it sets one (TcpDialer::socket), and the dialer’s connect timeout |
| DoT and DoH connections without a dialer | connect → local.tcp.connect(server) |
the same |
| Any connection with a dialer | StreamDialer::dial |
whatever the dialer applies; the resolver opens no socket itself |
getaddrinfo |
the C library | none: the library opens its sockets where no policy reaches them |
The TCP dialer’s connect timeout is environment/src/dial/tcp.rs → DEFAULT_CONNECT_TIMEOUT (10 s). It runs inside the exchange’s QUERY_TIMEOUT (5 s), so a resolver connect that hangs ends with dns: query timed out, not with the dialer’s connect to <addr> timed out. A hook that refuses a socket fails the exchange with the hook’s error. The ffi’s hook (ffi/src/platform.rs → socket_options) refuses with the platform refused to protect the socket (PermissionDenied), and the resolver then moves to its next server. How SocketOptions is applied is on Dialers, and the ffi’s use of it is on Mobile library (etemenanki-ffi).
Resolver::system() and Resolver::new use ResolverOptions::default(), whose policy is the default one. A resolver that has to honour a policy must be built with with_upstreams. The supervisor builds every resolver that opens sockets itself that way, with the policy given to SupervisorBuilder::socket_options (see Where resolvers come from). Its doc comment says the policy holds for the supervisor’s lifetime and an apply cannot change it, so a resolver the supervisor builds again later gets the same policy.
Where resolvers come from
Section titled “Where resolvers come from”Front ends and the supervisor
Section titled “Front ends and the supervisor”Front ends do not build resolvers. They lower their [dns] configuration into Backend values inside the supervisor’s DnsSpec, and the supervisor builds the resolvers from it.
| Front end | Input | Lowering | Result |
|---|---|---|---|
| etemenanki-app | [dns] (app/src/config.rs → DnsConfig: backend, server, server_name, url, ca_file; deny_unknown_fields) |
app/src/lower.rs → lower_dns → lower_single_dns: ca_file read into PEM bytes, then Backend::from_spec |
DnsSpec::Single(backend); without [dns], Single(Backend::System) |
etemenanki-app with a subscribe file that has [dns] |
subscribe/src/dns.rs → DnsConfig (pre_proxy, through_proxy, use_hosts, resolve_ipv6) |
lower_dns: each URL through Backend::from_url |
DnsSpec::Split { pre_proxy, through_proxy, use_hosts, resolve_ipv6 } |
| katana | [dns] (katana src/config.rs → DnsConfig, the same five keys as the app’s) |
katana src/lower/outbound.rs → lower_dns: ca_file read into PEM bytes, then Backend::from_spec |
DnsSpec::Single(backend) in every node’s spec |
The subscribe file’s fifth [dns] key, connect_ipv6, does not enter the DnsSpec: app/src/subscribe.rs turns it into the address_family of the outbounds it builds for the file’s proxy servers. Lowering keeps system in a subscribe file’s through_proxy (a_subscribe_file_splits_dns); Resolver::with_upstreams is what refuses it when the supervisor builds the resolver. How the app lowers the rest of its config is on etemenanki-app: from TOML to a spec and Subscribe files; katana’s lowering is on Lowering a node into a spec.
supervisor/src/build/dns.rs → build_dns turns a DnsSpec into resolvers. Single(System) becomes Resolver::system(). Every other backend list goes through Resolver::with_upstreams with ResolverOptions::socket set to the supervisor’s socket policy. A Split spec gives two resolvers and a service: a direct resolver over the pre_proxy servers; a through-proxy resolver over the through_proxy servers, with RoutedDialer as its dialer and the direct resolver as its bootstrap (a clone of the direct one when through_proxy is empty); and a Service over the through-proxy resolver. A build failure is ApplyError::Build { resource: Resource::Dns, .. }, which displays as building dns failed: <source> (supervisor/src/build/apply.rs).
Which consumer gets which resolver, the hosts table of a Split setup, RoutedDialer, the port-53 interception and katana’s resolvers per node are on Name resolution and the DNS service. When an apply builds new resolvers, and which outbounds it rebuilds with them, is on Planning and applying a change.
Defaults outside the supervisor
Section titled “Defaults outside the supervisor”A consumer built without a resolver gets Resolver::default(), a new system resolver with a private cache:
supervisor/src/topology/outbound/freedom.rs→FreedomConnector::default();protocols/src/transports/connect.rs→TransportConnector::tcp();WgConnectorandHy2Connector, untilwith_resolveris called;protocols/src/transports/reality.rs→RealityServer, untildial_withis called.supervisor/src/build/inbound.rs→build_realitycalls it withResolver::default()and aDialerover the socket policy, so a REALITY inbound resolves its cover site with the system resolver, never through the configured DNS: the cover site is the operator’s own, not proxied traffic. See REALITY transport.
Anything built outside supervisor/src/build/outbound.rs → build_outbound must pass a resolver explicitly, through FreedomConnector::new, TransportConnector::new, with_resolver or dial_with, or it resolves on its own, with its own cache and without the socket policy.
A WireGuard peer endpoint that is a name is resolved by the resolver only when WgConfig::endpoint_resolution is Some((resolver, strategy)): resolve_endpoint then calls destination_to_socketaddrs with that strategy and dials the first address. The supervisor always sets it, with servers and the outbound’s endpoint_address_family. With None, the endpoint is looked up with tokio::net::lookup_host, the host resolver without this cache, and its first address is dialed. Both paths fail an empty result with wireguard: endpoint domain did not resolve. See WireGuard.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
| A protocol upstream asks the configured server | Backend::Udp(addr) reaching exchange_udp |
the_udp_backend_resolves_against_the_configured_server |
| DoT uses the 2-byte length framing and DoH an RFC 8484 POST, both over a verified handshake | exchange_framed, exchange_https_over |
dot_resolves_over_tls, doh_resolves_over_https (the DoH test server asserts the request line, Content-Type and Host) |
| An address literal never reaches a server or the cache | the host.parse::<IpAddr>() early return |
an_address_literal_never_reaches_the_backend |
| A repeat lookup inside the TTL is answered from the cache | Cached.expires_at compared with Instant::now() |
a_second_lookup_is_served_from_cache |
| An expired entry is looked up again, not served stale | the same comparison | an_expired_entry_is_looked_up_again (uses with_ttl_bounds) |
| Clones share one cache | Resolver { inner: Arc<Inner> } |
a_clone_shares_the_same_cache |
| The cache stays bounded however many distinct names clients send | max_capacity(CACHE_CAPACITY) |
the_cache_stays_bounded_under_distinct_names, which inserts CACHE_CAPACITY / 4 + 500 (2548) names, fewer than the capacity, so it would also pass without the bound; it does not exercise eviction |
A lookup that yields no address is an error, not Ok(vec![]) |
the last-error return in query_both and the empty check in resolve_with_ttl |
a_name_that_does_not_resolve_is_an_error_not_an_empty_answer, which points the resolver at an unreachable server, so it pins the both-queries-failed case |
| The default backend is the host resolver | impl Default for Resolver → Resolver::system() |
the_default_backend_is_the_host_resolver |
A backend missing a required field is refused, never replaced by system |
the needed closure and the ok_or_else checks in from_spec |
a_backend_missing_its_fields_is_refused; in lowering, a_dns_backend_needs_what_it_names; end to end, a_backend_without_its_server_is_rejected |
| A DoH URL yields a host and a path; a URL port and userinfo never reach the verified name | split_https_url, Backend::https |
a_doh_url_is_split_into_authority_and_path |
| Every documented URL form parses, and malformed ones are refused | Backend::from_url, parse_authority |
a_server_url_is_read_in_every_documented_form (refuses "", tcp://1.1.1.1, 1.1.1.1, udp://1.1.1.1#x, tls://1.1.1.1#, udp://:53) |
| A server the resolver could never use is refused when it is built, not when a query fails | with_upstreams |
a_named_server_without_a_bootstrap_is_refused (the system-with-a-dialer refusal has no test) |
| Queries sent from this host get the resolver’s socket policy | Inner.local = Dialer::new(options.socket) |
a_query_socket_gets_the_socket_policy |
| A response must carry the query’s ID, set QR, and have RCODE 0 | decode_answer header checks |
rejects_a_mismatched_id_a_question_and_an_error_rcode |
| Truncated or malformed input returns an error and never panics | take, take_array and checked_add on every offset |
truncated_and_malformed_input_never_panics |
| A compression-pointer cycle terminates | skip_name never follows pointers, and its loop is bounded by MAX_POINTER_HOPS |
a_compression_pointer_loop_terminates |
| One unrecognised record does not discard the addresses beside it | the _ => {} arm of the record loop |
an_unrecognised_record_is_skipped_not_fatal |
| The shortest address TTL governs, and AAAA records are read | min over A and AAAA TTLs |
decodes_addresses_and_the_smallest_ttl, decodes_aaaa_records |
| Queries are well-formed and bounded | encode_query checks |
a_query_round_trips_through_its_own_encoder, a_trailing_dot_encodes_the_same_as_without, rejects_an_over_long_name_and_label |
| An HTTP error from a DoH server is an error, not an answer | the status-line check in exchange_https_over |
doh_surfaces_an_http_error |
| A server whose certificate chains to neither the configured CA nor a system root fails the handshake | chain verification under VerifyMode::CustomCa |
a_resolver_pinned_to_the_wrong_ca_is_refused |
| One failed family does not discard the other | query_both returns an error only when no address came back |
the_udp_backend_is_used_for_resolution: its fake server answers A with an address and AAAA with NXDOMAIN (RCODE 3) |
| The configured backend is what etemenanki-app uses | lower_single_dns → Backend::from_spec, then build_dns |
the_udp_backend_is_used_for_resolution with its negative control the_default_backend_does_not_know_the_test_name |
| Hosts entries are read as a system resolver reads them: aliases, comments, case, trailing dots, merged lines, skipped bad lines | Hosts::parse, Hosts::get |
names_aliases_comments_and_case_are_read_as_a_system_resolver_would |
| A relayed response reaches the client untouched | relay returns the bytes; respond passes them on |
a_query_is_relayed_and_its_response_handed_back_untouched (the fake server sets the AD bit, which must survive) |
| A withheld AAAA is answered empty without asking a server | the ipv6 check in respond |
withheld_aaaa_is_an_empty_answer_without_asking_anyone |
| Hosts entries answer before any server, case-insensitively | the hosts check in respond |
the_hosts_entries_answer_before_any_server |
Over UDP, answer replaces a response longer than the client’s udp_limit with a truncated one; over TCP it does not truncate |
udp_limit and encode_truncated in answer |
an_oversized_udp_response_is_truncated_but_tcp_gets_it_whole (40 A records) |
| A dead server is skipped for the next | relay moves on after an error |
a_dead_server_is_skipped_for_the_next |
| Bytes that are not a query, including a response, get no reply | decode_query failing in answer |
garbage_gets_no_reply |
The app lowers [dns] to Single and a subscribe [dns] to Split |
app/src/lower.rs → lower_dns |
a_dns_backend_needs_what_it_names, a_subscribe_file_splits_dns |
Behaviours with no dedicated test:
- Two successful answers with no address records. Every fake server answers A with an address, and the negative tests make both queries fail, so the path where both succeed empty and
resolve_with_ttlreturnsdns: <host> did not resolveis not exercised. - The retry over TCP after a truncated UDP response. No fake server sets the TC bit; the service test’s 40-record answer fits
RELAY_UDP_BUF. - Exchanges through a
StreamDialer, and a named server looked up through a bootstrap at query time. The tests cover only the construction-time refusal. - The DoH
Connection: closeheader. The DoH test server asserts the request line,Content-TypeandHost, but notConnection. - Case-insensitive cache keys. No test resolves the same name in two spellings.
NOTIMP, and the own lookup when the resolver has no server a query can be relayed to. The supervisor’sdns_outbound.rstests build a service with hosts entries and no servers, but every name they ask is in the hosts table, so they are answered beforerelayis reached.Hosts::system, which reads the real hosts file.
Failure paths and cancellation
Section titled “Failure paths and cancellation”resolve returns io::Result, and callers such as resolve_candidates pass the error up unchanged. What happens to the connection then belongs to the outbound. The messages below start with dns: , except the ProtocolError and TLS ones.
When a backend or resolver is built
Section titled “When a backend or resolver is built”| Stage | Message | io::ErrorKind |
|---|---|---|
from_spec |
dns: the udp backend needs a server address (also tls, https) |
InvalidInput |
from_spec |
dns: invalid server address: invalid socket address syntax |
InvalidInput |
from_spec |
dns: the tls backend needs a server name to verify against |
InvalidInput |
from_spec |
dns: the https backend needs the resolver's url |
InvalidInput |
from_spec |
dns: unknown backend "<name>" (expected "system", "udp", "tls" or "https") |
InvalidInput |
Backend::https |
dns: "…" is not an https:// url, … has no usable host, … has no host, … has an invalid port, … has an unclosed [, … has junk after ] |
InvalidInput |
from_url |
dns: server "<url>": <why>, as listed under Backend::from_url |
InvalidInput |
with_upstreams |
dns: the system resolver cannot be reached through a proxy |
InvalidInput |
with_upstreams |
dns: server "<host>" is a name, and nothing resolves it; write its address |
InvalidInput |
Upstream::new |
no certificate in CA PEM bundle |
InvalidInput |
Upstream::new |
an OpenSSL error, for example error:04800064:PEM routines:PEM_read_bio_ex:bad base64 decode:../crypto/pem/pem_lib.c:968: for a certificate block that does not decode; the exact text depends on the OpenSSL build (system or vendored-openssl) |
Other |
Hosts::system |
the OS error for a hosts file that exists but cannot be read | as returned by the standard library |
When a name is resolved or a query relayed
Section titled “When a name is resolved or a query relayed”| Stage | Message | io::ErrorKind |
|---|---|---|
resolve_with_ttl |
dns: <host> did not resolve |
NotFound |
lookup |
dns: <host> is not in the hosts file and no server is configured |
NotFound |
lookup_system |
the host resolver’s error, passed through from tokio::net::lookup_host |
as returned by the standard library |
encode_query |
dns: name too long (<n> bytes), dns: label longer than 63 |
InvalidInput |
exchange |
dns: query timed out |
TimedOut |
exchange |
socket, connect, hook or TLS errors | as returned by tokio, the socket policy and OpenSSL |
exchange_framed |
dns: query too long |
InvalidInput |
server_addr |
the bootstrap’s error, unchanged | as returned |
exchange through the supervisor’s RoutedDialer |
dns: the supervisor this resolver dials through is gone, and the errors of the route target’s dial; see Name resolution and the DNS service |
NotConnected for the first |
decode_answer |
dns: response id <got> does not match query <id>, dns: not a response |
InvalidData |
decode_answer |
dns: server returned rcode <n> (SERVFAIL is 2, NXDOMAIN is 3) |
NotFound |
decode_answer |
truncated input: dns name, … dns label type, … dns name pointer chain, … dns rdata, … fixed-size field |
UnexpectedEof |
decode_answer |
integer overflow: dns name, … dns question, … dns rr, … dns rdata, … field offset |
InvalidData |
exchange_https_over |
dns: no http header, dns: doh server answered "<status line>" |
InvalidData |
relay |
dns: query shorter than its id, dns: relayed response does not match the query id |
InvalidData |
relay |
dns: no server that a query can be relayed to |
Unsupported |
resolve_candidates |
<context>: destination did not resolve (a guard that Resolver::resolve never triggers) |
NotFound |
resolve_candidates |
<context>: no usable <strategy> destination address for <remote>:<port>, with the family clause described in From addresses to dial candidates |
AddrNotAvailable |
The DNS service turns none of these into an error of its own. An undecodable query gets None, and every other outcome is a DNS response, as The DNS service lists. The only log lines in the module are the service’s two debug lines, dns service: dropping an undecodable query: <error> and dns service: <name> failed: <error>, both with target etemenanki_protocols::dns::serve.
What the front ends print
Section titled “What the front ends print”Build errors reach the front ends as io::Error from lowering or as ApplyError from the supervisor. etemenanki-app logs them with target etemenanki_app at start and under --test, and with target etemenanki_app::instance on reload. These --test lines were captured with the pinned binary:
| Mistake | Line |
|---|---|
backend = "udp" without server |
configuration invalid: dns: the udp backend needs a server address |
server written as a name, or without a port |
configuration invalid: dns: invalid server address: invalid socket address syntax |
backend = "UDP" |
configuration invalid: dns: unknown backend "UDP" (expected "system", "udp", "tls" or "https") |
url = "https://[2001:db8::53/dns-query" |
configuration invalid: dns: "…" has an unclosed [ |
ca_file that does not exist |
configuration invalid: dns: cannot read ca_file "/etc/etemenanki/missing-ca.pem": No such file or directory (os error 2) |
ca_file with no certificate in it |
configuration invalid: building dns failed: no certificate in CA PEM bundle |
Subscribe URL udp://192.0.2.53#x |
configuration invalid: dns: server "udp://192.0.2.53#x": a udp server has no name to verify |
Subscribe through_proxy = ["system"] |
configuration invalid: building dns failed: dns: the system resolver cannot be reached through a proxy |
Subscribe pre_proxy = ["tls://dns.example.com"] |
configuration invalid: building dns failed: dns: server "dns.example.com" is a name, and nothing resolves it; write its address |
At start the same errors print as failed to start: <error> (app/src/main.rs), and on reload as reload: <error>; keeping the running config (app/src/instance.rs). The reload path is on etemenanki-app: running, reloading and shutting down.
katana’s --test prints configuration error: node <node_id>: <error> to standard error (src/main.rs, src/runtime.rs → test_config), for example configuration error: node 1: dns: the udp backend needs a server address with the pinned binary. On reload, a node that fails the check is logged as reload: node <node>: <error>; keeping current config, and nothing of the new config is applied.
Cancellation
Section titled “Cancellation”- The resolver spawns no task.
resolveandrelayare plain futures. Dropping one drops thejoin!of both queries, the bootstrap lookup, the sockets, TLS streams, dialer futures and timers inside. A lookup cancelled before it finishes inserts nothing into the cache. getaddrinfocannot be cancelled.tokio::net::lookup_hostruns it on the blocking pool. Dropping the future stops waiting for it, but the call finishes on its thread and its result is discarded.- The cache has no background worker. moka’s
future::Cachedoes its housekeeping insidegetandinsertcalls, so nothing outlives the resolver. - A resolver lives as long as a clone. In a supervisor, clones are held by the actor’s running DNS setup, the outbounds and balancer probes built with it, and the DNS service, and, for a
Splitspec, by the through-proxy resolver, whose bootstrap is the direct one.RoutedDialerholds only a weak reference to the plane. Its doc comment names the cycle this breaks: the plane owns, through its outbounds, the resolver that owns the dialer; the DNS service’s target in the plane is a second such path. - The service spawns nothing either.
Service::answerruns inside the task that polls it, usually a connection’s runtime through the supervisor’s DNS outbound.
Timeout scope
Section titled “Timeout scope”QUERY_TIMEOUT(5 s) applies to each exchange: each A or AAAA query to one server, and each relay attempt to one server. The resolver’s own work in an exchange counts against it: the bootstrap lookup of a named server, the local socket and TCP connect of a resolver without a dialer, the resolver’s own DoT or DoH handshake, the retry over TCP after a truncated UDP response, and reading the response.- The A and AAAA queries run concurrently, so one server takes at most about
QUERY_TIMEOUT.lookupandrelaytry servers one after another, so a resolver whose servers all time out takes about oneQUERY_TIMEOUTper server. - The
Systembackend is not wrapped inQUERY_TIMEOUT. It takes as long as the host resolver’s own timeout and retry settings allow.
Limits
Section titled “Limits”| Name | Value | Where | Effect |
|---|---|---|---|
CACHE_CAPACITY |
8192 entries | dns/mod.rs |
moka max_capacity. moka enforces it during its housekeeping, so the entry count can briefly run past it. |
MIN_TTL |
5 s | dns/mod.rs |
floor for every server TTL, so a zero-TTL answer is still cached briefly |
MAX_TTL |
3600 s | dns/mod.rs |
ceiling for every server TTL, moka’s per-cache time_to_live backstop, and the TTL returned for an address literal |
SYSTEM_TTL |
60 s | dns/mod.rs |
TTL assumed for getaddrinfo answers, and given to hosts entries |
QUERY_TIMEOUT |
5 s | dns/mod.rs |
per exchange with one server |
UDP_BUF |
512 bytes | dns/mod.rs |
UDP receive buffer for the resolver’s own queries |
RELAY_UDP_BUF |
65535 bytes | dns/mod.rs |
UDP receive buffer for relayed client queries |
HEADER_LEN |
12 bytes | dns/message.rs |
fixed DNS header |
MAX_NAME_LEN |
255 | dns/message.rs |
longest name encode_query and decode_query accept (textual length) |
| label length | 63 bytes | dns/message.rs |
longest single label, encoded or read from a question |
MAX_POINTER_HOPS |
16 | dns/message.rs |
the most iterations one skip_name call makes |
CLASSIC_UDP_LIMIT |
512 bytes | dns/message.rs |
smallest UDP answer size the service assumes a client takes |
RR_FIXED_LEN |
12 bytes | dns/message.rs |
per-record overhead used for the answer’s capacity hint |
| DNS-over-TCP length prefix | u16 |
dns/mod.rs → exchange_framed |
largest message over TCP or TLS is 65535 bytes |
| TLS versions | 1.2 and newer | transports/tls/config.rs |
set by with_verify_mode |
DEFAULT_CONNECT_TIMEOUT |
10 s | environment/src/dial/tcp.rs |
the local TCP dialer’s per-connect timeout, longer than QUERY_TIMEOUT |
The supervisor’s DNS outbound, which carries the service’s queries and answers, has limits of its own; they are on Name resolution and the DNS service.
| File | What it covers |
|---|---|
protocols/tests/unit/dns/mod.rs |
Resolver against an in-process UDP server that answers A with one address and AAAA with nothing, and counts queries: literals, cache hits, shared clones, the capacity bound, expiry, an unreachable server, the socket policy hook, from_spec refusals, Backend::https splitting, every from_url form, the bootstrap refusal, and the default backend resolving localhost |
protocols/tests/unit/dns/message.rs |
The response codec: round trip, trailing dot, A and AAAA decoding, smallest TTL, CNAME skipping, ID, QR and RCODE rejection, every truncation point, an RDLENGTH past the end, a self-referencing pointer, over-long names and labels |
protocols/tests/unit/dns/hosts.rs |
names_aliases_comments_and_case_are_read_as_a_system_resolver_would |
protocols/tests/unit/dns/serve.rs |
Service against an in-process UDP upstream that answers with a chosen number of A records and sets the AD bit: relaying, withheld AAAA, hosts entries, UDP truncation versus TCP, a dead first server, garbage and responses getting no reply |
protocols/tests/pipeline/dns_secure.rs |
DoT and DoH against a real OpenSSL server whose self-signed certificate (protocols/tests/support/mod.rs → self_signed_pem, CN and SAN localhost) is passed as ca_pem: dot_resolves_over_tls, doh_resolves_over_https, doh_surfaces_an_http_error, a_resolver_pinned_to_the_wrong_ca_is_refused |
supervisor/tests/unit/dns_outbound.rs |
The service as the supervisor carries it: tcp_answers_pipelined_queries_in_order_then_ends, udp_answers_from_the_address_asked, over a service built from hosts entries and no servers |
app/tests/unit/lower.rs |
a_dns_backend_needs_what_it_names (a tls backend without server_name is refused; udp lowers to Single(Backend::Udp(..))), a_subscribe_file_splits_dns |
app/tests/integration/e2e_dns.rs |
The built etemenanki-app binary behind a SOCKS inbound: a name only the fake UDP server (app/tests/support/mod.rs → fake_dns) knows resolves with backend = "udp" and fails with the default backend; backend = "udp" without server fails --test |
The unit tests are compiled into their crate’s library through #[path] modules, so they run with the lib tests:
cargo test -p etemenanki-protocols --lib dns::cargo test -p etemenanki-protocols --test pipeline dns_securecargo test -p etemenanki-supervisor --lib outbound::dns::cargo test -p etemenanki-app --lib -- a_subscribe_file_splits_dns a_dns_backend_needs_what_it_namescargo test -p etemenanki-app --test integration e2e_dnsan_expired_entry_is_looked_up_again uses real time rather than a paused clock. Its comment explains that a paused runtime auto-advances while waiting on the real socket, which would trip QUERY_TIMEOUT before the TTL. A move of the DNS tests to tokio::time::pause has to account for that.
A codec change needs a malformed-input case next to truncated_and_malformed_input_never_panics. A transport change belongs in dns_secure.rs: a live server is the only place where framing, the handshake and header handling are exercised together. A service change is the occasion to add the missing NOTIMP case, and the own lookup of a resolver with no relayable server, to serve.rs. See Testing for how the suites are laid out.