Merge the development branch: add a server by its address, TSDNS, gateway DNS

Both sides kept. From the development branch: the add-server dialog
asks for the address and an optional password (the rest under Advanced
when editing), servers are found through TSDNS and their gateways in
DNS, wss:// gateways, the official client's identities imported on
every start, and a bookmark built from the form over the old one.

The dialog keeps this wave's join mode for Home's "Join a Server": its
title says so, the button reads Join and connects once saved; adding
and editing read as on the development branch. Saving takes the
development branch's bookmark_from_form, which keeps the bookmark's
identity as this wave's code did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-04 04:29:59 +03:00
commit 013918cfc9
21 files changed
+1294 -283

No files matched your search

+18
View File
@@ -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.<domain>`
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 <ip>: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.<address>`, 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.
+344 -170
View File
@@ -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<T> = std::result::Result<T, Error>;
@@ -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.<address>`
/// 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<Item = Result<SocketAddr>> {
resolve_with(address, Lookups::system())
}
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Result<Vec<(String, u16)>>> + Send + Sync;
type HostFn = dyn Fn(String, u16) -> BoxFuture<'static, Result<Vec<SocketAddr>>> + 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<SrvFn>,
/// The addresses of a host name, with this port.
host: Arc<HostFn>,
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<Item = Result<SocketAddr>> {
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<BoxFuture<'static, Result<Vec<SocketAddr>>>> = 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::<Vec<_>>();
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<Result<SocketAddr>, _>| {
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<Vec<SocketAddr>> {
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.<domain>` 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<Vec<SocketAddr>> {
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<A: net::ToSocketAddrs>(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<A: net::ToSocketAddrs>(server: A, addr: &str) -> Resu
}
}
fn resolve_srv(resolver: TokioResolver, addr: String) -> impl Stream<Item = Result<SocketAddr>> {
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<Vec<(String, u16)>> {
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<T>(mut records: Vec<(u16, u16, T)>) -> Vec<T> {
// 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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<Result<(String, u16)>>>();
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::<Vec<_>>();
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<String> {
create_logger();
let found: Vec<SocketAddr> = 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"]);
}
}
}
+2
View File
@@ -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"] }
+340
View File
@@ -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.<name>`: `wss://<target>:<port><path>`,
//! - SRV `_tsgw._tcp.<name>`: `ws://<target>:<port><path>`,
//!
//! TLS first at the same name; `<path>` 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://<name>: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<String>> + 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<SrvFn>,
/// The strings of the TXT records at a name.
txt: Arc<TxtFn>,
/// 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<String> {
gateway_with(address, Lookups::system()).await
}
async fn gateway_with(address: &str, lookups: Lookups) -> Option<String> {
let host = host_of(address);
let names = names(host);
if names.is_empty() {
return None;
}
if host.parse::<IpAddr>().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::<IpAddr>().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<String> {
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<String> {
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://<host>:<port>/.well-known/tsgw`.
async fn well_known(host: &str, port: u16) -> Option<String> {
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());
}
}
+87 -12
View File
@@ -35,7 +35,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`.
@@ -77,6 +77,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 {
@@ -172,6 +174,26 @@ pub fn import(store: &Store, found: &[Found]) -> Result<Vec<Imported>, 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<Vec<Found>, IdentityError> {
let mut found: Vec<Found> = 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 {
@@ -372,7 +394,7 @@ fn record_identity(record: &[(String, String)], source: &Path) -> Option<Found>
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
@@ -393,22 +415,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<Found> {
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
@@ -537,13 +564,14 @@ mod tests {
}
}
/// An item of the shape both clients write, holding `identity`.
fn protobuf_item(identity: &Identity, nickname: &str) -> Vec<u8> {
/// 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<u8> {
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));
@@ -641,7 +669,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]),
] {
@@ -653,6 +681,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();
}
@@ -664,6 +738,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();
+1
View File
@@ -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;
+10
View File
@@ -1132,6 +1132,15 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = 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<bool> = 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<u32> = Key::new(
@@ -1336,6 +1345,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,
&PRIVACY_PRIVATE_MESSAGES,
+3 -1
View File
@@ -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" }
+18 -2
View File
@@ -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<Hub>) -> 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<Arc<Hub>>, headers: HeaderMap) -> Json<serde_json::Value> {
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<Arc<Hub>>, upgrade: WebSocketUpgrade) -> impl IntoResponse {
+34
View File
@@ -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");
}
+22 -4
View File
@@ -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::{
@@ -560,16 +561,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);
@@ -600,7 +615,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,
@@ -660,6 +674,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.
@@ -833,6 +850,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}"),
+8 -1
View File
@@ -12,7 +12,8 @@
//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer.
//! - `VOELIN_OPEN=<what>[,<what>...]`: open screens on start: `home`,
//! `server`, `settings[:<section>]` (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),
@@ -177,6 +178,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),
+233 -46
View File
@@ -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<String> {
let first = imported.first()?;
let n = imported.len();
let names = imported.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().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 channel =
@@ -32,6 +107,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) {
@@ -79,7 +225,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()
@@ -102,7 +248,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()),
@@ -115,49 +262,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: self.bookmark(form.id as i64).and_then(|b| b.identity),
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 {
@@ -183,6 +289,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) {
@@ -368,3 +475,83 @@ impl App {
self.refresh_tree();
}
}
#[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"
);
}
}
+72 -44
View File
@@ -15,76 +15,105 @@ 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 <BookmarkForm> form;
// Join by address: connect once saved.
in property <bool> join;
callback done();
// The fields beyond address and password: shown when editing.
property <bool> advanced: form.id >= 0;
title: join ? @tr("Join a server") : 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"); }
}
}
}
}
@@ -106,9 +135,8 @@ export component BookmarkDialog inherits Modal {
}
Button {
kind: ButtonKind.primary;
icon: root.join ? Icons.log-in : Icons.check;
text: root.join ? @tr("Save and connect") : @tr("Save");
enabled: form.address != "" && form.nickname != "";
text: root.join ? @tr("Join") : form.id < 0 ? @tr("Add") : @tr("Save");
enabled: form.address != "";
clicked => {
Bridge.save-bookmark(form);
if root.join {