diff --git a/crates/proto/UPSTREAM.md b/crates/proto/UPSTREAM.md index e7aa7fb..faf3d63 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -82,3 +82,21 @@ against or offered back to upstream. tracing setup used `init`, which panics when quickcheck (`use_logging`) has already installed a `log` logger; the panic poisoned the `Lazy` and failed every later test of the binary, depending on test order. It uses `try_init` now. +11. **TSDNS without an SRV record, as the official client resolves** + (`tsclientlib/src/resolver.rs`). Without an SRV record at `_tsdns._tcp.` + the official client asks a TSDNS server directly on TCP 41144 at the address's + parent domains (`A/AAAA DNS resolve for possible TSDNS successful, "example.com"`, + `TSDNS found at :41144 and queried successfully` in its log); upstream went + straight to the address on port 9987, so servers published only through TSDNS + (on another port) could not be reached without typing the port. Now: SRV + `_ts3._udp.
`, then TSDNS (the servers `_tsdns._tcp` names, else the + ones at each parent domain down to the last two labels), then A/AAAA on 9987. + The steps start at once and come out in that order; each is given up after + 10 s, a TSDNS server after 3 s (connect and answer), so a port a firewall drops + does not stall connecting. A port typed with the address now overrides the port + of every result (the `_ts3._udp` one too). The TSDNS query sends the host + without the port, and the answer is trimmed. SRV records of weight 0, the + common weight, were dropped by the weighted ordering; they are kept now + (RFC 2782 order). A CNAME among the SRV answers no longer panics. The lookups + are injectable inside the module, and the tests use a fake TSDNS server and + fake names; the upstream tests that need DNS and the internet are `#[ignore]`d. diff --git a/crates/proto/tsclientlib/src/resolver.rs b/crates/proto/tsclientlib/src/resolver.rs index d6dea01..3fffaba 100644 --- a/crates/proto/tsclientlib/src/resolver.rs +++ b/crates/proto/tsclientlib/src/resolver.rs @@ -4,26 +4,32 @@ use std::net::{IpAddr, Ipv6Addr, SocketAddr}; use std::str; +use std::sync::Arc; +use futures::future::BoxFuture; use futures::prelude::*; use hickory_net::proto::rr::RData; use hickory_resolver::TokioResolver; use hickory_resolver::config::{CLOUDFLARE, ResolverConfig, ResolverOpts}; use hickory_resolver::net::runtime::TokioRuntimeProvider; -use itertools::Itertools; use rand::RngExt; use thiserror::Error; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{self, TcpStream}; -use tokio::time::Duration; +use tokio::time::{Duration, timeout}; use tracing::{debug, instrument, warn}; const DEFAULT_PORT: u16 = 9987; +/// Port a TSDNS server listens on. +const TSDNS_PORT: u16 = 41144; const DNS_PREFIX_TCP: &str = "_tsdns._tcp."; const DNS_PREFIX_UDP: &str = "_ts3._udp."; const NICKNAME_LOOKUP_ADDRESS: &str = "https://named.myteamspeak.com/lookup"; -/// Wait this amount of seconds before giving up. -const TIMEOUT_SECONDS: u64 = 10; +/// Give up on one way of resolving after this long. +const STEP_TIMEOUT: Duration = Duration::from_secs(10); +/// Give up on one TSDNS server (connecting and asking) after this long, so a +/// firewall that drops the port does not hold up connecting. +const TSDNS_TIMEOUT: Duration = Duration::from_secs(3); type Result = std::result::Result; @@ -68,129 +74,174 @@ enum ParseIpResult<'a> { /// Beware that this may be slow because it tries all available methods. /// -/// The following methods are tried: +/// The methods start at once and each is given up after a while (as the +/// official client does); their addresses come out in this order: /// 1. If the address is an ip, the ip is returned /// 1. Server nicknames are resolved by a http request to TeamSpeak /// 1. The SRV record at `_ts3._udp.
` -/// 1. The SRV record at `_tsdns._tcp.address.tld` to get the address of a tsdns -/// server, e.g. when the address is `ts3.subdomain.from.com`, the SRV record -/// at `_tsdns._tcp.from.com` is requested -/// 1. Directly resolve the address to an ip address +/// 1. A TSDNS server: the ones the SRV records at `_tsdns._tcp.address.tld` +/// name, e.g. when the address is `ts3.subdomain.from.com`, the SRV record +/// at `_tsdns._tcp.from.com` is requested; without such a record, the ones +/// on port 41144 at the address's parent domains (`subdomain.from.com`, +/// `from.com`). The first that knows the address answers. +/// 1. Directly resolve the address to an ip address, port 9987 /// -/// If a port is given with `:port`, it overwrites the automatically determined -/// port. IPv6 addresses are put in square brackets when a port is present: +/// If a port is given with `:port`, it overwrites the port of every address +/// found. IPv6 addresses are put in square brackets when a port is present: /// `[::1]:9987` #[instrument] pub fn resolve(address: String) -> impl Stream> { + resolve_with(address, Lookups::system()) +} + +type SrvFn = dyn Fn(String) -> BoxFuture<'static, Result>> + Send + Sync; +type HostFn = dyn Fn(String, u16) -> BoxFuture<'static, Result>> + Send + Sync; + +/// Where [`resolve`] gets its answers from; the tests put fakes in. +#[derive(Clone)] +struct Lookups { + /// The targets and ports of the SRV records at a name, in the order to + /// try them. + srv: Arc, + /// The addresses of a host name, with this port. + host: Arc, + tsdns_port: u16, + tsdns_timeout: Duration, +} + +impl Lookups { + fn system() -> Self { + Self { + srv: Arc::new(|name| srv_targets(name).boxed()), + host: Arc::new(|host, port| { + async move { + Ok(net::lookup_host((host.as_str(), port)) + .await + .map_err(Error::ResolveHost)? + .collect()) + } + .boxed() + }), + tsdns_port: TSDNS_PORT, + tsdns_timeout: TSDNS_TIMEOUT, + } + } +} + +fn resolve_with(address: String, lookups: Lookups) -> impl Stream> { debug!("Starting resolve"); - let addr; - let port; - match parse_ip(&address) { + let (host, port) = match parse_ip(&address) { Ok(ParseIpResult::Addr(res)) => { return stream::once(future::ok(res)).left_stream(); } - Ok(ParseIpResult::Other(a, p)) => { - addr = a.to_string(); - port = p; - if let Some(port) = port { - debug!(port, "Found port"); - } - } + Ok(ParseIpResult::Other(host, port)) => (host.trim_end_matches('.').to_string(), port), Err(res) => return stream::once(future::err(res)).left_stream(), + }; + if let Some(port) = port { + debug!(port, "Found port"); } - // Resolve as nickname - let res = if !address.contains('.') && addr != "localhost" { - debug!("Resolving nickname"); + let mut steps: Vec>>> = Vec::new(); + if !host.contains('.') && host != "localhost" { // Could be a server nickname - resolve_nickname(address.clone()) - .map_ok(move |mut addr| { - if let Some(port) = port { - addr.set_port(port); - } - addr - }) - .left_stream() - } else { - stream::once(future::err(Error::InvalidNickname)).right_stream() - }; + steps.push(resolve_nickname(host.clone()).try_collect().boxed()); + } + steps.push(srv_addresses(lookups.clone(), format!("{DNS_PREFIX_UDP}{host}.")).boxed()); + steps.push(tsdns(lookups.clone(), host.clone()).boxed()); + // Interpret as normal address + steps.push((lookups.host)(host, DEFAULT_PORT)); - // The system config does not yet work on android: - // https://github.com/bluejekyll/trust-dns/issues/652 - let addr2 = addr.clone(); - // TODO Move current span into stream - let res = res.chain( - stream::once(async move { - let resolver = create_resolver()?; - - // Try to get the address by an SRV record - Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_UDP}{addr2}."))) - }) - .try_flatten(), - ); - - // Try to get the address of a tsdns server by an SRV record - let addr2 = addr.clone(); - // TODO Move current span into stream - let res = res.chain( - stream::once(async move { - let resolver = create_resolver()?; - // Trim address to two components - let name = if let Some(i) = addr2.rfind('.').and_then(|i| addr2[..i].rfind('.')) { - &addr2[i + 1..] - } else { - &addr2 - }; - // Pick the first srv record of the first server that answers - Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_TCP}{name}.")).and_then( - move |srv| { - let address = address.clone(); - async move { - // Got tsdns server - let mut addr = resolve_tsdns(srv, &address).await?; - if let Some(port) = port { - // Overwrite port if it was specified - addr.set_port(port); - } - Ok(addr) - } - }, - )) - }) - .try_flatten(), - ); - - // Interpret as normal address and resolve with system resolver - let res = res.chain( - stream::once(async move { - let res = net::lookup_host((addr.as_str(), port.unwrap_or(DEFAULT_PORT))) - .await - .map_err(Error::ResolveHost)? - .map(Ok) - .collect::>(); - Result::<_>::Ok(stream::iter(res)) - }) - .try_flatten(), - ); - - // TODO Move current span into stream - tokio_stream::StreamExt::timeout(res, Duration::from_secs(TIMEOUT_SECONDS)) - .filter_map(move |r: std::result::Result, _>| { - future::ready(match r { - // Timeout - Err(_) => None, - // Error + let count = steps.len(); + stream::iter(steps) + .map(|step| timeout(STEP_TIMEOUT, step)) + // All at once, the addresses in the order of the steps. + .buffered(count) + .flat_map(|result| { + stream::iter(match result { + Ok(Ok(addresses)) => addresses, Ok(Err(error)) => { debug!(%error, "Resolver failed in one step"); - None + Vec::new() + } + Err(_) => { + debug!("Resolver step timed out"); + Vec::new() } - // Success - Ok(Ok(r)) => Some(Ok(r)), }) }) + .map(move |mut addr| { + if let Some(port) = port { + // A port the user gave wins. + addr.set_port(port); + } + Ok(addr) + }) .right_stream() } +/// The addresses of the targets of the SRV records at `name`, in their order. +async fn srv_addresses(lookups: Lookups, name: String) -> Result> { + let mut addresses = Vec::new(); + for (target, port) in (lookups.srv)(name).await? { + match (lookups.host)(target, port).await { + Ok(found) => addresses.extend(found), + Err(error) => debug!(%error, "SRV target not found"), + } + } + Ok(addresses) +} + +/// Where a TSDNS server for `host` may be, most specific first: the domains +/// above `host` down to the last two labels, or `host` itself when it has +/// only two (`ts.sub.example.com`: `sub.example.com`, `example.com`). +// ponytail: two labels as the floor instead of the public suffix list; under +// a `co.uk`-style suffix this also asks the suffix. +fn tsdns_domains(host: &str) -> Vec<&str> { + fn parent(name: &str) -> Option<&str> { name.split_once('.').map(|(_, parent)| parent) } + let mut domains: Vec<&str> = + std::iter::successors(parent(host), |d| parent(d)).filter(|d| d.contains('.')).collect(); + if domains.is_empty() && host.contains('.') { + domains.push(host); + } + domains +} + +/// The address a TSDNS server has for `host`. The servers are the ones the +/// SRV records at `_tsdns._tcp.` name or, without such records (as +/// the official client does), the ones on the TSDNS port at `host`'s domain +/// and its parents. They are asked at once; the first in that order that +/// knows `host` answers. +async fn tsdns(lookups: Lookups, host: String) -> Result> { + let domains = tsdns_domains(&host); + let Some(domain) = domains.last() else { return Ok(Vec::new()) }; + let mut servers = srv_addresses(lookups.clone(), format!("{DNS_PREFIX_TCP}{domain}.")) + .await + .unwrap_or_default(); + if servers.is_empty() { + let found = future::join_all( + domains.iter().map(|d| (lookups.host)(d.to_string(), lookups.tsdns_port)), + ) + .await; + servers = found.into_iter().filter_map(|r| r.ok()).flatten().collect(); + } + if servers.is_empty() { + return Ok(Vec::new()); + } + let count = servers.len(); + let mut answers = stream::iter(servers) + .map(|server| timeout(lookups.tsdns_timeout, resolve_tsdns(server, &host))) + .buffered(count); + let mut error = Error::TsdnsAddressNotFound; + while let Some(answer) = answers.next().await { + match answer { + Ok(Ok(address)) => return Ok(vec![address]), + Ok(Err(e)) => error = e, + Err(_) => error = Error::Io("tsdns", std::io::ErrorKind::TimedOut.into()), + } + } + Err(error) +} + // Windows for some reason automatically adds a link-local address to the dns // resolver. These addresses are usually not reachable and should be filtered out. // See: https://superuser.com/questions/638566/strange-value-in-dns-shown-in-ipconfig @@ -330,7 +381,7 @@ pub async fn resolve_tsdns(server: A, addr: &str) -> Resu let mut data = Vec::new(); stream.read_to_end(&mut data).await.map_err(|e| Error::Io("tsdns", e))?; - let addr = str::from_utf8(&data).map_err(Error::TsdnsParseResponse)?; + let addr = str::from_utf8(&data).map_err(Error::TsdnsParseResponse)?.trim(); if addr.starts_with("404") { return Err(Error::TsdnsAddressNotFound); } @@ -340,75 +391,45 @@ pub async fn resolve_tsdns(server: A, addr: &str) -> Resu } } -fn resolve_srv(resolver: TokioResolver, addr: String) -> impl Stream> { - stream::once(async { - let lookup = resolver.srv_lookup(addr).await.map_err(Error::SrvLookup)?; - let srvs = lookup - .answers() +/// The targets and ports of the SRV records at `name`, in the order to try +/// them. +async fn srv_targets(name: String) -> Result> { + let lookup = create_resolver()?.srv_lookup(name).await.map_err(Error::SrvLookup)?; + let records = lookup + .answers() + .iter() + .filter_map(|r| match &r.data { + RData::SRV(srv) => Some((srv.priority, srv.weight, (srv.target.to_ascii(), srv.port))), + _ => None, + }) + .collect(); + Ok(order_srv(records)) +} + +/// Order SRV records `(priority, weight, record)` as RFC 2782 says: lowest +/// priority first, and within one priority at random by weight, where weight +/// 0 is picked only rarely before the others. +fn order_srv(mut records: Vec<(u16, u16, T)>) -> Vec { + // The weight 0 records of a priority first: only a draw of 0 picks them. + records.sort_by_key(|(priority, weight, _)| (*priority, *weight != 0)); + let mut ordered = Vec::with_capacity(records.len()); + while let Some(&(priority, ..)) = records.first() { + let end = records.iter().position(|r| r.0 != priority).unwrap_or(records.len()); + let total: u32 = records[..end].iter().map(|r| u32::from(r.1)).sum(); + let mut draw = rand::rng().random_range(0..=total); + let pick = records[..end] .iter() - .map(|r| { - let RData::SRV(srv) = &r.data else { panic!("Unexpected answer") }; - srv.clone() - }) - .collect::>(); - - let prios = srvs.iter().chunk_by(|srv| srv.priority); - let entries = prios.into_iter().sorted_by_key(|(p, _)| *p); - - // Select by weight - let mut sorted_entries = Vec::new(); - for (_, es) in entries { - let mut zero_entries = Vec::new(); - - // All non-zero entries - let mut entries = es - .filter_map(|e| { - if e.weight == 0 { - zero_entries.push(e); - None - } else { - Some(e) - } - }) - .collect::>(); - - while !entries.is_empty() { - let weight: u32 = entries.iter().map(|e| e.weight as u32).sum(); - let mut w = rand::rng().random_range(0..=weight); - if w == 0 { - // Pick the first entry with weight 0 - if let Some(i) = entries.iter().position(|e| e.weight == 0) { - sorted_entries.push(entries.remove(i)); - } + .position(|r| { + if draw <= u32::from(r.1) { + return true; } - for i in 0..entries.len() { - let weight = entries[i].weight as u32; - if w <= weight { - sorted_entries.push(entries.remove(i)); - break; - } - w -= weight; - } - } - } - - let res = sorted_entries - .into_iter() - .map(|e| Ok((e.target.to_ascii(), e.port))) - .collect::>>(); - drop(resolver); - Ok(stream::iter(res) - .and_then(|(e, port)| async move { - let res = net::lookup_host((e.as_str(), port)) - .await - .map_err(Error::ResolveHost)? - .map(Ok) - .collect::>(); - Ok(stream::iter(res)) + draw -= u32::from(r.1); + false }) - .try_flatten()) - }) - .try_flatten() + .unwrap_or(0); + ordered.push(records.remove(pick).2); + } + ordered } #[cfg(test)] @@ -479,6 +500,7 @@ mod test { } #[tokio::test] + #[ignore = "needs DNS and the internet"] async fn resolve_localhost2() { create_logger(); let res: Vec<_> = resolve("localhost".into()).map(|r| r.unwrap()).collect().await; @@ -486,6 +508,7 @@ mod test { } #[tokio::test] + #[ignore = "needs DNS and the internet"] async fn resolve_example() { create_logger(); let res: Vec<_> = resolve("example.com".into()).map(|r| r.unwrap()).collect().await; @@ -493,6 +516,7 @@ mod test { } #[tokio::test] + #[ignore = "needs DNS and the internet"] async fn resolve_splamy_de() { create_logger(); @@ -506,9 +530,159 @@ mod test { } #[tokio::test] + #[ignore = "needs DNS and the internet"] async fn resolve_loc() { create_logger(); let res: Vec<_> = resolve("loc".into()).map(|r| r.unwrap()).collect().await; assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap())); } + + /// Lookups that never leave this machine: `hosts` maps a name to an ip + /// (with the port asked for), `srv` an SRV name to its target and port. + fn fake(hosts: &[(&str, &str)], srv: &[(&str, &str, u16)], tsdns_port: u16) -> Lookups { + let hosts: Vec<(String, IpAddr)> = + hosts.iter().map(|(name, ip)| (name.to_string(), ip.parse().unwrap())).collect(); + let srv: Vec<(String, String, u16)> = srv + .iter() + .map(|(name, target, port)| (name.to_string(), target.to_string(), *port)) + .collect(); + let missing = || Error::Io("dns", std::io::ErrorKind::NotFound.into()); + Lookups { + srv: Arc::new(move |name| { + let found: Vec<_> = + srv.iter().filter(|r| r.0 == name).map(|r| (r.1.clone(), r.2)).collect(); + future::ready(if found.is_empty() { Err(missing()) } else { Ok(found) }).boxed() + }), + host: Arc::new(move |name, port| { + let found: Vec<_> = hosts + .iter() + .filter(|h| h.0 == name) + .map(|h| SocketAddr::new(h.1, port)) + .collect(); + future::ready(if found.is_empty() { Err(missing()) } else { Ok(found) }).boxed() + }), + tsdns_port, + tsdns_timeout: Duration::from_millis(500), + } + } + + /// A TSDNS server on 127.0.0.1 that answers the names in `answers` and + /// `404` to others, or with `silent` accepts and never answers (like a + /// server behind a firewall that drops the port). Returns its port. + async fn fake_tsdns(answers: &'static [(&'static str, &'static str)], silent: bool) -> u16 { + let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + tokio::spawn(async move { + let mut asked = [0; 256]; + let n = socket.read(&mut asked).await.unwrap(); + if silent { + tokio::time::sleep(Duration::from_secs(60)).await; + } + let asked = str::from_utf8(&asked[..n]).unwrap(); + let answer = answers.iter().find(|a| a.0 == asked).map_or("404", |a| a.1); + socket.write_all(answer.as_bytes()).await.unwrap(); + }); + } + }); + port + } + + async fn resolved(address: &str, lookups: Lookups) -> Vec { + create_logger(); + let found: Vec = tokio::time::timeout( + Duration::from_secs(5), + resolve_with(address.into(), lookups).try_collect(), + ) + .await + .expect("resolving takes too long") + .unwrap(); + found.iter().map(ToString::to_string).collect() + } + + /// The official client's log for such a server: `A/AAAA DNS resolve for + /// possible TSDNS successful, "example.test"`, `TSDNS found at …:41144 + /// and queried successfully`. + #[tokio::test] + async fn tsdns_at_the_domain_without_srv_records() { + let port = fake_tsdns(&[("ts.example.test", "192.0.2.10:19987")], false).await; + let lookups = + fake(&[("example.test", "127.0.0.1"), ("ts.example.test", "198.51.100.7")], &[], port); + assert_eq!(resolved("ts.example.test", lookups.clone()).await, [ + "192.0.2.10:19987", + "198.51.100.7:9987" + ]); + // A port typed with the address wins over TSDNS and the default. + assert_eq!(resolved("ts.example.test:4000", lookups).await, [ + "192.0.2.10:4000", + "198.51.100.7:4000" + ]); + } + + #[tokio::test] + async fn tsdns_that_does_not_know_the_name_leaves_the_plain_address() { + let port = fake_tsdns(&[("other.example.test", "192.0.2.10:19987")], false).await; + let lookups = + fake(&[("example.test", "127.0.0.1"), ("ts.example.test", "198.51.100.7")], &[], port); + assert_eq!(resolved("ts.example.test", lookups).await, ["198.51.100.7:9987"]); + } + + #[tokio::test] + async fn a_silent_tsdns_server_does_not_hold_up_resolving() { + let port = fake_tsdns(&[("ts.example.test", "192.0.2.10:19987")], true).await; + let lookups = + fake(&[("example.test", "127.0.0.1"), ("ts.example.test", "198.51.100.7")], &[], port); + let start = std::time::Instant::now(); + assert_eq!(resolved("ts.example.test", lookups).await, ["198.51.100.7:9987"]); + assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed()); + } + + /// The official order: `_ts3._udp` SRV, then TSDNS, then the address + /// itself; and a TSDNS server named by `_tsdns._tcp` SRV is asked instead + /// of one at the domain. + #[tokio::test] + async fn srv_records_come_first_and_name_the_tsdns_server() { + let direct = fake_tsdns(&[("ts.example.test", "192.0.2.99:1")], false).await; + let named = fake_tsdns(&[("ts.example.test", "192.0.2.20:2000")], false).await; + let lookups = fake( + &[ + ("example.test", "127.0.0.1"), + ("tsdns.example.test", "127.0.0.1"), + ("voice.example.test", "203.0.113.5"), + ("ts.example.test", "198.51.100.7"), + ], + &[ + ("_ts3._udp.ts.example.test.", "voice.example.test", 9999), + ("_tsdns._tcp.example.test.", "tsdns.example.test", named), + ], + direct, + ); + assert_eq!(resolved("ts.example.test", lookups).await, [ + "203.0.113.5:9999", + "192.0.2.20:2000", + "198.51.100.7:9987" + ]); + } + + #[test] + fn tsdns_is_looked_for_at_the_parent_domains() { + assert_eq!(tsdns_domains("ts.example.test"), ["example.test"]); + assert_eq!(tsdns_domains("a.b.example.test"), ["b.example.test", "example.test"]); + assert_eq!(tsdns_domains("example.test"), ["example.test"]); + assert!(tsdns_domains("localhost").is_empty()); + } + + #[test] + fn srv_records_are_ordered_by_priority_and_none_is_lost() { + // Weight 0 is the usual weight; such records were dropped before. + assert_eq!(order_srv(vec![(0, 0, "only")]), ["only"]); + for _ in 0..50 { + let ordered = order_srv(vec![(10, 0, "c"), (0, 0, "a"), (0, 5, "b"), (20, 1, "d")]); + assert_eq!(ordered.len(), 4); + assert!(ordered[..2].contains(&"a") && ordered[..2].contains(&"b"), "{:?}", ordered); + assert_eq!(ordered[2..], ["c", "d"]); + } + } }