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 356bb0c6ac
21 files changed
+1294 -283

No files matched your search

+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,