diff --git a/Cargo.lock b/Cargo.lock index e719e13..d3f44bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8638,7 +8638,11 @@ checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" dependencies = [ "futures-util", "log", + "rustls", + "rustls-native-certs", + "rustls-pki-types", "tokio", + "tokio-rustls", "tungstenite 0.30.0", ] @@ -9188,6 +9192,8 @@ dependencies = [ "httparse", "log", "rand 0.10.3", + "rustls", + "rustls-pki-types", "sha1 0.11.0", "thiserror 2.0.21", ] @@ -9472,6 +9478,7 @@ dependencies = [ "base64 0.22.1", "dirs", "futures", + "hickory-resolver", "md5", "rusqlite", "serde", 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"]); + } + } } diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 6613e64..67fa22d 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -26,6 +26,8 @@ anyhow = "1" base64 = "0.22" dirs = "6" futures = "0.3" +# Finding a server's gateway in DNS (the voice resolver's version). +hickory-resolver = "0.26" md5 = "0.8" # Reading the official clients' settings.db when importing identities. rusqlite = { version = "0.40.2", features = ["bundled"] } diff --git a/crates/voelin-core/src/discover.rs b/crates/voelin-core/src/discover.rs new file mode 100644 index 0000000..804b8e5 --- /dev/null +++ b/crates/voelin-core/src/discover.rs @@ -0,0 +1,340 @@ +//! Finding a server's `tsgw` gateway from the server's address, so nobody +//! types the gateway's URL. +//! +//! Like TeamSpeak's own lookup (SRV `_ts3._udp`, then TSDNS), at the +//! address's host and then each parent domain down to the last two labels, +//! the most specific name first: +//! +//! - SRV `_tsgws._tcp.`: `wss://:`, +//! - SRV `_tsgw._tcp.`: `ws://:`, +//! +//! TLS first at the same name; `` is `path=…` from a TXT record at the +//! SRV record's name, `/v1` without one. Without any such record, as TSDNS +//! has its well-known port, the gateway itself is asked at tsgw's default +//! port: `http://:7788/.well-known/tsgw` answers `{"url": "…"}`. For an +//! IP address (or `localhost`) only that is tried. What an admin publishes is +//! in `docs/gateway-admin.md`. + +use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; + +use futures::future::{BoxFuture, FutureExt, join_all}; +use hickory_resolver::TokioResolver; +use hickory_resolver::config::{CLOUDFLARE, ResolverConfig}; +use hickory_resolver::net::runtime::TokioRuntimeProvider; +use hickory_resolver::proto::rr::RData; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::time::timeout; + +/// The port tsgw listens on by default, where it is asked for its URL. +pub const DEFAULT_PORT: u16 = 7788; +/// Where tsgw serves its WebSocket. +const DEFAULT_PATH: &str = "/v1"; +/// Give up on asking one name's gateway after this long. +const PROBE_TIMEOUT: Duration = Duration::from_secs(3); + +type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync; +type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec> + Send + Sync; + +/// Where [`gateway`] gets its answers from; the tests put fakes in. +#[derive(Clone)] +struct Lookups { + /// The SRV records at a name: priority, target, port. + srv: Arc, + /// The strings of the TXT records at a name. + txt: Arc, + /// Where a gateway is asked for its URL. + probe_port: u16, +} + +impl Lookups { + fn system() -> Self { + // The system's resolver, else (Android) a public one, as the voice + // connection's resolver does. + let resolver = TokioResolver::builder_tokio().and_then(|b| b.build()).or_else(|_| { + TokioResolver::builder_with_config( + ResolverConfig::udp_and_tcp(&CLOUDFLARE), + TokioRuntimeProvider::default(), + ) + .build() + }); + let resolver = resolver.ok(); + let txt_resolver = resolver.clone(); + Self { + srv: Arc::new(move |name| { + let resolver = resolver.clone(); + async move { + let lookup = resolver?.srv_lookup(name).await.ok()?; + Some( + lookup + .answers() + .iter() + .filter_map(|r| match &r.data { + RData::SRV(s) => Some((s.priority, s.target.to_ascii(), s.port)), + _ => None, + }) + .collect(), + ) + } + .map(Option::unwrap_or_default) + .boxed() + }), + txt: Arc::new(move |name| { + let resolver = txt_resolver.clone(); + async move { + let lookup = resolver?.txt_lookup(name).await.ok()?; + Some( + lookup + .answers() + .iter() + .filter_map(|r| match &r.data { + RData::TXT(t) => Some(t.txt_data.iter()), + _ => None, + }) + .flatten() + .map(|s| String::from_utf8_lossy(s).into_owned()) + .collect(), + ) + } + .map(Option::unwrap_or_default) + .boxed() + }), + probe_port: DEFAULT_PORT, + } + } +} + +/// The URL of the gateway of the server at `address` (as a bookmark has it: +/// host, host:port, an IP), if one is published. +pub async fn gateway(address: &str) -> Option { + gateway_with(address, Lookups::system()).await +} + +async fn gateway_with(address: &str, lookups: Lookups) -> Option { + let host = host_of(address); + let names = names(host); + if names.is_empty() { + return None; + } + if host.parse::().is_err() + && host.contains('.') + && let Some(url) = from_srv(&names, &lookups).await + { + return Some(url); + } + from_well_known(&names, lookups.probe_port).await +} + +/// The host of an address: without the port, the brackets of an IPv6 +/// address and a final dot. +fn host_of(address: &str) -> &str { + let address = address.trim(); + let host = match address.strip_prefix('[') { + Some(rest) => rest.split(']').next().unwrap_or(rest), + // One colon: host and port; more: an IPv6 address. + None if address.matches(':').count() == 1 => address.split(':').next().unwrap_or(address), + None => address, + }; + host.trim_end_matches('.') +} + +/// The names to look at, most specific first: a host name and its parent +/// domains down to the last two labels; an IP address or `localhost` alone; +/// nothing for a server nickname. +// ponytail: two labels as the floor instead of the public suffix list, as +// the voice resolver's TSDNS lookup; under `co.uk`-style suffixes this also +// asks the suffix. +fn names(host: &str) -> Vec<&str> { + if host.parse::().is_ok() || host == "localhost" { + return vec![host]; + } + std::iter::successors(Some(host), |name| name.split_once('.').map(|(_, parent)| parent)) + .take_while(|name| name.contains('.')) + .collect() +} + +/// The URL from SRV records, every name and service asked at once. +async fn from_srv(names: &[&str], lookups: &Lookups) -> Option { + let queries: Vec<(&str, String)> = names + .iter() + .flat_map(|name| { + [("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))] + }) + .collect(); + let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await; + // The first (most specific, TLS first) name with a usable record. + let ((scheme, owner), (_, target, port)) = + queries.iter().zip(answers).find_map(|(q, records)| { + // A target of "." says there is no such service there. + let best = records.into_iter().filter(|r| r.1 != ".").min_by_key(|r| r.0)?; + Some((q, best)) + })?; + let mut path = (lookups.txt)(owner.clone()) + .await + .into_iter() + .find_map(|s| s.strip_prefix("path=").map(str::to_owned)) + .unwrap_or_else(|| DEFAULT_PATH.to_owned()); + if !path.starts_with('/') { + path.insert(0, '/'); + } + Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'))) +} + +/// The URL a gateway gives for itself at one of `names`, all asked at once; +/// the most specific that answers wins. +async fn from_well_known(names: &[&str], port: u16) -> Option { + let answers = + join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await; + answers.into_iter().find_map(|answer| answer.ok().flatten()) +} + +/// tsgw's answer at `http://:/.well-known/tsgw`. +async fn well_known(host: &str, port: u16) -> Option { + let mut stream = TcpStream::connect((host, port)).await.ok()?; + let authority = + if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; + let request = + format!("GET /.well-known/tsgw HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.ok()?; + let mut response = Vec::new(); + stream.take(16 * 1024).read_to_end(&mut response).await.ok()?; + let response = String::from_utf8(response).ok()?; + let (head, body) = response.split_once("\r\n\r\n")?; + if head.split_whitespace().nth(1) != Some("200") { + return None; + } + let answer: serde_json::Value = serde_json::from_str(body).ok()?; + let url = answer.get("url")?.as_str()?; + (url.starts_with("ws://") || url.starts_with("wss://")).then(|| url.to_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// DNS answers from these lists only: SRV `(name, priority, target, + /// port)`, TXT `(name, string)`. + fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)], probe_port: u16) -> Lookups { + let srv: Vec<(String, u16, String, u16)> = + srv.iter().map(|(n, p, t, port)| (n.to_string(), *p, t.to_string(), *port)).collect(); + let txt: Vec<(String, String)> = + txt.iter().map(|(n, s)| (n.to_string(), s.to_string())).collect(); + Lookups { + srv: Arc::new(move |name| { + let found = + srv.iter().filter(|r| r.0 == name).map(|r| (r.1, r.2.clone(), r.3)).collect(); + futures::future::ready(found).boxed() + }), + txt: Arc::new(move |name| { + let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect(); + futures::future::ready(found).boxed() + }), + probe_port, + } + } + + /// A port nothing listens on. + fn closed_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() + } + + #[tokio::test] + async fn finds_the_gateway_at_the_host_or_its_domain() { + let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[], 0); + for address in ["ts.example.test", "ts.example.test:9987", "example.test"] { + assert_eq!( + gateway_with(address, lookups.clone()).await.as_deref(), + Some("ws://gw.example.test:7788/v1"), + "{address}" + ); + } + // The parent's parent is not the domain any more. + assert_eq!(gateway_with("example", lookups).await, None); + } + + #[tokio::test] + async fn the_most_specific_name_wins_then_tls() { + let lookups = fake( + &[ + ("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443), + ("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788), + ("_tsgws._tcp.ts.example.test.", 5, "backup.example.test.", 443), + ("_tsgws._tcp.ts.example.test.", 1, "tls.example.test.", 8443), + ], + &[("_tsgws._tcp.ts.example.test.", "path=/tsgw/v1")], + 0, + ); + assert_eq!( + gateway_with("ts.example.test", lookups.clone()).await.as_deref(), + Some("wss://tls.example.test:8443/tsgw/v1") + ); + assert_eq!( + gateway_with("voice.example.test", lookups).await.as_deref(), + Some("wss://domain.example.test:443/v1") + ); + } + + #[tokio::test] + async fn a_record_that_says_no_service_is_skipped() { + let lookups = fake( + &[ + ("_tsgw._tcp.ts.example.test.", 0, ".", 0), + ("_tsgw._tcp.example.test.", 0, "gw.example.test.", 80), + ], + &[("_tsgw._tcp.example.test.", "path=ws")], + closed_port(), + ); + assert_eq!( + gateway_with("ts.example.test", lookups).await.as_deref(), + Some("ws://gw.example.test:80/ws") + ); + } + + /// Without records the gateway next to the server answers at its port, + /// as tsgw does (`/.well-known/tsgw`). + #[tokio::test] + async fn without_records_the_gateway_itself_is_asked() { + let listener = tokio::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(); + let mut request = [0; 1024]; + let n = socket.read(&mut request).await.unwrap(); + let request = String::from_utf8_lossy(&request[..n]).into_owned(); + let response = if request.starts_with("GET /.well-known/tsgw ") { + let body = r#"{"url":"wss://gw.example.test/v1"}"#; + format!("HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{body}", body.len()) + } else { + "HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\n\r\n".to_owned() + }; + socket.write_all(response.as_bytes()).await.unwrap(); + } + }); + let lookups = fake(&[], &[], port); + for address in ["127.0.0.1", "127.0.0.1:9987", "localhost"] { + assert_eq!( + gateway_with(address, lookups.clone()).await.as_deref(), + Some("wss://gw.example.test/v1"), + "{address}" + ); + } + // Nothing there. + assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None); + } + + #[test] + fn names_walk_up_to_the_domain() { + assert_eq!( + names(host_of("ts.sub.example.test:9987")), + ["ts.sub.example.test", "sub.example.test", "example.test"] + ); + assert_eq!(names(host_of("[::1]:9987")), ["::1"]); + assert_eq!(names(host_of("::1")), ["::1"]); + assert_eq!(names(host_of("example.test.")), ["example.test"]); + // A server nickname is resolved by TeamSpeak, not in DNS. + assert!(names(host_of("nickname")).is_empty()); + } +} diff --git a/crates/voelin-core/src/identity.rs b/crates/voelin-core/src/identity.rs index eea4bbf..35721be 100644 --- a/crates/voelin-core/src/identity.rs +++ b/crates/voelin-core/src/identity.rs @@ -34,7 +34,7 @@ use voelin_gateway_proto::UniqueIds; use voelin_store::Store; /// Name given to an identity whose source kept none. -const DEFAULT_NICKNAME: &str = "imported"; +pub const DEFAULT_NICKNAME: &str = "imported"; /// Item field holding the item's type; the payload is in field /// [`PAYLOAD_FIELD_BASE`] `+ type`. @@ -76,6 +76,8 @@ pub struct Found { pub identity: Identity, /// The file it came from. pub source: PathBuf, + /// The identity the other client uses by default (payload field 5). + pub selected: bool, } impl Found { @@ -171,6 +173,26 @@ pub fn import(store: &Store, found: &[Found]) -> Result, IdentityE .collect() } +/// Store the identities in the official clients' files at `paths` (usually +/// [`discover`]) that the store does not have yet, as the app does when it +/// starts. Files that cannot be read or hold no identity are skipped; none is +/// written. The identities the clients use by default go in first, so on a +/// store without identities the official client's default becomes ours (the +/// first identity) and servers see the same unique id. Returns what was +/// added. +pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result, IdentityError> { + let mut found: Vec = paths.iter().filter_map(|path| read(path).ok()).flatten().collect(); + // Stable: TeamSpeak 6's default before TeamSpeak 3's, as `locations` lists them. + found.sort_by_key(|f| !f.selected); + let outcomes = import(store, &found)?; + Ok(found + .into_iter() + .zip(outcomes) + .filter(|(_, outcome)| matches!(outcome, Imported::Added(_))) + .map(|(f, _)| f) + .collect()) +} + /// The TeamSpeak 3 `.ini` export of an identity, which the official client /// and every other tool reads. pub fn export(nickname: &str, identity: &Identity) -> String { @@ -326,7 +348,7 @@ fn record_identity(record: &[(String, String)], source: &Path) -> Option let identity = Identity::new_from_ts_str(find("identity")?).ok()?; let nickname = find("nickname").or_else(|| find("id")).unwrap_or_default(); let nickname = if nickname.is_empty() { DEFAULT_NICKNAME } else { nickname }.to_owned(); - Some(Found { nickname, identity, source: source.to_owned() }) + Some(Found { nickname, identity, source: source.to_owned(), selected: false }) } /// The identity payload of a `ProtobufItems` item, or `None` if the item is @@ -347,22 +369,27 @@ fn identity_payload(item: &[u8]) -> Option<&[u8]> { payload.filter(|_| kind == Some(IDENTITY_TYPE)) } -/// The export string is field 1 of the identity payload, the nickname field 2. +/// The export string is field 1 of the identity payload, the nickname field 2, +/// and field 5 is 1 on the identity the client uses by default. fn payload_identity(payload: &[u8], source: &Path) -> Option { let mut export = None; let mut nickname = None; + let mut selected = false; let mut wire = Wire { rest: payload }; - while let Some((number, Field::Bytes(bytes))) = wire.next_field() { - match number { - 1 => export = str::from_utf8(bytes).ok(), - 2 => nickname = Some(String::from_utf8_lossy(bytes).into_owned()), + while let Some((number, field)) = wire.next_field() { + match (number, field) { + (1, Field::Bytes(bytes)) => export = str::from_utf8(bytes).ok(), + (2, Field::Bytes(bytes)) => { + nickname = Some(String::from_utf8_lossy(bytes).into_owned()) + } + (5, Field::Var(value)) => selected = value == 1, _ => {} } } let identity = Identity::new_from_ts_str(export?).ok()?; let nickname = nickname.filter(|n| !n.is_empty()).unwrap_or_else(|| DEFAULT_NICKNAME.to_owned()); - Some(Found { nickname, identity, source: source.to_owned() }) + Some(Found { nickname, identity, source: source.to_owned(), selected }) } /// A protobuf field's value. Fixed-width fields carry nothing we read; they @@ -472,13 +499,14 @@ mod tests { } } - /// An item of the shape both clients write, holding `identity`. - fn protobuf_item(identity: &Identity, nickname: &str) -> Vec { + /// An item of the shape both clients write, holding `identity`; `selected` + /// is the client's default. + fn protobuf_item(identity: &Identity, nickname: &str, selected: bool) -> Vec { let export = format!("{}V{}", identity.counter(), identity.key().to_ts_obfuscated()); let mut payload = bytes_field(1, export.as_bytes()); payload.extend(bytes_field(2, nickname.as_bytes())); payload.extend(bytes_field(3, b"a1b2c3d4")); - payload.extend(varint_field(5, 1)); + payload.extend(varint_field(5, u64::from(selected))); let mut item = bytes_field(2, b"4a7b4f46-0000-4000-8000-000000000001"); item.extend(varint_field(TYPE_FIELD, IDENTITY_TYPE)); item.extend(varint_field(9, 1_700_000_000)); @@ -576,7 +604,7 @@ mod tests { mismatched.extend(bytes_field(PAYLOAD_FIELD_BASE, b"not an identity")); for (key, value) in [ ("1", other), - ("2", protobuf_item(&identity, "Имя")), + ("2", protobuf_item(&identity, "Имя", true)), ("3", mismatched), ("Checksum", vec![0; 20]), ] { @@ -588,6 +616,52 @@ mod tests { // A non-ASCII nickname survives. assert_eq!(found[0].nickname, "Имя"); assert_eq!(found[0].uid(), identity.key().to_pub().get_uid()); + assert!(found[0].selected); + fs::remove_dir_all(dir).unwrap(); + } + + /// A `settings.db` as the official clients write it, with these + /// identities. + fn client_database(path: &Path, items: &[(&Identity, &str, bool)]) { + let db = Connection::open(path).unwrap(); + db.execute_batch( + "CREATE TABLE ProtobufItems (timestamp integer unsigned NOT NULL, + key varchar NOT NULL UNIQUE, value varchar)", + ) + .unwrap(); + for (key, (identity, nickname, selected)) in items.iter().enumerate() { + let item = protobuf_item(identity, nickname, *selected); + db.execute("INSERT INTO ProtobufItems VALUES (0, ?1, ?2)", (key.to_string(), item)) + .unwrap(); + } + } + + #[test] + fn launch_import_makes_the_clients_default_ours_and_adds_only_new_ones() { + let dir = temp_dir("launch"); + let ts6 = dir.join("ts6.db"); + let ts3 = dir.join("ts3.db"); + let (spare, main, old) = (synthetic(), synthetic(), synthetic()); + // The default identity is not the first item. + client_database(&ts6, &[(&spare, "Spare", false), (&main, "Main", true)]); + let missing = dir.join("missing.db"); + let store = Store::open_in_memory().unwrap(); + + let added = import_new(&store, &[ts6.clone(), missing.clone()]).unwrap(); + let nicknames: Vec<_> = added.iter().map(|f| f.nickname.as_str()).collect(); + assert_eq!(nicknames, ["Main", "Spare"]); + // The first identity is the app's default: the client's default. + assert_eq!(store.identities().unwrap()[0].uid, main.key().to_pub().get_uid()); + + // The next start finds only what is new. + client_database(&ts3, &[(&old, "Old", true), (&main, "Main", true)]); + let added = import_new(&store, &[ts6, ts3, missing]).unwrap(); + let nicknames: Vec<_> = added.iter().map(|f| f.nickname.as_str()).collect(); + assert_eq!(nicknames, ["Old"]); + let stored = store.identities().unwrap(); + assert_eq!(stored.len(), 3); + // A store that has identities keeps its default. + assert_eq!(stored[0].uid, main.key().to_pub().get_uid()); fs::remove_dir_all(dir).unwrap(); } @@ -599,6 +673,7 @@ mod tests { nickname: nickname.to_owned(), identity: identity.clone(), source: PathBuf::from("test.ini"), + selected: false, }; // The same unique id twice in one batch, then again in a second run. let outcome = import(&store, &[found("first"), found("again")]).unwrap(); diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 705179f..cac6690 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -46,6 +46,7 @@ mod audio; mod book; pub mod cache; pub mod contacts; +pub mod discover; pub mod files; pub mod gateway; pub mod history; diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index cc00841..5aa62fb 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1132,6 +1132,15 @@ pub static CACHE_FETCH_IMAGES: Key = Key::new( || true, ); +/// Import identities from the official TeamSpeak clients when the app +/// starts ([`crate::identity::import_new`]; their files are only read). +pub static IDENTITY_IMPORT: Key = Key::new( + "identity.import_from_teamspeak", + Kind::Bool, + "Import new identities from the official TeamSpeak clients on start (read only).", + || true, +); + /// How often a file transfer reports its progress (ms); 0: after every /// piece received or sent. pub static FILES_PROGRESS_MS: Key = Key::new( @@ -1309,6 +1318,7 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> { &STREAM_AUDIO_SOURCES, &CACHE_MAX_MB, &CACHE_FETCH_IMAGES, + &IDENTITY_IMPORT, &FILES_PROGRESS_MS, &PRIVACY_BLOCK_MODE, #[cfg(feature = "media")] diff --git a/crates/voelin-gateway-proto/Cargo.toml b/crates/voelin-gateway-proto/Cargo.toml index 64ad14b..2a03809 100644 --- a/crates/voelin-gateway-proto/Cargo.toml +++ b/crates/voelin-gateway-proto/Cargo.toml @@ -21,7 +21,9 @@ sha1 = { package = "sha-1", version = "0.10" } sha2 = "0.10" thiserror = "2" tokio = { version = "1", features = ["macros", "rt", "sync"], optional = true } -tokio-tungstenite = { version = "0.30", optional = true } +# TLS (`wss://`, as gateways run behind a proxy) with the system's +# certificates; rustls and its crates are in the tree already (reqwest). +tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] } voelin-model = { path = "../voelin-model" } tsproto-types = { path = "../proto/tsproto-types" } diff --git a/crates/voelin-gateway/src/main.rs b/crates/voelin-gateway/src/main.rs index f7981c1..5d0df4e 100644 --- a/crates/voelin-gateway/src/main.rs +++ b/crates/voelin-gateway/src/main.rs @@ -21,10 +21,11 @@ use std::path::PathBuf; use std::sync::Arc; use anyhow::Result; -use axum::Router; use axum::extract::{State, WebSocketUpgrade}; +use axum::http::{HeaderMap, header}; use axum::response::IntoResponse; use axum::routing::get; +use axum::{Json, Router}; use clap::Parser; use tracing::{info, warn}; use tracing_subscriber::EnvFilter; @@ -62,7 +63,22 @@ async fn main() -> Result<()> { } pub fn router(hub: Arc) -> Router { - Router::new().route("/v1", get(ws)).route("/health", get(|| async { "ok" })).with_state(hub) + Router::new() + .route("/v1", get(ws)) + .route("/health", get(|| async { "ok" })) + .route("/.well-known/tsgw", get(well_known)) + .with_state(hub) +} + +/// Where apps reach this gateway, for those that find it by asking the +/// server's host on the default port (docs/gateway-admin.md): the +/// configured public URL, else this listener as the request reached it. +async fn well_known(State(hub): State>, headers: HeaderMap) -> Json { + let url = hub.boot.public_url.clone().unwrap_or_else(|| { + let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("localhost"); + format!("ws://{host}/v1") + }); + Json(serde_json::json!({ "url": url })) } async fn ws(State(hub): State>, upgrade: WebSocketUpgrade) -> impl IntoResponse { diff --git a/crates/voelin-gateway/src/tests/mod.rs b/crates/voelin-gateway/src/tests/mod.rs index e268f35..e8c5116 100644 --- a/crates/voelin-gateway/src/tests/mod.rs +++ b/crates/voelin-gateway/src/tests/mod.rs @@ -533,3 +533,37 @@ async fn admin_settings_apply_live() { let stored = fx.hub.db.config_values().unwrap(); assert!(stored.iter().any(|(k, v)| k == "relay.nickname" && v == "Bridge")); } + +/// The gateway's answer at `/.well-known/tsgw`, as an app asks for it. +async fn well_known(fx: &Fixture) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let host = fx.url.trim_start_matches("ws://").trim_end_matches("/v1"); + let mut stream = tokio::net::TcpStream::connect(host).await.unwrap(); + let request = + format!("GET /.well-known/tsgw HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + let body = response.split_once("\r\n\r\n").unwrap().1; + let answer: serde_json::Value = serde_json::from_str(body).unwrap(); + answer["url"].as_str().unwrap().to_owned() +} + +/// Apps that know only the server's host ask the gateway on its port where +/// it is (`voelin_core::discover`), then log in there. +#[tokio::test(flavor = "multi_thread")] +async fn tells_apps_where_it_is() { + let fx = Fixture::start("well-known", "").await; + let url = well_known(&fx).await; + assert_eq!(url, fx.url); + let (alice, _, _) = fx.people(); + let login = Login::Identity { key: alice.key.clone(), key_offset: 0 }; + let (client, _pushes) = connect(&url, login).await.unwrap(); + assert!(client.has(feature::PRESENCE)); + + // Behind a proxy it gives the public URL instead. + let public = "[listen]\npublic_url = \"wss://gw.example.test/v1\"\n"; + let fx = Fixture::start("well-known-public", public).await; + assert_eq!(well_known(&fx).await, "wss://gw.example.test/v1"); +} diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 6a67f32..17f2190 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -19,7 +19,8 @@ use tokio::runtime::Runtime; use tracing::warn; use voelin_core::media::decoder_preference; use voelin_core::settings::{ - AUDIO, CRASH_REPORTS, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, Settings, + AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, + Settings, }; use voelin_core::stream::StreamInfo; use voelin_core::{ @@ -530,16 +531,30 @@ pub fn run(options: RunOptions) -> Result<()> { Ok(history) => engine.send(Command::AttachHistory(history)), Err(e) => warn!(%e, "chat history is not stored this time"), } + let prefs = open_settings(&dir, &options.setting_overrides); + let switches = crate::dev::Switches::from_env(); + // New identities of the official TeamSpeak clients, on every start (not + // with the sample data of VOELIN_DEMO_UI); with none of our own yet, the + // client's default identity becomes ours. + let had_identity = !store.identities()?.is_empty(); + let imported = if prefs.get(&IDENTITY_IMPORT) && !switches.demo_ui { + voelin_core::identity::import_new(&store, &voelin_core::identity::discover()) + .unwrap_or_else(|e| { + warn!(%e, "could not import TeamSpeak identities"); + Vec::new() + }) + } else { + Vec::new() + }; let identity = match store.identities()?.first() { Some(entry) => store.identity(entry.id)?, None => { // Creating an identity takes a moment (security level 8). let identity = tsclientlib::Identity::create(); - store.add_identity("Default", &identity)?; + store.add_identity(crate::servers::CREATED_IDENTITY, &identity)?; identity } }; - let prefs = open_settings(&dir, &options.setting_overrides); engine.send(Command::AttachSettings(prefs.clone())); let mut settings: UiSettings = (*prefs.get_arc(&UI)).clone(); settings.crash_reports = prefs.get(&CRASH_REPORTS); @@ -570,7 +585,6 @@ pub fn run(options: RunOptions) -> Result<()> { } let mut video = Video::new(&dir, settings.openh264); video.set_decoder_preference(decoder_preference(&prefs)); - let switches = crate::dev::Switches::from_env(); let app = App { ui: ui.as_weak(), store, @@ -622,6 +636,9 @@ pub fn run(options: RunOptions) -> Result<()> { if app.demo { app.start_demo(); } + if let Some(text) = crate::servers::imported_status(&imported, had_identity) { + app.set_status(text); + } }); // Engine events -> UI thread, until the event loop is gone. @@ -788,6 +805,7 @@ impl App { } Event::ServerInfo { session, name, flavor, capabilities } => { self.sessions.entry(session as i64).or_default().capabilities = capabilities; + self.adopt_server_name(session as i64, &name); if self.current == Some(session as i64) { let kind = match flavor { voelin_model::ServerFlavor::Ts3(v) => format!("TeamSpeak 3 {v}"), diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index c99af1b..8f56942 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -12,7 +12,8 @@ //! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer. //! - `VOELIN_OPEN=[,...]`: open screens on start: `home`, //! `server`, `settings[:
]` (voice, keybinds, streaming, privacy, -//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server), +//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server; +//! `bookmark:edit` the current one, Advanced open), //! `emoji` (the picker), `client` (the volume dialog of the first other //! client once connected), `panel` / `no-panel` (the members panel), //! `voice` (the voice channel view; on the phone its own screen), @@ -159,6 +160,12 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { with_app(|app| app.demo_share()); } } + // The current server's dialog, Advanced open. + "bookmark" if arg == "edit" => { + if let Some(id) = with_app(|app| app.current).flatten() { + nav.invoke_edit_server(id as i32); + } + } "bookmark" => nav.invoke_add_server(), "emoji" => nav.set_emoji_open(true), "panel" => nav.set_right_panel_open(true), diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 9dc4a95..14107db 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -3,12 +3,87 @@ use slint::{ComponentHandle, SharedString}; use tracing::warn; +use voelin_core::identity::Found; use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState}; use voelin_store::{Bookmark, QueryConfig, QueryTransport}; -use crate::app::{App, BookmarkForm, Bridge}; +use crate::app::{App, BookmarkForm, Bridge, later}; use crate::vm; +/// The name of the identity the app creates when it has none. +pub(crate) const CREATED_IDENTITY: &str = "Default"; + +/// What to tell the user about the identities imported from the official +/// clients at start ([`voelin_core::identity::import_new`]), if any. +/// `had_identity`: we had one before, so it stays the default. +pub(crate) fn imported_status(imported: &[Found], had_identity: bool) -> Option { + let first = imported.first()?; + let n = imported.len(); + let names = imported.iter().map(|f| f.nickname.as_str()).collect::>().join(", "); + Some(match (had_identity, n) { + (true, 1) => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"), + (true, _) => format!("Imported {n} identities from TeamSpeak: {names}"), + (false, 1) => format!("Using your TeamSpeak identity \u{201c}{names}\u{201d}"), + (false, _) => format!( + "Using your TeamSpeak identity \u{201c}{}\u{201d} ({n} imported: {names})", + first.nickname + ), + }) +} + +/// The bookmark the form describes, over `old` (what the form does not show, +/// like the identity, the default channel or the client version, stays; a +/// new server has none of it). Only the address is needed: the name is the +/// address until the server tells its own (`adopt_server_name`), the +/// nickname `default_nickname`, the gateway is looked up later. +fn bookmark_from_form( + old: Option<&Bookmark>, + form: &BookmarkForm, + default_nickname: impl FnOnce() -> String, +) -> Bookmark { + let mut bookmark = old.cloned().unwrap_or_default(); + bookmark.id = form.id as i64; + bookmark.address = form.address.trim().to_string(); + bookmark.name = match form.name.trim() { + "" => bookmark.address.clone(), + name => name.to_string(), + }; + bookmark.nickname = match form.nickname.trim() { + "" => default_nickname(), + nickname => nickname.to_string(), + }; + bookmark.gateway_url = Some(form.gateway_url.trim().to_string()).filter(|u| !u.is_empty()); + bookmark.query = match form.query_transport.as_str() { + "none" | "" => None, + t => { + let (host, port) = form + .query_addr + .rsplit_once(':') + .map_or((form.query_addr.to_string(), None), |(h, p)| { + (h.to_string(), p.parse().ok()) + }); + let transport = match t { + "raw" => QueryTransport::Raw, + "http" => QueryTransport::Http, + _ => QueryTransport::Ssh, + }; + let default_port = match transport { + QueryTransport::Raw => 10011, + QueryTransport::Ssh => 10022, + QueryTransport::Http => 10080, + }; + Some(QueryConfig { + transport, + host, + port: port.unwrap_or(default_port), + user: form.query_user.to_string(), + server_port: bookmark.query.as_ref().and_then(|q| q.server_port), + }) + } + }; + bookmark +} + impl App { pub(crate) fn connect_voice(&mut self) { let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return }; @@ -21,6 +96,77 @@ impl App { self.engine .send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) }); self.set_status(format!("Connecting to {}…", b.address)); + // The admin may have published the gateway since it was added. + self.discover_gateway(b.id); + } + + /// The nickname a new server gets: the default identity's (one imported + /// from TeamSpeak keeps the nickname used there), else the system user's. + pub(crate) fn default_nickname(&self) -> String { + self.store + .identities() + .ok() + .and_then(|identities| identities.into_iter().next()) + .map(|identity| identity.name) + .filter(|name| { + ![CREATED_IDENTITY, voelin_core::identity::DEFAULT_NICKNAME] + .contains(&name.as_str()) + }) + .or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok()) + // Servers refuse an empty nickname (Android has no user name). + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| "Voelin user".to_owned()) + } + + /// Look up the gateway of a server that has none in DNS + /// ([`voelin_core::discover`]); one found is kept as if typed. + pub(crate) fn discover_gateway(&self, id: i64) { + let Some(b) = self.bookmark(id).filter(|b| b.gateway_url.is_none() && !self.demo_ui) else { + return; + }; + let address = b.address.clone(); + self.engine.runtime().spawn(async move { + if let Some(url) = voelin_core::discover::gateway(&address).await { + later(move |app| app.gateway_found(id, &address, url)); + } + }); + } + + /// A gateway was found for the server at `address`; it is kept unless + /// the server changed meanwhile. + fn gateway_found(&mut self, id: i64, address: &str, url: String) { + let Some(b) = self + .bookmarks + .iter_mut() + .find(|b| b.id == id && b.address == address && b.gateway_url.is_none()) + else { + return; + }; + b.gateway_url = Some(url.clone()); + let name = b.name.clone(); + if let Err(e) = self.store.update_bookmark(b) { + warn!(%e, "could not keep the gateway found"); + return; + } + self.set_status(format!("Found the gateway of {name}: {url}")); + self.refresh_toolbar(); + } + + /// The server told its name: a server still named by its address takes + /// it, so the address is all a user has to type. + pub(crate) fn adopt_server_name(&mut self, id: i64, name: &str) { + let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else { + return; + }; + if name.trim().is_empty() || self.demo_ui { + return; + } + b.name = name.trim().to_owned(); + if let Err(e) = self.store.update_bookmark(b) { + warn!(%e, "could not name the server"); + } + self.refresh_servers(); + self.refresh_toolbar(); } pub(crate) fn toggle_observe(&mut self) { @@ -68,7 +214,7 @@ impl App { let Some(b) = self.bookmark(id) else { return BookmarkForm { id: -1, - nickname: std::env::var("USER").unwrap_or_default().into(), + nickname: self.default_nickname().into(), query_transport: "none".into(), query_user: "serveradmin".into(), ..Default::default() @@ -91,7 +237,8 @@ impl App { }; BookmarkForm { id: b.id as i32, - name: b.name.clone().into(), + // Named by its address: empty, so a new address names it again. + name: if b.name == b.address { SharedString::new() } else { b.name.clone().into() }, address: b.address.clone().into(), nickname: b.nickname.clone().into(), server_password: secret(b.server_password_key()), @@ -104,49 +251,8 @@ impl App { } pub(crate) fn save_bookmark(&mut self, form: BookmarkForm) { - let query = match form.query_transport.as_str() { - "none" | "" => None, - t => { - let (host, port) = form - .query_addr - .rsplit_once(':') - .map_or((form.query_addr.to_string(), None), |(h, p)| { - (h.to_string(), p.parse().ok()) - }); - let transport = match t { - "raw" => QueryTransport::Raw, - "http" => QueryTransport::Http, - _ => QueryTransport::Ssh, - }; - let default_port = match transport { - QueryTransport::Raw => 10011, - QueryTransport::Ssh => 10022, - QueryTransport::Http => 10080, - }; - Some(QueryConfig { - transport, - host, - port: port.unwrap_or(default_port), - user: form.query_user.to_string(), - server_port: None, - }) - } - }; - let mut bookmark = Bookmark { - id: form.id as i64, - name: if form.name.is_empty() { - form.address.to_string() - } else { - form.name.to_string() - }, - address: form.address.to_string(), - nickname: form.nickname.to_string(), - identity: None, - default_channel: None, - gateway_url: Some(form.gateway_url.to_string()).filter(|u| !u.is_empty()), - query, - client_version: None, - }; + let mut bookmark = + bookmark_from_form(self.bookmark(form.id as i64), &form, || self.default_nickname()); let result = if bookmark.id < 0 { self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id) } else { @@ -172,6 +278,7 @@ impl App { self.current = Some(bookmark.id); self.bookmarks = self.store.bookmarks().unwrap_or_default(); self.refresh_all(); + self.discover_gateway(bookmark.id); } pub(crate) fn delete_bookmark(&mut self, id: i64) { @@ -360,3 +467,83 @@ impl App { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_address_alone_makes_a_server() { + let form = BookmarkForm { + id: -1, + address: " ts.example.test ".into(), + query_transport: "none".into(), + ..Default::default() + }; + let b = bookmark_from_form(None, &form, || "Nick".into()); + assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test")); + assert_eq!(b.nickname, "Nick"); + assert_eq!( + (b.gateway_url, b.query, b.identity, b.default_channel), + (None, None, None, None) + ); + } + + #[test] + fn editing_keeps_what_the_form_does_not_show() { + let old = Bookmark { + id: 7, + name: "Old".into(), + address: "old.example.test".into(), + nickname: "Me".into(), + identity: Some(2), + default_channel: Some("Lobby/Sub".into()), + gateway_url: Some("ws://gw.example.test:7788/v1".into()), + query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }), + client_version: Some("linux".into()), + }; + let form = BookmarkForm { + id: 7, + name: "Mine".into(), + address: "new.example.test:9988".into(), + nickname: "Other".into(), + // Cleared: looked up again. + gateway_url: "".into(), + query_transport: "raw".into(), + query_addr: "q.example.test".into(), + query_user: "serveradmin".into(), + ..Default::default() + }; + let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given")); + assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other")); + assert_eq!(b.address, "new.example.test:9988"); + assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into()))); + assert_eq!(b.client_version.as_deref(), Some("linux")); + assert_eq!(b.gateway_url, None); + let q = b.query.unwrap(); + assert_eq!( + (q.transport, q.host.as_str(), q.port), + (QueryTransport::Raw, "q.example.test", 10011) + ); + assert_eq!(q.server_port, Some(9988)); + } + + #[test] + fn the_import_is_told_by_nickname() { + let found = |nickname: &str| Found { + nickname: nickname.into(), + identity: tsclientlib::Identity::create(), + source: "settings.db".into(), + selected: false, + }; + assert_eq!(imported_status(&[], false), None); + assert_eq!( + imported_status(&[found("Main")], false).unwrap(), + "Using your TeamSpeak identity \u{201c}Main\u{201d}" + ); + assert_eq!( + imported_status(&[found("Main"), found("Alt")], true).unwrap(), + "Imported 2 identities from TeamSpeak: Main, Alt" + ); + } +} diff --git a/crates/voelin-ui/ui/screens/dialogs.slint b/crates/voelin-ui/ui/screens/dialogs.slint index d4c22d8..bf83919 100644 --- a/crates/voelin-ui/ui/screens/dialogs.slint +++ b/crates/voelin-ui/ui/screens/dialogs.slint @@ -15,74 +15,103 @@ component Footer inherits HorizontalLayout { spacing: Theme.space-3; } +// Add or edit a server: its address and, if it has one, its password; the +// rest under Advanced (name, nickname, gateway, ServerQuery), which Voelin +// fills in itself when left empty. export component BookmarkDialog inherits Modal { in-out property form; callback done(); + // The fields beyond address and password: shown when editing. + property advanced: form.id >= 0; title: form.id < 0 ? @tr("Add server") : @tr("Edit server"); - subtitle: @tr("TeamSpeak 3 or 6 server address and your nickname there."); + subtitle: @tr("Only the address is needed; Voelin finds the rest."); icon: Icons.server; card-width: 560px; - card-height: 640px; + // Fits the address and password (two lines more on a phone). + card-height: advanced ? 720px : Nav.narrow ? 360px : 330px; dismissed => { done(); } ScrollView { vertical-stretch: 1; VerticalLayout { + alignment: start; spacing: Theme.space-4; padding-right: Theme.space-3; Field { - label: @tr("Name"); - TextField { text <=> form.name; placeholder: @tr("My server"); label: @tr("Name"); } + label: @tr("Address"); + hint: @tr("Host name, IP address or server nickname; a port only if the server needs one."); + TextField { text <=> form.address; placeholder: "ts.example.org"; label: @tr("Address"); icon: Icons.globe; } } Field { - label: @tr("Address"); - TextField { text <=> form.address; placeholder: "ts.example.org:9987"; label: @tr("Address"); icon: Icons.globe; } + label: @tr("Server password (optional)"); + TextField { text <=> form.server-password; input-type: InputType.password; label: @tr("Server password"); icon: Icons.lock; } } HorizontalLayout { + spacing: Theme.space-3; + Button { + kind: ButtonKind.ghost; + small: true; + icon: root.advanced ? Icons.chevron-down : Icons.chevron-right; + text: @tr("Advanced"); + clicked => { root.advanced = !root.advanced; } + } + Text { + text: @tr("Name, nickname, gateway, ServerQuery"); + color: Theme.text-muted; + font-size: Theme.font-sm; + vertical-alignment: center; + overflow: elide; + horizontal-stretch: 1; + } + } + if root.advanced: VerticalLayout { spacing: Theme.space-4; + Field { + label: @tr("Name"); + hint: @tr("Empty: the address, then the server's own name once connected."); + TextField { text <=> form.name; placeholder: @tr("The server's name"); label: @tr("Name"); } + } Field { label: @tr("Nickname"); + hint: @tr("Empty: the nickname of your identity."); TextField { text <=> form.nickname; label: @tr("Nickname"); icon: Icons.user; } } - Field { - label: @tr("Server password"); - TextField { text <=> form.server-password; input-type: InputType.password; label: @tr("Server password"); icon: Icons.lock; } + Text { + text: @tr("Invisible presence and chat without joining"); + font-weight: Theme.weight-semibold; + color: Theme.text; + wrap: word-wrap; } - } - Text { - text: @tr("Invisible presence and chat without joining (optional)"); - font-weight: Theme.weight-semibold; - color: Theme.text; - wrap: word-wrap; - } - Field { - label: @tr("Gateway URL"); - TextField { text <=> form.gateway-url; placeholder: "wss://gw.example.org/v1"; label: @tr("Gateway URL"); } - } - HorizontalLayout { - spacing: Theme.space-4; Field { - label: @tr("Query transport"); - Select { - model: ["none", "ssh", "raw", "http"]; - current-value <=> form.query-transport; - current-index: form.query-transport == "ssh" ? 1 : form.query-transport == "raw" ? 2 : form.query-transport == "http" ? 3 : 0; + label: @tr("Gateway URL"); + hint: @tr("Empty: looked up in DNS, as published by the server's admin."); + TextField { text <=> form.gateway-url; placeholder: @tr("Found automatically"); label: @tr("Gateway URL"); } + } + HorizontalLayout { + spacing: Theme.space-4; + Field { label: @tr("Query transport"); + Select { + model: ["none", "ssh", "raw", "http"]; + current-value <=> form.query-transport; + current-index: form.query-transport == "ssh" ? 1 : form.query-transport == "raw" ? 2 : form.query-transport == "http" ? 3 : 0; + label: @tr("Query transport"); + } + } + Field { + label: @tr("Query address"); + TextField { text <=> form.query-addr; placeholder: "ts.example.org:10022"; label: @tr("Query address"); } } } - Field { - label: @tr("Query address"); - TextField { text <=> form.query-addr; placeholder: "ts.example.org:10022"; label: @tr("Query address"); } - } - } - HorizontalLayout { - spacing: Theme.space-4; - Field { - label: @tr("Query login"); - TextField { text <=> form.query-user; label: @tr("Query login"); } - } - Field { - label: @tr("Query password"); - TextField { text <=> form.query-password; input-type: InputType.password; label: @tr("Query password"); } + HorizontalLayout { + spacing: Theme.space-4; + Field { + label: @tr("Query login"); + TextField { text <=> form.query-user; label: @tr("Query login"); } + } + Field { + label: @tr("Query password"); + TextField { text <=> form.query-password; input-type: InputType.password; label: @tr("Query password"); } + } } } } @@ -104,8 +133,8 @@ export component BookmarkDialog inherits Modal { } Button { kind: ButtonKind.primary; - text: @tr("Save"); - enabled: form.address != "" && form.nickname != ""; + text: form.id < 0 ? @tr("Add") : @tr("Save"); + enabled: form.address != ""; clicked => { Bridge.save-bookmark(form); done(); diff --git a/docs/gateway-admin.md b/docs/gateway-admin.md index d127964..5738d28 100644 --- a/docs/gateway-admin.md +++ b/docs/gateway-admin.md @@ -80,7 +80,65 @@ Every login, post and settings change is written to the audit table. 5. Install tsgw ([below](#install)), copy the example config to `/etc/tsgw/tsgw.toml` and set the query address and credentials (`TSGW_QUERY_PASSWORD` or `password_file`). -6. Run it behind TLS (Caddy, nginx) and give users the `wss://…/v1` URL. +6. Run it behind TLS (Caddy, nginx) and publish it in DNS + ([below](#letting-voelin-find-the-gateway)), so users only add the + server's address; or give them the `wss://…/v1` URL. + +## Letting Voelin find the gateway + +When a user adds a server by its address (`ts.example.org`), Voelin looks +for its gateway the way TeamSpeak looks for the voice server (SRV +`_ts3._udp`, then TSDNS), and uses what it finds as if the user had typed +the URL (the field stays editable under *Advanced*). It asks at the +server's host name and then at each parent domain down to the registered +domain, the most specific name first; for `ts.example.org` that is +`ts.example.org`, then `example.org`. It looks again when the server is +saved with an empty gateway URL and when it connects with voice. + +**DNS records** (preferred). An SRV record names the gateway's host and +port, the service name says whether it speaks TLS: + +| Record | Gives | +|---|---| +| `_tsgws._tcp. SRV ` | `wss://:/v1` (TLS, e.g. behind Caddy or nginx) | +| `_tsgw._tcp. SRV ` | `ws://:/v1` (plain, e.g. tsgw itself on 7788) | +| `_tsgws._tcp. TXT "path=/"` (optional, same for `_tsgw`) | another path than `/v1`, e.g. behind a reverse proxy | + +At the same name TLS wins; among several records of one name the lowest +priority. A target of `.` means "no gateway here" and the search goes on at +the parent domain. Examples (zone of `example.org`): + +```dns +; Behind a TLS proxy at gw.example.org that forwards /tsgw/v1 to tsgw: +_tsgws._tcp.example.org. 3600 IN SRV 0 0 443 gw.example.org. +_tsgws._tcp.example.org. 3600 IN TXT "path=/tsgw/v1" +; -> wss://gw.example.org:443/tsgw/v1 for ts.example.org, voice.example.org, … + +; tsgw itself, without TLS, next to the server ts.example.org: +_tsgw._tcp.ts.example.org. 3600 IN SRV 0 0 7788 ts.example.org. +; -> ws://ts.example.org:7788/v1, only for ts.example.org +``` + +One domain with several servers and several gateways: publish one record +per server host (`_tsgws._tcp.ts1.example.org`, `_tsgws._tcp.ts2.example.org`); +a record at the domain itself applies to every host below it that has none +of its own. + +**Without DNS records** (like TSDNS on port 41144): Voelin asks +`http://:7788/.well-known/tsgw` at the same names (and at an IP +address the server was added by). tsgw answers there with its URL, +`{"url": "…"}`: `listen.public_url` if set, else the address the request +came in on (`ws://:7788/v1`). So a tsgw that listens on the default +port on the server's host is found with no setup at all; behind a proxy, +set `listen.public_url` so the answer points at the proxy. + +Discovery is as trustworthy as DNS and the network, like TSDNS: prefer a +`_tsgws` record, so TLS proves the gateway is yours. Voelin checks a +`wss://` gateway's certificate against the system's certificate store, so +use one from a public CA (Caddy's automatic Let's Encrypt certificates +work); the Android app cannot reach `wss://` gateways yet (it has no +system store to read). A user logs in with +their own identity, and only when they choose to observe the server. ## Install diff --git a/docs/gateway-protocol.md b/docs/gateway-protocol.md index 41f2a85..28e3791 100644 --- a/docs/gateway-protocol.md +++ b/docs/gateway-protocol.md @@ -19,6 +19,11 @@ frame: {"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}} ``` +Next to it, `GET /.well-known/tsgw` answers `{"url": "…"}`, the URL apps +should use (`listen.public_url`, else the one the request came in on); apps +that find no DNS record ask there ([gateway-admin.md](gateway-admin.md#letting-voelin-find-the-gateway), +`voelin_core::discover`). + The client picks `id` for requests; the answer carries the same `id`. Pushes have no `id`. Version 1 only grows: new message types and optional fields. Both sides ignore unknown fields. The gateway answers a type it does diff --git a/docs/identity.md b/docs/identity.md index 65ee49f..fa33050 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -92,7 +92,7 @@ field carries the body. **Type 1, payload field 17, is an identity:** | 4 | bytes | empty in every row seen | | 5 | varint | 1 on exactly one identity: the selected one | -Voelin reads field 1 and field 2 and ignores the rest. The other item types +Voelin reads fields 1, 2 and 5 and ignores the rest. The other item types (0, 2, 3, 4, 5 — connection profiles, bookmarks, server lists and such) are **not** decoded; they are skipped by their type, not by guessing at their contents. @@ -168,6 +168,18 @@ voelinctl identity export [--store ] `--store` defaults to the desktop app's client database, `/voelin/client.db`, so the CLI and the app share identities. +**On every start** the app does the same as `import --auto` +(`voelin_core::identity::import_new`): identities found in the default +locations that the client database does not have yet are added, the files +are only read. The identity the official client uses by default (field 5 of +its payload, below) goes in first, so when Voelin has no identity of its own +yet, that one becomes Voelin's default (the first identity) and servers see +the same unique id; otherwise Voelin's default stays. What was imported is +shown once, in the status line (the toast on desktop), by nickname. The +runtime setting `identity.import_from_teamspeak` (default on) turns it off, +e.g. `--set identity.import_from_teamspeak=false`. The sample data of +`VOELIN_DEMO_UI` never imports. + - **Import** prints what it found as nickname, unique id and security level — all three are public, everything else in an identity is the private key — and stores each one through `voelin-store` under its nickname. An identity diff --git a/docs/screenshots/desktop-add-server.png b/docs/screenshots/desktop-add-server.png index 3bfae99..69b4019 100644 Binary files a/docs/screenshots/desktop-add-server.png and b/docs/screenshots/desktop-add-server.png differ diff --git a/docs/screenshots/mobile-add-server.png b/docs/screenshots/mobile-add-server.png new file mode 100644 index 0000000..e8b5132 Binary files /dev/null and b/docs/screenshots/mobile-add-server.png differ diff --git a/docs/ui.md b/docs/ui.md index b2976f9..6b570b8 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -200,6 +200,22 @@ goes to the running capture at once (`Capture::follow_audio`, which calls to add sources to. With sample data `share:live` shares the test pattern with the sample studio's sources, live at once with sample viewers. +## Adding a server + +The add-server dialog (`BookmarkDialog` in `screens/dialogs.slint`, logic in +`servers.rs`) asks for the address (host, host:port, IP or server +nickname; the resolver finds the port through SRV records and TSDNS) and +an optional server password. *Advanced* (open when editing) has the rest, +and empty fields there are filled in: the name is the address until the +first connection, then the server's own name (`adopt_server_name`); the +nickname is the default identity's (one imported from TeamSpeak keeps its +nickname there), else the system user's, else "Voelin user"; the identity is the default one, +there is no default channel; the gateway is looked up in DNS when the +server is saved without one and when it connects +([gateway-admin.md](gateway-admin.md#letting-voelin-find-the-gateway)), +and one found is stored as if typed. `bookmark` and `bookmark:edit` open +it (below). + ## Adding a screen 1. Write the screen in `ui/screens/.slint` from the components @@ -262,7 +278,7 @@ Environment variables (see `src/dev.rs`): - `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with emoji and a stream, without a server (nothing is stored). - `VOELIN_OPEN=[,...]`: `home`, `server`, `settings[:voice|keybinds|streaming|privacy|appearance]`, - `about`, `share[:live]`, `bookmark`, `emoji`, `client`, `panel`, `no-panel`, + `about`, `share[:live]`, `bookmark[:edit]`, `emoji`, `client`, `panel`, `no-panel`, `voice`, `pins`, `topics`, `topic:`, `member`, `watch`, `popout` (the server page, above), `tab:` (phone layout). With sample data, `watch` plays the local test pattern in the @@ -322,6 +338,7 @@ the window's size so the pointer is not over the window, and passes |---|---|---|---|---| | ![chat](screenshots/mobile-chat.png) | ![servers](screenshots/mobile-servers.png) | ![home](screenshots/mobile-home.png) | ![you](screenshots/mobile-you.png) | ![settings](screenshots/mobile-settings.png) | | ![voice channel](screenshots/mobile-voice.png) | ![activity](screenshots/mobile-activity.png) | ![studio](screenshots/mobile-studio.png) | ![share](screenshots/mobile-share.png) | ![sharing](screenshots/mobile-share-live.png) | +| ![add server](screenshots/mobile-add-server.png) | | | | | ## Limits