From ff919070575473b46f47e0ec206bcdde585b4b1a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:30:32 +0200 Subject: [PATCH] SRV redirects: ask the name servers directly instead of hickory + tokio Vanilla's ServerRedirectHandler asks through JNDI's DNS client: the system's name servers in turn, one 1 s UDP try each (retries = 1), TCP when the reply is truncated, the first SRV record of the answer. resolver/dns.rs does that by hand in ~200 lines with wire-format tests and a local stub server, so the game, the dedicated server and the bots no longer pull in tokio, hickory and ~25 other crates (none of them were in the game before). Name servers come from resolv.conf on Unix, as JNDI reads them, and from the network adapters on Windows (ipconfig, Windows only; the crate keeps forbid(unsafe_code)). Each server waits 1 s, as vanilla does, instead of the whole connect timeout. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 238 +------------- crates/horizon-protocol/Cargo.toml | 7 +- crates/horizon-protocol/src/connection.rs | 2 +- crates/horizon-protocol/src/resolver.rs | 65 ++-- crates/horizon-protocol/src/resolver/dns.rs | 339 ++++++++++++++++++++ 5 files changed, 370 insertions(+), 281 deletions(-) create mode 100644 crates/horizon-protocol/src/resolver/dns.rs diff --git a/Cargo.lock b/Cargo.lock index 1f0958f95..523812b5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -187,17 +187,6 @@ dependencies = [ "libloading", ] -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - [[package]] name = "atomic-waker" version = "1.1.2" @@ -710,30 +699,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "critical-section" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" - -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -753,7 +718,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", + "rand_core", "typenum", ] @@ -773,7 +738,7 @@ dependencies = [ "cpufeatures", "curve25519-dalek-derive", "fiat-crypto", - "rand_core 0.6.4", + "rand_core", "rustc_version", "subtle", ] @@ -795,12 +760,6 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" -[[package]] -name = "data-encoding" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" - [[package]] name = "derive_arbitrary" version = "1.5.0" @@ -912,18 +871,6 @@ dependencies = [ "simdutf8", ] -[[package]] -name = "enum-as-inner" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "equivalent" version = "1.0.2" @@ -1044,27 +991,12 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", -] - [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - [[package]] name = "futures-task" version = "0.3.34" @@ -1256,52 +1188,6 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" -[[package]] -name = "hickory-proto" -version = "0.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502" -dependencies = [ - "async-trait", - "cfg-if", - "data-encoding", - "enum-as-inner", - "futures-channel", - "futures-io", - "futures-util", - "idna", - "ipnet", - "once_cell", - "rand", - "ring", - "thiserror 2.0.21", - "tinyvec", - "tokio", - "tracing", - "url", -] - -[[package]] -name = "hickory-resolver" -version = "0.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a" -dependencies = [ - "cfg-if", - "futures-util", - "hickory-proto", - "ipconfig", - "moka", - "once_cell", - "parking_lot", - "rand", - "resolv-conf", - "smallvec", - "thiserror 2.0.21", - "tokio", - "tracing", -] - [[package]] name = "hidapi" version = "2.6.7" @@ -1489,13 +1375,12 @@ version = "0.1.0" dependencies = [ "flate2", "getrandom 0.3.4", - "hickory-resolver", "horizon-core", "horizon-world", + "ipconfig", "serde_json", "sha1", "sha2", - "tokio", ] [[package]] @@ -1782,12 +1667,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "ipnet" -version = "2.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" - [[package]] name = "itertools" version = "0.14.0" @@ -2052,34 +1931,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "mio" -version = "1.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "moka" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" -dependencies = [ - "crossbeam-channel", - "crossbeam-epoch", - "crossbeam-utils", - "equivalent", - "parking_lot", - "portable-atomic", - "smallvec", - "tagptr", - "uuid", -] - [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -2579,10 +2430,6 @@ name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -dependencies = [ - "critical-section", - "portable-atomic", -] [[package]] name = "opaque-debug" @@ -2786,15 +2633,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - [[package]] name = "presser" version = "0.3.1" @@ -2888,26 +2726,6 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" -[[package]] -name = "rand" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" -dependencies = [ - "rand_chacha", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - [[package]] name = "rand_core" version = "0.6.4" @@ -2917,15 +2735,6 @@ dependencies = [ "getrandom 0.2.17", ] -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - [[package]] name = "range-alloc" version = "0.1.5" @@ -3026,12 +2835,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" -[[package]] -name = "resolv-conf" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" - [[package]] name = "ring" version = "0.17.14" @@ -3366,7 +3169,7 @@ checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a" dependencies = [ "curve25519-dalek", "hkdf", - "rand_core 0.6.4", + "rand_core", "sha2", ] @@ -3507,12 +3310,6 @@ dependencies = [ "syn 3.0.6", ] -[[package]] -name = "tagptr" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" - [[package]] name = "target-lexicon" version = "0.13.5" @@ -3603,36 +3400,13 @@ dependencies = [ "zerovec", ] -[[package]] -name = "tinyvec" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" - [[package]] name = "tokio" version = "1.53.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" dependencies = [ - "bytes", - "libc", - "mio", "pin-project-lite", - "socket2 0.6.5", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", ] [[package]] @@ -3702,9 +3476,6 @@ name = "tracing-core" version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] [[package]] name = "tree_magic_mini" @@ -3814,7 +3585,6 @@ version = "1.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" dependencies = [ - "getrandom 0.4.3", "js-sys", "wasm-bindgen", ] diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml index ae9049e2c..90a85cbf5 100644 --- a/crates/horizon-protocol/Cargo.toml +++ b/crates/horizon-protocol/Cargo.toml @@ -16,9 +16,10 @@ getrandom = "0.3" sha1 = "0.10" # Secure chat: SHA256withRSA message signatures. sha2 = "0.10" -# Minecraft SRV redirects, using the system DNS configuration. -hickory-resolver = "0.25.2" -tokio = { version = "1", features = ["rt", "time"] } + +# The name servers of Windows' network adapters, for Minecraft SRV redirects. +[target.'cfg(windows)'.dependencies] +ipconfig = "0.3.4" # Its own name, not `probe`: Cargo copies every crate's examples into one target//examples. [[example]] diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs index 7cd7083dd..e89ce5de1 100644 --- a/crates/horizon-protocol/src/connection.rs +++ b/crates/horizon-protocol/src/connection.rs @@ -196,7 +196,7 @@ impl Connection { /// Minecraft's SRV redirect applies to the socket destination only. Callers /// keep the player's original host and port in the protocol handshake. pub fn connect_server(host: &str, port: u16, timeout: Duration) -> Result { - let addrs = crate::resolver::resolve(host, port, timeout)?; + let addrs = crate::resolver::resolve(host, port)?; Self::connect_addresses(host, addrs, timeout) } fn connect_addresses( diff --git a/crates/horizon-protocol/src/resolver.rs b/crates/horizon-protocol/src/resolver.rs index 3a76578ec..6cd2eca57 100644 --- a/crates/horizon-protocol/src/resolver.rs +++ b/crates/horizon-protocol/src/resolver.rs @@ -1,65 +1,44 @@ //! Minecraft server DNS redirects (`ServerRedirectHandler` / `ServerNameResolver`). -//! Only the default port uses SRV; no record or a failed query leaves the -//! original address in use. The protocol handshake still uses that address. +//! Port 25565 asks for `_minecraft._tcp.`'s SRV record; no record or a +//! failed query leaves the original address in use. The protocol handshake +//! still uses that original address. use crate::{Error, Result}; -use std::{ - net::{IpAddr, SocketAddr, ToSocketAddrs}, - time::Duration, -}; +use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; -pub(crate) fn resolve(host: &str, port: u16, timeout: Duration) -> Result> { - resolve_with( - host, - port, - |name| srv_redirect(name, timeout), - |host, port| { - (host, port) - .to_socket_addrs() - .map(|addrs| addrs.collect()) - .map_err(|e| Error::new(format!("Unknown host {host}: {e}"))) - }, - ) +mod dns; + +pub(crate) fn resolve(host: &str, port: u16) -> Result> { + resolve_with(host, port, srv_redirect, |host, port| { + (host, port) + .to_socket_addrs() + .map(|addrs| addrs.collect()) + .map_err(|e| Error::new(format!("Unknown host {host}: {e}"))) + }) } fn resolve_with( host: &str, port: u16, - mut srv: impl FnMut(&str) -> Option<(String, u16)>, - mut addresses: impl FnMut(&str, u16) -> Result>, + srv: impl FnOnce(&str) -> Option<(String, u16)>, + addresses: impl FnOnce(&str, u16) -> Result>, ) -> Result> { + // Vanilla also asks for `_minecraft._tcp.127.0.0.1`, which never has a + // record: IP literals and localhost skip the query. if port == 25565 && host.parse::().is_err() && host != "localhost" && let Some((target, target_port)) = srv(&format!("_minecraft._tcp.{}.", host.trim_end_matches('.'))) { - // Do not follow another SRV record at the target. Vanilla resolves its - // addresses directly, and does not fall back if the target is unknown. + // No second SRV lookup at the target, and no fallback to the original + // host when the target is unknown. return addresses(&target, target_port); } addresses(host, port) } -fn srv_redirect(name: &str, timeout: Duration) -> Option<(String, u16)> { - // Runs only on the blocking ping/login worker, never the render thread. - // Use the system's configured resolvers, not a public fallback. - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .ok()?; - runtime.block_on(async { - let mut builder = hickory_resolver::TokioResolver::builder_tokio().ok()?; - builder.options_mut().attempts = 1; - builder.options_mut().timeout = timeout; - let resolver = builder.build(); - let records = tokio::time::timeout(timeout, resolver.srv_lookup(name)) - .await - .ok()? - .ok()?; - // ServerRedirectHandler uses the first record, not weighted balancing. - let record = records.iter().next()?; - Some((record.target().to_utf8(), record.port())) - }) +fn srv_redirect(name: &str) -> Option<(String, u16)> { + dns::query_srv(name, &dns::system_name_servers(), dns::SERVER_TIMEOUT) } #[cfg(test)] @@ -157,7 +136,7 @@ mod tests { let connection = crate::connection::Connection::connect_server( "127.0.0.1", address.port(), - Duration::from_secs(1), + std::time::Duration::from_secs(1), ) .unwrap(); let (accepted, _) = listener.accept().unwrap(); diff --git a/crates/horizon-protocol/src/resolver/dns.rs b/crates/horizon-protocol/src/resolver/dns.rs new file mode 100644 index 000000000..a91156a77 --- /dev/null +++ b/crates/horizon-protocol/src/resolver/dns.rs @@ -0,0 +1,339 @@ +//! The SRV question as JNDI's DNS client asks it: the system's name servers in +//! turn, one UDP try of 1 s (`com.sun.jndi.dns.timeout.retries` = 1), TCP when +//! the reply is truncated, and the answer's first SRV record. By hand, so the +//! game needs no async runtime or resolver library for one question. +use std::{ + io::{Read, Write}, + net::{SocketAddr, TcpStream, UdpSocket}, + time::Duration, +}; + +const TYPE_SRV: u16 = 33; +/// JNDI's `com.sun.jndi.dns.timeout.initial`, per name server. +pub(super) const SERVER_TIMEOUT: Duration = Duration::from_secs(1); + +/// JNDI reads them from resolv.conf on Unix and from the network adapters on +/// Windows. +#[cfg(unix)] +pub(super) fn system_name_servers() -> Vec { + std::fs::read_to_string("/etc/resolv.conf") + .map_or_else(|_| Vec::new(), |conf| name_servers(&conf)) +} + +#[cfg(windows)] +pub(super) fn system_name_servers() -> Vec { + let mut servers = Vec::new(); + for adapter in ipconfig::get_adapters().unwrap_or_default() { + if adapter.oper_status() != ipconfig::OperStatus::IfOperStatusUp { + continue; + } + for &ip in adapter.dns_servers() { + let server = SocketAddr::new(ip, 53); + if !servers.contains(&server) { + servers.push(server); + } + } + } + servers +} + +#[cfg(not(any(unix, windows)))] +pub(super) fn system_name_servers() -> Vec { + Vec::new() +} + +/// `nameserver` lines of resolv.conf, in order. +#[cfg(any(unix, test))] +fn name_servers(conf: &str) -> Vec { + conf.lines() + .filter_map(|line| line.strip_prefix("nameserver")) + .filter_map(|rest| rest.split_whitespace().next()) + .filter_map(|ip| ip.split('%').next()?.parse::().ok()) + .map(|ip| SocketAddr::new(ip, 53)) + .collect() +} + +enum Reply { + /// The server answered: the first SRV record, if any. + Answer(Option<(String, u16)>), + Truncated, + /// No reply, a server failure or a malformed reply: ask the next server. + Unusable, +} + +pub(super) fn query_srv( + name: &str, + servers: &[SocketAddr], + timeout: Duration, +) -> Option<(String, u16)> { + let mut id = [0; 2]; + getrandom::fill(&mut id).ok()?; + let id = u16::from_be_bytes(id); + let query = encode_query(id, name)?; + for &server in servers { + let reply = match ask_udp(server, &query, timeout).map(|reply| parse_reply(id, &reply)) { + Some(Reply::Truncated) => ask_tcp(server, &query, timeout) + .map_or(Reply::Unusable, |reply| parse_reply(id, &reply)), + reply => reply.unwrap_or(Reply::Unusable), + }; + if let Reply::Answer(srv) = reply { + return srv; + } + } + None +} + +fn ask_udp(server: SocketAddr, query: &[u8], timeout: Duration) -> Option> { + let local: SocketAddr = if server.is_ipv4() { + ([0, 0, 0, 0], 0).into() + } else { + ([0u16; 8], 0).into() + }; + let socket = UdpSocket::bind(local).ok()?; + socket.set_read_timeout(Some(timeout)).ok()?; + socket.connect(server).ok()?; + socket.send(query).ok()?; + let mut buf = vec![0; 512]; + let len = socket.recv(&mut buf).ok()?; + buf.truncate(len); + Some(buf) +} + +fn ask_tcp(server: SocketAddr, query: &[u8], timeout: Duration) -> Option> { + let mut stream = TcpStream::connect_timeout(&server, timeout).ok()?; + stream.set_read_timeout(Some(timeout)).ok()?; + let mut framed = (query.len() as u16).to_be_bytes().to_vec(); + framed.extend_from_slice(query); + stream.write_all(&framed).ok()?; + let mut len = [0; 2]; + stream.read_exact(&mut len).ok()?; + let mut buf = vec![0; u16::from_be_bytes(len) as usize]; + stream.read_exact(&mut buf).ok()?; + Some(buf) +} + +/// A recursive SRV question (RFC 1035 ยง4.1) for an absolute name. +fn encode_query(id: u16, name: &str) -> Option> { + let mut msg = Vec::with_capacity(18 + name.len()); + msg.extend_from_slice(&id.to_be_bytes()); + msg.extend_from_slice(&[0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0]); // RD; one question + for label in name.trim_end_matches('.').split('.') { + if label.is_empty() || label.len() > 63 { + return None; + } + msg.push(label.len() as u8); + msg.extend_from_slice(label.as_bytes()); + } + msg.push(0); + if msg.len() - 12 > 255 { + return None; + } + msg.extend_from_slice(&TYPE_SRV.to_be_bytes()); + msg.extend_from_slice(&1u16.to_be_bytes()); // IN + Some(msg) +} + +fn parse_reply(id: u16, msg: &[u8]) -> Reply { + parse_answer(id, msg).unwrap_or(Reply::Unusable) +} + +fn parse_answer(id: u16, msg: &[u8]) -> Option { + let u16_at = |at: usize| Some(u16::from_be_bytes([*msg.get(at)?, *msg.get(at + 1)?])); + let flags = u16_at(2)?; + if u16_at(0)? != id || flags & 0x8000 == 0 { + return None; + } + if flags & 0x0200 != 0 { + return Some(Reply::Truncated); + } + match flags & 0xf { + 0 => {} + 3 => return Some(Reply::Answer(None)), // NXDOMAIN + _ => return None, + } + let mut at = 12; + for _ in 0..u16_at(4)? { + at = read_name(msg, at)?.1 + 4; + } + for _ in 0..u16_at(6)? { + at = read_name(msg, at)?.1; + let (kind, len) = (u16_at(at)?, u16_at(at + 8)? as usize); + let data = at + 10; + msg.get(data..data + len)?; + if kind == TYPE_SRV && len >= 7 { + let (target, _) = read_name(msg, data + 6)?; + return Some(Reply::Answer(Some((target, u16_at(data + 4)?)))); + } + at = data + len; + } + Some(Reply::Answer(None)) +} + +/// The name at `at`, absolute (`a.b.`), and where the record continues. +fn read_name(msg: &[u8], mut at: usize) -> Option<(String, usize)> { + let mut name = String::new(); + let mut end = None; + // Pointers must go backwards; the bound ends a loop of labels and pointers. + for _ in 0..128 { + let len = *msg.get(at)? as usize; + match len { + 0 => { + if name.is_empty() { + name.push('.'); + } + return Some((name, end.unwrap_or(at + 1))); + } + 0xc0.. => { + let target = (len & 0x3f) << 8 | *msg.get(at + 1)? as usize; + if target >= at { + return None; + } + end.get_or_insert(at + 2); + at = target; + } + 1..=63 => { + let label = msg.get(at + 1..at + 1 + len)?; + name.push_str(std::str::from_utf8(label).ok()?); + name.push('.'); + at += 1 + len; + } + _ => return None, + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + const NAME: &str = "_minecraft._tcp.play.example.org."; + + /// The reply a server gives to `query`: its question, then a CNAME and the + /// SRV records, each owner name compressed to the question's name. + fn reply(query: &[u8], rcode: u8, records: &[(u16, &str)]) -> Vec { + let mut msg = query.to_vec(); + msg[2] |= 0x80; + msg[3] = 0x80 | rcode; + let answers = records.len() as u16 + u16::from(!records.is_empty()); + msg[6..8].copy_from_slice(&answers.to_be_bytes()); + if !records.is_empty() { + // CNAME first: the parser must step over records of other types. + msg.extend_from_slice(&[0xc0, 12, 0, 5, 0, 1, 0, 0, 0, 60, 0, 2, 0xc0, 12]); + } + for &(port, target) in records { + let mut rdata = vec![0, 1, 0, 1]; + rdata.extend_from_slice(&port.to_be_bytes()); + for label in target.trim_end_matches('.').split('.') { + rdata.push(label.len() as u8); + rdata.extend_from_slice(label.as_bytes()); + } + rdata.push(0); + msg.extend_from_slice(&[0xc0, 12, 0, 33, 0, 1, 0, 0, 0, 60]); + msg.extend_from_slice(&(rdata.len() as u16).to_be_bytes()); + msg.extend_from_slice(&rdata); + } + msg + } + + fn answer(msg: &[u8]) -> Option> { + match parse_reply(7, msg) { + Reply::Answer(srv) => Some(srv), + _ => None, + } + } + + #[test] + fn query_is_a_recursive_srv_question() { + let query = encode_query(0x1234, NAME).unwrap(); + let mut expected = vec![0x12, 0x34, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0]; + expected.extend_from_slice(b"\x0a_minecraft\x04_tcp\x04play\x07example\x03org\x00"); + expected.extend_from_slice(&[0, 33, 0, 1]); + assert_eq!(query, expected); + assert!(encode_query(1, "a..b.").is_none()); + assert!(encode_query(1, &format!("{}.org.", "a".repeat(64))).is_none()); + } + + #[test] + fn first_srv_record_of_the_answer_wins() { + let query = encode_query(7, NAME).unwrap(); + let msg = reply( + &query, + 0, + &[(25570, "a.example.org."), (25571, "b.example.org.")], + ); + assert_eq!(answer(&msg), Some(Some(("a.example.org.".into(), 25570)))); + } + + #[test] + fn empty_answer_and_nxdomain_mean_no_redirect() { + let query = encode_query(7, NAME).unwrap(); + assert_eq!(answer(&reply(&query, 0, &[])), Some(None)); + assert_eq!(answer(&reply(&query, 3, &[])), Some(None)); + } + + #[test] + fn server_failures_and_bad_replies_ask_the_next_server() { + let query = encode_query(7, NAME).unwrap(); + let good = reply(&query, 0, &[(25570, "a.example.org.")]); + assert!(matches!( + parse_reply(7, &reply(&query, 2, &[])), + Reply::Unusable + )); + assert!(matches!(parse_reply(8, &good), Reply::Unusable)); // another id + assert!(matches!(parse_reply(7, &query), Reply::Unusable)); // not a response + for cut in 0..good.len() { + assert!(matches!(parse_reply(7, &good[..cut]), Reply::Unusable)); + } + let mut forward = good.clone(); + let at = query.len(); // the first answer's owner pointer + assert_eq!(forward[at..at + 2], [0xc0, 12]); + forward[at + 1] = 0xff; // a pointer forwards + assert!(matches!(parse_reply(7, &forward), Reply::Unusable)); + let mut truncated = good; + truncated[2] |= 0x02; + assert!(matches!(parse_reply(7, &truncated), Reply::Truncated)); + } + + #[test] + fn resolv_conf_name_servers_in_order() { + let conf = "# generated\nsearch lan\nnameserver 192.168.1.1\nnameserver fe80::1%en0\n\ + nameserver ::1 \nnameserver bogus\noptions ndots:1\n"; + let servers: Vec = name_servers(conf).iter().map(|s| s.to_string()).collect(); + assert_eq!(servers, ["192.168.1.1:53", "[fe80::1]:53", "[::1]:53"]); + } + + /// A local name server: a silent one first, then one that answers truncated + /// over UDP and in full over TCP, like a real server with a big answer. + #[test] + fn asks_each_server_in_turn_and_retries_truncated_replies_over_tcp() { + let silent = UdpSocket::bind("127.0.0.1:0").unwrap(); + let (udp, tcp) = loop { + let udp = UdpSocket::bind("127.0.0.1:0").unwrap(); + if let Ok(tcp) = std::net::TcpListener::bind(udp.local_addr().unwrap()) { + break (udp, tcp); + } + }; + let servers = [silent.local_addr().unwrap(), udp.local_addr().unwrap()]; + let server = std::thread::spawn(move || { + let mut buf = [0; 512]; + let (len, from) = udp.recv_from(&mut buf).unwrap(); + let mut truncated = reply(&buf[..len], 0, &[]); + truncated[2] |= 0x02; + udp.send_to(&truncated, from).unwrap(); + let (mut stream, _) = tcp.accept().unwrap(); + let mut len = [0; 2]; + stream.read_exact(&mut len).unwrap(); + let mut query = vec![0; u16::from_be_bytes(len) as usize]; + stream.read_exact(&mut query).unwrap(); + let full = reply(&query, 0, &[(25570, "backend.example.org.")]); + stream + .write_all(&(full.len() as u16).to_be_bytes()) + .unwrap(); + stream.write_all(&full).unwrap(); + }); + let srv = query_srv(NAME, &servers, Duration::from_millis(200)); + server.join().unwrap(); + assert_eq!(srv, Some(("backend.example.org.".into(), 25570))); + } +}