myTS avatar, badges and User Tag from a saved session; banners; gateway logs and speed

Own account on TeamSpeak 6 servers:
- With only a saved session, the account's avatar and its certificate come
  from myTeamSpeak's avatar service (requestContactsAvatar for the own myTS
  ID), the signed badges from getSignedBadges and the User Tag's token from
  /tschat requestSignedAllowedIdentifierList; no password sign-in needed.
- tsproto::myts::Certificate checks a certificate chain as the server does
  (block types 4-7, leaf type 6, validity, key from the root, cofactorless
  Ed25519); each part is sent with a certificate that verifies it, in
  separate updatemytsdata commands when they differ, and cleared on sign-out.
- client_user_tag is set as the official client sets it
  ({"myts_token","tag","updated"}) on TeamSpeak 6 servers, after a
  self-check of the token; cleared on sign-out or an account change.
- Settings -> My Account shows the User Tag and lets the user choose up to
  three badges to show. The log says what the server published.

Banners:
- The URL (without query) is logged on the first failure; stalls, connect
  failures and missing answers are named; 400/404/410 are retried after
  15 minutes, then hourly; 429/503 honour Retry-After.
- Cached pictures are revalidated (ETag, Last-Modified); at most 6
  downloads per host; a User-Agent with the app version.
- The desktop portal's proxy (Linux) and the system proxy (Windows, macOS)
  are used, SOCKS included; redirects are followed hop by hop.

Gateway, client side:
- Only a refused login stops observing; retries after 1, 2, 5, 10, 20, then
  30 s with jitter, at once when voice connects; a 30 s keepalive.
- Discovery asks DNS and the well-known endpoints at once; observing is not
  restarted when the found list still holds the gateway in use.
- Info logs for discovery, attempts (with the stage that hung), connections,
  losses and the first presence.

tsgw:
- Logging setup (log.level, log.file with size rotation, colour only on a
  terminal) and lifecycle logs: startup summary, the address the server
  sees for queries, WebSocket connections, logins, refusals, slow requests,
  ServerQuery failures, relays and the observer.
- The lookup query connection reconnects after a TeamSpeak restart; query
  connects time out after 10 s; a silent server cannot wedge a connection;
  SIGTERM, startup while TeamSpeak is down and /health are handled.
- TCP_QUICKACK and one write per line: ~45 ms -> <2 ms per SSH command.
- One flood guard shared by all query connections (9 per 3 s, SSH auth
  counted, every connection holds on a 524).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
Claude committed 2026-10-06 18:28:09 +00:00
1 parent 1c2d5efd3a
commit 79a12654c8
56 files changed
+7405 -672

No files matched your search

+266 -4
View File
@@ -14,16 +14,113 @@
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
//! download (into a temporary path), later askers wait for the same
//! download ([`Cache::finish`] answers them all).
//!
//! A picture from the web keeps its host's validators (`ETag`,
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
//! again, it is downloaded only if it changed ([`Cache::validators`],
//! [`Arrived::Unchanged`]).
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::SystemTime;
use std::time::{Duration, SystemTime};
use tracing::debug;
/// Called with the cached file's path, or why it could not be fetched.
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, String>) + Send>;
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, FetchError>) + Send>;
/// Why a fetch failed (for the log), and when it may be tried again.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct FetchError {
pub text: String,
pub retry: RetryHint,
}
/// When a failed fetch may be tried again, as its host told.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum RetryHint {
/// Whenever the asker's own schedule says.
#[default]
Default,
/// Not before this long (the host's `Retry-After`).
After(Duration),
/// The address is wrong or gone (HTTP 400, 404, 410): not soon.
Permanent,
}
impl FetchError {
pub fn new(text: impl Into<String>, retry: RetryHint) -> Self {
Self { text: text.into(), retry }
}
}
impl From<String> for FetchError {
fn from(text: String) -> Self {
Self::new(text, RetryHint::Default)
}
}
impl From<&str> for FetchError {
fn from(text: &str) -> Self {
Self::new(text, RetryHint::Default)
}
}
impl fmt::Display for FetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
/// What a host said identifies the version of a picture it sent, to ask
/// later whether it changed (`If-None-Match`, `If-Modified-Since`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Validators {
pub etag: Option<String>,
pub last_modified: Option<String>,
}
impl Validators {
pub fn is_empty(&self) -> bool {
self.etag.is_none() && self.last_modified.is_none()
}
/// As kept: a `name: value` line each.
fn to_text(&self) -> String {
let mut text = String::new();
for (name, value) in [("etag", &self.etag), ("last-modified", &self.last_modified)] {
if let Some(value) = value {
text.push_str(&format!("{name}: {value}\n"));
}
}
text
}
fn from_text(text: &str) -> Self {
let mut validators = Self::default();
for line in text.lines() {
match line.split_once(": ") {
Some(("etag", value)) => validators.etag = Some(value.to_owned()),
Some(("last-modified", value)) => validators.last_modified = Some(value.to_owned()),
_ => {}
}
}
validators
}
}
/// How a download ended well.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Arrived {
/// In the temporary path, with what identifies its version (when the
/// host said).
File(Validators),
/// The host said the cached copy is still what it has (HTTP 304): the
/// copy stays, nothing was downloaded.
Unchanged,
}
/// What [`Cache::fetch`] decided.
pub(crate) enum Fetch {
@@ -199,10 +296,35 @@ impl Cache {
&self,
key: &str,
temp: &Path,
result: Result<(), String>,
result: Result<(), FetchError>,
max_bytes: u64,
) {
let result = result.and_then(|()| self.insert_file(key, temp, max_bytes));
let arrived = result.map(|()| Arrived::File(Validators::default()));
self.finish_with(key, temp, arrived, max_bytes);
}
/// [`finish`](Self::finish) a download from the web: a new file with
/// its validators, or the cached copy confirmed (kept, and marked as
/// used).
pub(crate) fn finish_with(
&self,
key: &str,
temp: &Path,
result: Result<Arrived, FetchError>,
max_bytes: u64,
) {
let result = result.and_then(|arrived| match arrived {
Arrived::File(validators) => {
let path = self.insert_file(key, temp, max_bytes)?;
self.keep_validators(key, &validators);
Ok(path)
}
Arrived::Unchanged => {
let mut index = self.lock();
self.touch(&mut index, key)
.ok_or_else(|| FetchError::from("cache: the copy was removed meanwhile"))
}
});
let _ = std::fs::remove_file(temp);
let waiters = self.lock().in_flight.remove(key).unwrap_or_default();
for waiter in waiters {
@@ -210,6 +332,32 @@ impl Cache {
}
}
/// What identifies the cached version of `key` (a picture from the
/// web), if it is cached and its host said.
pub(crate) fn validators(&self, key: &str) -> Option<Validators> {
if !self.lock().entries.contains_key(key) || !self.dir.join(key).is_file() {
return None;
}
let text = std::fs::read_to_string(validators_path(&self.dir, key)).ok()?;
Some(Validators::from_text(&text)).filter(|v| !v.is_empty())
}
/// Keep `validators` with `key`'s new file (none: the old ones go).
fn keep_validators(&self, key: &str, validators: &Validators) {
let path = validators_path(&self.dir, key);
if validators.is_empty() {
let _ = std::fs::remove_file(&path);
return;
}
let written = path
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&path, validators.to_text()));
if let Err(e) = written {
debug!("cache: cannot keep the validators of {key}: {e}");
}
}
/// Put a file we have (e.g. our own avatar) into the cache.
pub(crate) fn insert_copy(
&self,
@@ -264,6 +412,7 @@ impl Cache {
if let Err(e) = std::fs::remove_file(self.dir.join(&key)) {
debug!("cache: cannot remove {key}: {e}");
}
let _ = std::fs::remove_file(validators_path(&self.dir, &key));
}
}
@@ -297,6 +446,22 @@ fn scan(dir: &Path, index: &mut Index) {
index.lru.insert(tick, key.clone());
index.entries.insert(key, Entry { size, tick });
}
// Validators of pictures no longer here.
let Ok(kept) = std::fs::read_dir(dir.join(VALIDATORS).join("pictures")) else { return };
for entry in kept.flatten() {
let key = format!("pictures/{}", entry.file_name().to_string_lossy());
if !index.entries.contains_key(&key) {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// The directory of the pictures' validators.
const VALIDATORS: &str = "validators";
/// Where the validators of `key` are kept.
fn validators_path(dir: &Path, key: &str) -> PathBuf {
dir.join(VALIDATORS).join(key)
}
/// The engine's cache: one [`Cache`] that [`crate::Command::AttachCache`]
@@ -465,6 +630,103 @@ mod tests {
}
}
/// A picture keeps its host's validators; confirmed unchanged, the copy
/// stays and is used; replaced without validators or evicted, they go.
#[test]
fn validators_go_with_their_picture() {
let dir = temp_dir("validators");
let cache = Cache::new(&dir);
let key = picture_key("https://example.com/v.png").unwrap();
let validators = Validators {
etag: Some("W/\"v1\"".into()),
last_modified: Some("Tue, 06 Oct 2026 10:00:00 GMT".into()),
};
assert_eq!(cache.validators(&key), None);
let (tx, rx) = mpsc::channel();
let waiter = |tx: &mpsc::Sender<_>| -> Waiter {
let tx = tx.clone();
Box::new(move |r| tx.send(r).unwrap())
};
let Fetch::Download(temp) = cache.fetch(&key, false, waiter(&tx)) else { panic!() };
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"v1").unwrap();
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
let path = rx.recv().unwrap().unwrap();
assert_eq!(cache.validators(&key), Some(validators.clone()));
// Asked again: unchanged, the same file answers both askers.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
assert!(matches!(cache.fetch(&key, true, waiter(&tx)), Fetch::Waiting));
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
assert_eq!(std::fs::read(&path).unwrap(), b"v1");
// They survive a restart, with their picture.
assert_eq!(Cache::new(&dir).validators(&key), Some(validators.clone()));
// A new version without validators: the old ones are not sent again.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
// (The restart above cleared the temporary files' directory.)
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"new").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
rx.recv().unwrap().unwrap();
assert_eq!(cache.validators(&key), None);
// Evicted with the picture.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
std::fs::write(&temp, b"v2").unwrap();
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
rx.recv().unwrap().unwrap();
assert!(validators_path(&dir, &key).is_file());
put(&cache, "icons/1", 10, 10);
assert!(!path.exists());
assert!(!validators_path(&dir, &key).exists());
// Unchanged, but the copy went meanwhile: a failure, retried in full.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
assert!(rx.recv().unwrap().is_err());
std::fs::remove_dir_all(dir).unwrap();
}
/// A picture confirmed unchanged counts as used: others go first.
#[test]
fn an_unchanged_picture_counts_as_used() {
let dir = temp_dir("unchanged-used");
let cache = Cache::new(&dir);
let key = picture_key("https://example.com/u.png").unwrap();
let picture = put(&cache, &key, 400, 1000);
let icon = put(&cache, "icons/1", 400, 1000);
let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(|_| {})) else { panic!() };
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 1000);
put(&cache, "icons/2", 400, 1000);
assert!(picture.exists(), "the picture confirmed unchanged stays");
assert!(!icon.exists(), "the least recently used file goes");
std::fs::remove_dir_all(dir).unwrap();
}
/// Validators whose picture is gone go at the next start.
#[test]
fn orphaned_validators_are_removed() {
let dir = temp_dir("orphans");
let key = picture_key("https://example.com/o.png").unwrap();
let orphan = validators_path(&dir, &key);
std::fs::create_dir_all(orphan.parent().unwrap()).unwrap();
std::fs::write(&orphan, "etag: \"x\"\n").unwrap();
let cache = Cache::new(&dir);
assert_eq!(cache.size(), 0);
assert!(!orphan.exists());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn fetch_errors_carry_their_retry_hint() {
let error = FetchError::from("HTTP 503 Service Unavailable");
assert_eq!(error.retry, RetryHint::Default);
assert_eq!(error.to_string(), "HTTP 503 Service Unavailable");
let gone = FetchError::new("HTTP 404 Not Found", RetryHint::Permanent);
assert_ne!(gone, FetchError::from("HTTP 404 Not Found"));
let text = Validators { etag: Some("\"a: b\"".into()), last_modified: None }.to_text();
assert_eq!(Validators::from_text(&text).etag.as_deref(), Some("\"a: b\""));
}
/// Pictures are cached files like the others (counted after a restart).
#[test]
fn pictures_survive_restart() {
+308 -74
View File
@@ -12,9 +12,13 @@
//! without one. As TSDNS has its well-known port, the gateway itself is also
//! asked at tsgw's default port: `http://<name>:7788/.well-known/tsgw`
//! answers `{"url": "…"}`; for an IP address (or `localhost`) only that is
//! tried. That answer is plain HTTP, so it is asked only when nothing or a
//! tried. That answer is plain HTTP, so it is used only when nothing or a
//! plain record is published: a TLS-only publication stays TLS-only.
//!
//! Everything is asked at once (SRV and TXT at every name, and the gateway
//! at every name), so a discovery takes as long as its slowest needed
//! answer, not their sum; DNS gives up after 2 s (twice).
//!
//! The most specific name with a record wins: a parent domain's records
//! are another server's gateway when the host publishes its own. Every
//! gateway of that name is kept, best first (TLS before plain, by
@@ -23,11 +27,12 @@
//! to the plain gateway published next to it. Discovery trusts DNS and the
//! network as TSDNS does; falling back from a published `_tsgws` to a
//! published `_tsgw` is no weaker than publishing only `_tsgw`. What an
//! admin publishes is in `docs/gateway-admin.md`.
//! admin publishes is in `docs/gateway-admin.md`. Each discovery is logged
//! (target `voelin_core::discover`, the details at debug).
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};
use futures::future::{BoxFuture, FutureExt, join_all};
use hickory_resolver::TokioResolver;
@@ -36,7 +41,9 @@ use hickory_resolver::net::runtime::TokioRuntimeProvider;
use hickory_resolver::proto::rr::RData;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tracing::{debug, info};
/// The port tsgw listens on by default, where it is asked for its URL.
pub const DEFAULT_PORT: u16 = 7788;
@@ -44,6 +51,8 @@ pub const DEFAULT_PORT: u16 = 7788;
const DEFAULT_PATH: &str = "/v1";
/// Give up on asking one name's gateway after this long.
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
/// Give up on one DNS query after this long (it is sent twice).
const DNS_TIMEOUT: Duration = Duration::from_secs(2);
/// At most this many gateways are kept, best first.
const MAX_CANDIDATES: usize = 8;
@@ -65,21 +74,40 @@ struct Lookups {
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();
// connection's resolver does. A query that is not answered is sent
// again soon: discovery runs once a run, and finding nothing is
// final until the next.
let resolver = TokioResolver::builder_tokio()
.map(|mut b| {
let options = b.options_mut();
options.timeout = DNS_TIMEOUT;
options.attempts = options.attempts.max(2);
b
})
.and_then(|b| b.build())
.or_else(|_| {
let mut b = TokioResolver::builder_with_config(
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
TokioRuntimeProvider::default(),
);
b.options_mut().timeout = DNS_TIMEOUT;
b.build()
});
let resolver = match resolver {
Ok(resolver) => Some(resolver),
Err(e) => {
debug!(error = %e, "no DNS resolver for gateway discovery");
None
}
};
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()?;
let started = Instant::now();
let lookup = resolver?.srv_lookup(name.as_str()).await;
let lookup = dns_answer(&name, "SRV", started, lookup)?;
Some(
lookup
.answers()
@@ -97,7 +125,9 @@ impl Lookups {
txt: Arc::new(move |name| {
let resolver = txt_resolver.clone();
async move {
let lookup = resolver?.txt_lookup(name).await.ok()?;
let started = Instant::now();
let lookup = resolver?.txt_lookup(name.as_str()).await;
let lookup = dns_answer(&name, "TXT", started, lookup)?;
Some(
lookup
.answers()
@@ -116,7 +146,18 @@ impl Lookups {
}),
probe: Arc::new(|name| {
async move {
timeout(PROBE_TIMEOUT, well_known(&name, DEFAULT_PORT)).await.ok().flatten()
let started = Instant::now();
let answer = match timeout(PROBE_TIMEOUT, well_known(&name, DEFAULT_PORT)).await
{
Ok(answer) => answer,
Err(_) => Err(format!("no answer within {} s", PROBE_TIMEOUT.as_secs())),
};
let elapsed_ms = started.elapsed().as_millis() as u64;
match &answer {
Ok(url) => debug!(name, %url, elapsed_ms, "tsgw well-known probe answered"),
Err(outcome) => debug!(name, %outcome, elapsed_ms, "tsgw well-known probe"),
}
answer.ok()
}
.boxed()
}),
@@ -124,6 +165,27 @@ impl Lookups {
}
}
/// A DNS answer, the failure logged (no record at most names is normal).
fn dns_answer<T>(
name: &str,
kind: &str,
started: Instant,
lookup: Result<T, hickory_resolver::net::NetError>,
) -> Option<T> {
let elapsed_ms = started.elapsed().as_millis() as u64;
match lookup {
Ok(lookup) => Some(lookup),
Err(e) if e.is_no_records_found() => {
debug!(name, kind, elapsed_ms, "no DNS record");
None
}
Err(e) => {
debug!(name, kind, elapsed_ms, error = %e, "DNS lookup failed");
None
}
}
}
/// The URLs of the gateway of the server at `address` (as a bookmark has
/// it: host, host:port, an IP), best first: everything published, to be
/// tried in turn. Empty: none is published.
@@ -132,11 +194,16 @@ pub async fn gateways(address: &str) -> Vec<String> {
}
async fn gateways_with(address: &str, lookups: Lookups) -> Vec<String> {
let started = Instant::now();
let host = host_of(address);
let names = names(host);
if names.is_empty() {
debug!(address, "no gateway discovery for a server nickname");
return Vec::new();
}
// The gateway's own answer is asked at every name while DNS is; only
// the answer that counts is waited for.
let mut probes = Probes::start(&names, &lookups);
let srv = if host.parse::<IpAddr>().is_err() && host.contains('.') {
from_srv(&names, &lookups).await
} else {
@@ -145,22 +212,84 @@ async fn gateways_with(address: &str, lookups: Lookups) -> Vec<String> {
// The gateway's own answer comes over plain HTTP: not for a server that
// publishes only TLS; at the name that publishes, or without records the
// most specific name that answers.
let mut urls = match srv {
None => from_well_known(&names, &lookups).await.into_iter().collect(),
Some((name, mut urls)) => {
if urls.iter().any(|url| url.starts_with("ws://"))
&& let Some(url) = from_well_known(&[name], &lookups).await
&& !urls.contains(&url)
{
urls.push(url);
let (mut urls, well_known) = match &srv {
None => match probes.first().await {
Some((name, url)) => (vec![url.clone()], format!("{name}: {url}")),
None => (Vec::new(), "none".to_owned()),
},
Some(found) if found.urls.iter().any(|url| url.starts_with("ws://")) => {
let mut urls = found.urls.clone();
match probes.of(found.name).await {
Some(url) => {
let well_known = format!("{}: {url}", found.name);
if !urls.contains(&url) {
urls.push(url);
}
(urls, well_known)
}
None => (urls, "none".to_owned()),
}
urls
}
Some(found) => (found.urls.clone(), "not used (TLS only)".to_owned()),
};
urls.truncate(MAX_CANDIDATES);
let (srv_name, srv_urls, txt) = match &srv {
Some(found) => (found.name, found.urls.as_slice(), found.txt.as_slice()),
None => ("", &[][..], &[][..]),
};
info!(
address,
names = ?names,
srv_name,
srv = ?srv_urls,
txt = ?txt,
%well_known,
result = ?urls,
elapsed_ms = started.elapsed().as_millis() as u64,
"gateway discovery"
);
urls
}
/// The gateway's own answers being asked, one per name, most specific
/// first; those still asking when dropped are given up.
struct Probes<'a>(Vec<(&'a str, JoinHandle<Option<String>>)>);
impl<'a> Probes<'a> {
fn start(names: &[&'a str], lookups: &Lookups) -> Self {
Self(
names
.iter()
.map(|name| (*name, tokio::spawn((lookups.probe)(name.to_string()))))
.collect(),
)
}
/// The answer at `name`.
async fn of(&mut self, name: &str) -> Option<String> {
let (_, probe) = self.0.iter_mut().find(|(n, _)| *n == name)?;
probe.await.ok().flatten()
}
/// The answer of the most specific name that answers.
async fn first(&mut self) -> Option<(&'a str, String)> {
for (name, probe) in &mut self.0 {
if let Some(url) = probe.await.ok().flatten() {
return Some((*name, url));
}
}
None
}
}
impl Drop for Probes<'_> {
fn drop(&mut self) {
for (_, probe) in &self.0 {
probe.abort();
}
}
}
/// The host of an address: without the port, the brackets of an IPv6
/// address and a final dot.
fn host_of(address: &str) -> &str {
@@ -189,10 +318,20 @@ fn names(host: &str) -> Vec<&str> {
.collect()
}
/// The URLs from SRV records, every name and service asked at once: those
/// of the most specific name with a usable record (with that name), TLS
/// first, by priority.
async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<(&'a str, Vec<String>)> {
/// What SRV records publish: at `name`, the most specific name with a
/// usable record.
struct Published<'a> {
name: &'a str,
/// TLS first, by priority.
urls: Vec<String>,
/// The TXT strings at the records' names.
txt: Vec<String>,
}
/// The URLs from SRV records, every name and service asked at once, with
/// the TXT records there (the path; most names have none): those of the
/// most specific name with a usable record.
async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<Published<'a>> {
let queries: Vec<(&str, &str, String)> = names
.iter()
.flat_map(|name| {
@@ -202,38 +341,42 @@ async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<(&'a str,
]
})
.collect();
let answers = join_all(queries.iter().map(|(.., owner)| (lookups.srv)(owner.clone()))).await;
let (answers, texts) = futures::join!(
join_all(queries.iter().map(|(.., owner)| (lookups.srv)(owner.clone()))),
join_all(queries.iter().map(|(.., owner)| (lookups.txt)(owner.clone()))),
);
let mut found: Vec<_> = queries
.iter()
.zip(answers)
.filter_map(|(query, mut records)| {
.zip(texts)
.filter_map(|((query, mut records), txt)| {
// A target of "." says there is no such service there.
records.retain(|r| r.1 != ".");
records.sort_by_key(|r| r.0);
(!records.is_empty()).then_some((query, records))
(!records.is_empty()).then_some((query, records, txt))
})
.collect();
let name = found.first()?.0.0;
found.retain(|((n, ..), _)| *n == name);
let paths = join_all(found.iter().map(|((.., owner), _)| path_at(lookups, owner))).await;
let mut urls = Vec::new();
for (((_, scheme, _), records), path) in found.into_iter().zip(paths) {
found.retain(|((n, ..), ..)| *n == name);
let mut published = Published { name, urls: Vec::new(), txt: Vec::new() };
for ((_, scheme, _), records, txt) in found {
let path = path_in(&txt);
published.txt.extend(txt);
for (_, target, port) in records {
let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'));
if !urls.contains(&url) {
urls.push(url);
if !published.urls.contains(&url) {
published.urls.push(url);
}
}
}
Some((name, urls))
Some(published)
}
/// The path at a SRV record's name: `path=…` from its TXT records, `/v1`
/// without one.
async fn path_at(lookups: &Lookups, owner: &str) -> String {
let mut path = (lookups.txt)(owner.to_owned())
.await
.into_iter()
/// The path in a SRV record's name's TXT strings: `path=…`, `/v1` without
/// one.
fn path_in(txt: &[String]) -> String {
let mut path = txt
.iter()
.find_map(|s| s.strip_prefix("path=").map(str::to_owned))
.unwrap_or_else(|| DEFAULT_PATH.to_owned());
if !path.starts_with('/') {
@@ -242,31 +385,36 @@ async fn path_at(lookups: &Lookups, owner: &str) -> String {
path
}
/// 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], lookups: &Lookups) -> Option<String> {
let answers = join_all(names.iter().map(|name| (lookups.probe)((*name).to_owned()))).await;
answers.into_iter().flatten().next()
}
/// 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()?;
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`; else what
/// happened instead.
async fn well_known(host: &str, port: u16) -> Result<String, String> {
let mut stream =
TcpStream::connect((host, port)).await.map_err(|e| format!("cannot connect: {e}"))?;
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()?;
stream.write_all(request.as_bytes()).await.map_err(|e| format!("cannot ask: {e}"))?;
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;
stream
.take(16 * 1024)
.read_to_end(&mut response)
.await
.map_err(|e| format!("no answer: {e}"))?;
let response = String::from_utf8(response).map_err(|_| "not text".to_owned())?;
let (head, body) = response.split_once("\r\n\r\n").ok_or("not HTTP")?;
let status = head.split_whitespace().nth(1).unwrap_or_default();
if status != "200" {
return Err(format!("http {status}"));
}
let answer: serde_json::Value =
serde_json::from_str(body).map_err(|_| "not a tsgw answer".to_owned())?;
let url = answer.get("url").and_then(|url| url.as_str()).ok_or("no url in the answer")?;
if url.starts_with("ws://") || url.starts_with("wss://") {
Ok(url.to_owned())
} else {
Err(format!("not a gateway URL: {url}"))
}
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)]
@@ -308,8 +456,7 @@ mod tests {
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
lookups.probe = Arc::new(move |name| {
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok().flatten() }
.boxed()
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
});
lookups
}
@@ -416,21 +563,108 @@ mod tests {
);
}
/// The gateway's plain answer is asked with DNS, but not used.
#[tokio::test]
async fn a_tls_only_publication_is_not_widened() {
let asked = Arc::new(std::sync::atomic::AtomicBool::new(false));
let mut lookups =
fake(&[("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)], &[]);
let flag = asked.clone();
lookups.probe = Arc::new(move |_| {
flag.store(true, std::sync::atomic::Ordering::SeqCst);
futures::future::ready(Some("ws://ts.example.test:7788/v1".to_owned())).boxed()
});
let lookups = answering(
fake(&[("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)], &[]),
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
);
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["wss://gw.example.test:443/v1"]
);
assert!(!asked.load(std::sync::atomic::Ordering::SeqCst), "plain HTTP was asked");
}
/// `lookups` whose DNS answers take `dns` and the gateway's own `probe`.
fn slow(lookups: Lookups, dns: Duration, probe: Duration) -> Lookups {
let Lookups { srv, txt, probe: answer } = lookups;
Lookups {
srv: Arc::new(move |name| {
let found = srv(name);
async move {
tokio::time::sleep(dns).await;
found.await
}
.boxed()
}),
txt: Arc::new(move |name| {
let found = txt(name);
async move {
tokio::time::sleep(dns).await;
found.await
}
.boxed()
}),
probe: Arc::new(move |name| {
let found = answer(name);
async move {
tokio::time::sleep(probe).await;
found.await
}
.boxed()
}),
}
}
/// SRV, TXT and the gateway's own answer are asked at once: a slow
/// gateway and slow DNS cost the slower of them, not the sum; an answer
/// that is not used is not waited for.
#[tokio::test(start_paused = true)]
async fn everything_is_asked_at_once() {
let published = |srv: &[(&str, u16, &str, u16)]| {
answering(
fake(srv, &[("_tsgw._tcp.ts.example.test.", "path=/gw")]),
&[("ts.example.test", "wss://proxy.example.test/v1")],
)
};
let plain = [("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788)];
let (dns, probe) = (Duration::from_millis(400), Duration::from_millis(2500));
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", slow(published(&plain), dns, probe)).await,
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
);
assert_eq!(started.elapsed().as_millis(), 2500);
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", slow(published(&plain), probe, dns)).await,
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
);
assert_eq!(started.elapsed().as_millis(), 2500);
// TLS only: the gateway's plain answer is not waited for.
let tls = [("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)];
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", slow(published(&tls), dns, probe)).await,
["wss://gw.example.test:443/v1"]
);
assert_eq!(started.elapsed().as_millis(), 400);
}
/// Without records, the most specific name's gateway is waited for
/// before a parent domain's answer is taken.
#[tokio::test(start_paused = true)]
async fn without_records_the_most_specific_answer_wins() {
let mut lookups = fake(&[], &[]);
lookups.probe = Arc::new(|name| {
async move {
match name.as_str() {
"ts.example.test" => {
tokio::time::sleep(Duration::from_secs(2)).await;
Some("ws://ts.example.test:7788/v1".to_owned())
}
_ => Some("ws://example.test:7788/v1".to_owned()),
}
}
.boxed()
});
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["ws://ts.example.test:7788/v1"]
);
assert_eq!(started.elapsed().as_millis(), 2000);
}
#[tokio::test]
+476 -41
View File
@@ -38,14 +38,24 @@
//! and is removed when it ends. The directory is also where the session's
//! streams look for streams that started before we joined, next to the
//! server's `requeststreaminfo`.
//!
//! A gateway that cannot be reached, or cannot log us in yet (the server
//! does not know the identity before voice connected once; its server is
//! restarting), is tried again by itself: after 1, 2, 5, 10, 20, then every
//! 30 s, give or take 30 %, and at once when voice connects. Only a refused
//! login (signature, security level, ban, not allowed) ends it. A connection
//! is pinged every 30 s and left after 60 s without an answer. All of it is
//! logged (target `voelin_core::gateway`), never shown.
use std::time::Duration;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use futures::future::{Fuse, FusedFuture, FutureExt};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tracing::{debug, info, warn};
use voelin_gateway_proto::client::Login;
pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push};
use voelin_gateway_proto::client::{Login, Progress};
use voelin_gateway_proto::{
Action, ActivityEntry, ClientMsg, ConfigEntry, ErrorCode, EventInfo, EventQuery, EventSpec,
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
@@ -61,6 +71,10 @@ pub(crate) enum GatewayCmd {
OpenChat(ChatTarget),
CloseChat(ChatTarget),
SendChat(ChatTarget, String),
/// Waiting for the next attempt: make it now (voice connected, which
/// makes the identity known to the server; the server was selected
/// again). Nothing while connected.
RetryNow,
Stop,
}
@@ -82,9 +96,18 @@ pub(crate) enum GatewayEvent {
pub async fn connect(
url: &str,
identity: &tsclientlib::Identity,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
connect_watched(url, identity, &Progress::default()).await
}
/// [`connect`], telling `progress` each step (for the log).
async fn connect_watched(
url: &str,
identity: &tsclientlib::Identity,
progress: &Progress,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() };
voelin_gateway_proto::client::connect(url, login).await
voelin_gateway_proto::client::connect_watched(url, login, progress).await
}
/// Observe through the first of `urls` (best first, as published) that
@@ -96,36 +119,38 @@ pub(crate) async fn run(
events: mpsc::UnboundedSender<GatewayEvent>,
) {
// A gateway that is away (down, restarting, a network change, a proxy
// in front of it that fails) is tried again until the session stops
// observing; only a refused login ends it. A round tries every URL in
// turn without waiting; only a round that fails waits.
// in front of it that fails) or cannot log us in yet (it does not know
// the identity before voice connected once, its server is restarting)
// is tried again until the session stops observing; only a refused
// login ends it. A round tries every URL in turn without waiting; only
// a round that fails waits.
debug!(?urls, "gateway: starting");
let mut chats = Chats::default();
let mut failures = 0;
// What was logged per URL: once per cause, not every minute of a long
// absence.
let mut told: Vec<(String, String)> = Vec::new();
let mut told = Told::default();
// Why the last failed round failed.
let mut last_round: Option<String> = None;
// Attempts since observing started or the connection was lost.
let (mut attempts, mut since) = (0, Instant::now());
let reason = 'observe: loop {
let mut lost = None;
let mut index = 0;
while index < urls.len() {
attempts += 1;
let url = urls[index].clone();
match attempt(&url, &identity, &mut commands, &events, &mut chats).await {
let next = urls.get(index + 1).map(String::as_str);
debug!(%url, attempt = attempts, "gateway: trying");
let at = Try { url: &url, number: attempts, since, next };
match attempt(&at, &identity, &mut commands, &events, &mut chats, &mut told).await {
Ended::Stopped => break 'observe None,
Ended::Refused(reason) => break 'observe Some(reason),
Ended::Lost { reason, logged_in } => {
let next = urls.get(index + 1);
if told.iter().any(|(u, r)| *u == url && *r == reason) {
debug!(%url, error = %reason, ?next, "gateway still unreachable");
} else {
warn!(%url, error = %reason, ?next, "gateway unreachable");
told.retain(|(u, _)| *u != url);
told.push((url.clone(), reason.clone()));
}
lost = Some(reason);
if logged_in {
// It worked: it is tried first again, after a wait.
urls[..=index].rotate_right(1);
failures = 0;
(attempts, since) = (0, Instant::now());
break;
}
index += 1;
@@ -134,12 +159,22 @@ pub(crate) async fn run(
}
let Some(reason) = lost else { break None };
failures += 1;
let delay = retry_delay(failures);
let delay = retry_delay(failures, jitter());
// Past the longest wait, the same cause again is not news (a server
// only observed, never joined, cannot log us in at all).
let wait = delay.as_secs_f64();
if failures as usize > RETRY_SECONDS.len() && last_round.as_ref() == Some(&reason) {
debug!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
} else {
info!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
}
last_round = Some(reason.clone());
let _ = events.send(GatewayEvent::Retrying(reason));
if !chats.wait(delay, &mut commands).await {
break None;
}
};
debug!(?reason, "gateway: stopped");
let _ = events.send(GatewayEvent::Disconnected(reason));
}
@@ -149,20 +184,125 @@ enum Ended {
Stopped,
/// The gateway refused the login: trying again would not help.
Refused(String),
/// Not reached, or lost (after logging in): try again.
/// Not reached, not logged in yet, or lost (after logging in): try
/// again.
Lost { reason: String, logged_in: bool },
}
/// Login errors that trying again does not change: the identity or the
/// user is not allowed. Anything else (the gateway's server away, an
/// identity voice has not made known yet, too many logins) passes.
fn refused(code: ErrorCode) -> bool {
matches!(
code,
ErrorCode::AuthFailed | ErrorCode::LevelTooLow | ErrorCode::Banned | ErrorCode::Forbidden
)
}
/// One attempt of [`run`], for the log.
struct Try<'a> {
url: &'a str,
/// Since observing started, or the connection was lost; 1 first.
number: u32,
/// When observing started, or the connection was lost.
since: Instant,
/// The URL tried next in this round if this one fails.
next: Option<&'a str>,
}
/// What was logged per URL: each cause once while it lasts (until a login
/// works), not at every attempt of a long absence.
#[derive(Default)]
struct Told(Vec<(String, String)>);
impl Told {
/// Whether `url` failing with `cause` is news.
fn news(&mut self, url: &str, cause: &str) -> bool {
if self.0.iter().any(|(u, c)| u == url && c == cause) {
return false;
}
self.0.retain(|(u, _)| u != url);
self.0.push((url.to_owned(), cause.to_owned()));
true
}
}
/// One attempt to reach a gateway and log in (TCP, TLS, the WebSocket
/// upgrade, the login's own queries at the gateway) gives up after this
/// long, so a gateway that never answers does not hold up the next one.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
/// The wait before the next attempt after `failures` failed ones in a row.
fn retry_delay(failures: u32) -> Duration {
const SECONDS: [u64; 5] = [2, 5, 15, 30, 60];
let index = (failures.max(1) as usize - 1).min(SECONDS.len() - 1);
Duration::from_secs(SECONDS[index])
/// The waits after failed rounds in a row, the last one repeated.
const RETRY_SECONDS: [u64; 6] = [1, 2, 5, 10, 20, 30];
/// The wait before the next attempt after `failures` failed rounds in a
/// row, give or take 30 % (`jitter`, -1 to 1): clients that lost the same
/// gateway do not all come back at the same moment.
fn retry_delay(failures: u32, jitter: f64) -> Duration {
let index = (failures.max(1) as usize - 1).min(RETRY_SECONDS.len() - 1);
Duration::from_secs(RETRY_SECONDS[index]).mul_f64(1.0 + 0.3 * jitter.clamp(-1.0, 1.0))
}
/// A number from -1 to 1, another each time: the standard library's
/// randomly keyed hasher over a counter and the clock.
fn jitter() -> f64 {
use std::hash::{BuildHasher, Hasher};
static COUNT: AtomicU64 = AtomicU64::new(0);
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u64(COUNT.fetch_add(1, Ordering::Relaxed));
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
hasher.write_u128(now.unwrap_or_default().as_nanos());
(hasher.finish() >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
}
/// Asking a gateway that is still connecting to try again at once, at most
/// this often ([`Observed::nudge`]): selecting servers does not hammer a
/// struggling gateway.
const NUDGE_EVERY: Duration = Duration::from_secs(5);
/// What a session's gateway observes with, so that asking again for the
/// same ([`crate::Command::ObserveGateway`], e.g. the server selected again)
/// does not start it over, at most makes it try again sooner.
pub(crate) struct Observed {
urls: Vec<String>,
/// The identity's public key.
key: String,
/// The identity's counter, which the login sends: a raised security
/// level keeps the key and changes only this.
counter: u64,
nudged: Option<Instant>,
}
impl Observed {
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
Self {
urls: urls.to_vec(),
key: identity.key().to_pub().to_ts(),
counter: identity.counter(),
nudged: None,
}
}
/// Whether this is what is observed with.
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
self.urls == urls
&& self.counter == identity.counter()
&& self.key == identity.key().to_pub().to_ts()
}
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
/// within [`NUDGE_EVERY`].
pub(crate) fn nudge(&mut self) -> bool {
self.nudge_at(Instant::now())
}
fn nudge_at(&mut self, now: Instant) -> bool {
if self.nudged.is_some_and(|at| now.saturating_duration_since(at) < NUDGE_EVERY) {
return false;
}
self.nudged = Some(now);
true
}
}
/// Messages written while the gateway is away, at most this many, go out
@@ -192,7 +332,7 @@ impl Chats {
self.unsent.push((target, text));
}
}
GatewayCmd::Stop => {}
GatewayCmd::RetryNow | GatewayCmd::Stop => {}
}
}
@@ -210,7 +350,7 @@ impl Chats {
client.send(ClientMsg::CloseChat { target })
}
GatewayCmd::SendChat(target, text) => client.send(ClientMsg::SendChat { target, text }),
GatewayCmd::Stop => Ok(()),
GatewayCmd::RetryNow | GatewayCmd::Stop => Ok(()),
}
}
@@ -226,7 +366,8 @@ impl Chats {
}
/// Wait `delay` before the next attempt, noting the commands that come
/// meanwhile; false when the session stops observing.
/// meanwhile, or until told to try now; false when the session stops
/// observing.
async fn wait(
&mut self,
delay: Duration,
@@ -239,6 +380,10 @@ impl Chats {
() = &mut sleep => return true,
cmd = commands.recv() => match cmd {
None | Some(GatewayCmd::Stop) => return false,
Some(GatewayCmd::RetryNow) => {
debug!("gateway: trying again now");
return true;
}
Some(cmd) => self.note(cmd),
},
}
@@ -256,32 +401,106 @@ const CHAT_EXTENSIONS: [&str; 4] = [
/// One connection: log in, then relay until it ends.
async fn attempt(
url: &str,
at: &Try<'_>,
identity: &tsclientlib::Identity,
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
events: &mpsc::UnboundedSender<GatewayEvent>,
chats: &mut Chats,
told: &mut Told,
) -> Ended {
let url = at.url;
let lost = |reason: String| Ended::Lost { reason, logged_in: false };
let (client, mut pushes) =
match tokio::time::timeout(CONNECT_TIMEOUT, connect(url, identity)).await {
Ok(Ok(connected)) => connected,
Ok(Err(ClientError::Gateway { code, message })) => {
warn!(%url, ?code, %message, "gateway refused the login");
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
let progress = Progress::default();
let started = Instant::now();
let result =
tokio::time::timeout(CONNECT_TIMEOUT, connect_watched(url, identity, &progress)).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
let (stage, peer) = (progress.stage(), progress.peer_addr());
let (client, mut pushes) = match result {
Ok(Ok(connected)) => connected,
Ok(Err(ClientError::Gateway { code, message })) if refused(code) => {
warn!(%url, ?code, %message, "gateway refused the login");
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
}
// Observing starts before voice: on a server we never joined, the
// first login cannot work. Voice connecting makes it try again.
Ok(Err(ClientError::Gateway { code: ErrorCode::UnknownIdentity, message })) => {
if told.news(url, "unknown identity") {
info!(%url, elapsed_ms, "the server does not know this identity yet (voice connects it); trying again");
} else {
debug!(%url, elapsed_ms, "the server does not know this identity yet");
}
Ok(Err(e)) => return lost(e.to_string()),
Err(_) => return lost(format!("no answer within {} s", CONNECT_TIMEOUT.as_secs())),
};
info!(%url, server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
let reason = match relay(url, &client, &mut pushes, commands, events, chats).await {
return lost(format!("UnknownIdentity: {message}"));
}
Ok(Err(ClientError::Gateway { code, message })) => {
if told.news(url, &format!("{code:?}")) {
warn!(%url, ?code, %message, elapsed_ms, next = ?at.next, "gateway did not log us in; trying again");
} else {
debug!(%url, ?code, %message, elapsed_ms, "gateway still does not log us in");
}
return lost(format!("{code:?}: {message}"));
}
Ok(Err(e)) => {
let reason = e.to_string();
if told.news(url, &reason) {
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, error = %reason, next = ?at.next, "gateway unreachable");
} else {
debug!(%url, %stage, steps = %progress, elapsed_ms, error = %reason, "gateway still unreachable");
}
return lost(reason);
}
Err(_) => {
let reason = format!("no answer within {} s ({stage})", CONNECT_TIMEOUT.as_secs());
if told.news(url, &reason) {
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, next = ?at.next, "gateway unreachable: {reason}");
} else {
debug!(%url, %stage, steps = %progress, elapsed_ms, "gateway still unreachable: {reason}");
}
return lost(reason);
}
};
*told = Told::default();
info!(
%url,
attempt = at.number,
connect_ms = elapsed_ms,
since_start_ms = at.since.elapsed().as_millis() as u64,
server = %client.info().server_name,
?peer,
steps = %progress,
capabilities = ?client.capabilities(),
"gateway connected"
);
let connected = Instant::now();
let reason = match relay(url, &client, &mut pushes, commands, events, chats, connected).await {
Ok(Ended::Lost { reason, .. }) => reason,
Ok(ended) => return ended,
Ok(ended) => {
debug!(%url, connected_for_s = connected.elapsed().as_secs(), "gateway: left");
return ended;
}
Err(e) => e.to_string(),
};
warn!(%url, connected_for_s = connected.elapsed().as_secs(), error = %reason, "gateway connection lost");
Ended::Lost { reason, logged_in: true }
}
/// A connection is checked this often while nothing else asks the gateway
/// anything ([`ClientMsg::Ping`])…
const PING_EVERY: Duration = Duration::from_secs(30);
/// …and taken as lost without an answer within this long (the gateway
/// answers in turn, after requests that can take a while).
const PING_TIMEOUT: Duration = Duration::from_secs(60);
/// Whether the gateway still answers: a ping, answered in time.
async fn alive(client: &GatewayClient) -> Result<(), String> {
match tokio::time::timeout(PING_TIMEOUT, client.request(ClientMsg::Ping)).await {
// Any answer will do, also an error from an older gateway.
Ok(Ok(_) | Err(ClientError::Gateway { .. })) => Ok(()),
Ok(Err(e)) => Err(e.to_string()),
Err(_) => Err(format!("no answer to a ping within {} s", PING_TIMEOUT.as_secs())),
}
}
async fn relay(
url: &str,
client: &GatewayClient,
@@ -289,6 +508,7 @@ async fn relay(
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
events: &mpsc::UnboundedSender<GatewayEvent>,
chats: &mut Chats,
connected: Instant,
) -> Result<Ended, ClientError> {
let lost = |reason: String| Ended::Lost { reason, logged_in: true };
// Messages with their gateway ids, pins, reactions and topics of open
@@ -300,6 +520,14 @@ async fn relay(
client.subscribe_presence()?;
chats.restore(client)?;
let mut presence = Presence::default();
let mut synced = false;
// A connection that died without closing (a network change, sleep, a
// NAT that forgot it) shows only when the gateway stops answering.
let start = tokio::time::Instant::now() + PING_EVERY;
let mut keepalive = tokio::time::interval_at(start, PING_EVERY);
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let ping = Fuse::terminated();
tokio::pin!(ping);
loop {
tokio::select! {
@@ -310,6 +538,16 @@ async fn relay(
Some(Push::Disconnected(Some(reason))) => return Ok(lost(reason)),
Some(Push::PresenceSnapshot(snapshot)) => {
presence = Presence::from_snapshot(snapshot);
if !synced {
synced = true;
info!(
%url,
channels = presence.channels.len(),
clients = presence.clients.len(),
since_connect_ms = connected.elapsed().as_millis() as u64,
"gateway presence"
);
}
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
}
Some(Push::PresenceDelta(delta)) => {
@@ -330,6 +568,12 @@ async fn relay(
None | Some(GatewayCmd::Stop) => return Ok(Ended::Stopped),
Some(cmd) => chats.apply(client, cmd)?,
},
_ = keepalive.tick(), if ping.is_terminated() => ping.set(alive(client).fuse()),
answer = &mut ping => {
if let Err(reason) = answer {
return Ok(lost(reason));
}
}
}
}
}
@@ -906,3 +1150,194 @@ pub(crate) struct ReactionPush {
pub added: bool,
pub count: u32,
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use futures::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::Message;
use voelin_gateway_proto::{Envelope, ServerMsg};
use super::*;
fn millis(d: Duration) -> u64 {
(d.as_secs_f64() * 1000.0).round() as u64
}
#[test]
fn retries_come_soon_then_every_30_s_spread() {
let seconds: Vec<u64> = (0..=8).map(|n| retry_delay(n, 0.0).as_secs()).collect();
assert_eq!(seconds, [1, 1, 2, 5, 10, 20, 30, 30, 30]);
// Give or take 30 %.
assert_eq!(millis(retry_delay(1, -1.0)), 700);
assert_eq!(millis(retry_delay(1, 1.0)), 1300);
assert_eq!(millis(retry_delay(6, 1.0)), 39_000);
assert_eq!(millis(retry_delay(3, 7.0)), millis(retry_delay(3, 1.0)));
let samples: Vec<f64> = (0..1000).map(|_| jitter()).collect();
assert!(samples.iter().all(|j| (-1.0..1.0).contains(j)), "{samples:?}");
assert!(samples.iter().any(|j| *j < -0.5) && samples.iter().any(|j| *j > 0.5));
}
#[test]
fn the_same_observation_is_nudged_at_most_every_5_s() {
let identity = tsclientlib::Identity::create();
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
let mut observed = Observed::new(&urls, &identity);
assert!(observed.same(&urls, &identity));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
// Its security level raised: logged in with the new counter.
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
assert!(!observed.same(&urls, &raised));
let now = Instant::now();
assert!(observed.nudge_at(now));
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
assert!(observed.nudge_at(now + NUDGE_EVERY));
assert!(!observed.nudge_at(now + NUDGE_EVERY + Duration::from_secs(1)));
}
#[test]
fn only_some_login_errors_are_final() {
use ErrorCode as E;
for code in [E::AuthFailed, E::LevelTooLow, E::Banned, E::Forbidden] {
assert!(refused(code), "{code:?}");
}
for code in [
E::Unavailable,
E::Internal,
E::RateLimited,
E::UnknownIdentity,
E::NotAuthenticated,
E::BadRequest,
E::Unknown,
] {
assert!(!refused(code), "{code:?}");
}
}
#[tokio::test(start_paused = true)]
async fn retry_now_ends_the_wait() {
let (tx, mut rx) = mpsc::unbounded_channel();
let mut chats = Chats::default();
let start = tokio::time::Instant::now();
// What comes meanwhile is noted; RetryNow ends the wait at once.
tx.send(GatewayCmd::OpenChat(ChatTarget::Channel(1))).unwrap();
tx.send(GatewayCmd::RetryNow).unwrap();
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
assert_eq!(start.elapsed(), Duration::ZERO);
assert_eq!(chats.open, [ChatTarget::Channel(1)]);
// Told 3 s into a wait of 30.
let told = tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(3)).await;
tx.send(GatewayCmd::RetryNow).unwrap();
tx
});
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
assert_eq!(millis(start.elapsed()), 3000);
let tx = told.await.unwrap();
// Not told: the whole wait.
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
assert_eq!(millis(start.elapsed()), 33_000);
tx.send(GatewayCmd::Stop).unwrap();
assert!(!chats.wait(Duration::from_secs(30), &mut rx).await);
}
/// A logged-in client of a gateway on an in-memory connection that
/// answers pings when `pings`; counts the pings.
async fn gateway(
pings: bool,
) -> (GatewayClient, mpsc::UnboundedReceiver<Push>, Arc<AtomicUsize>) {
let (near, far) = tokio::io::duplex(64 * 1024);
let count = Arc::new(AtomicUsize::new(0));
let counted = count.clone();
tokio::spawn(async move {
let mut ws = tokio_tungstenite::accept_async(far).await.unwrap();
let hello = ServerMsg::Hello {
gateway_id: "gw".into(),
server_uid: "server".into(),
server_name: "Server".into(),
nonce: "n".into(),
capabilities: Vec::new(),
};
let text = serde_json::to_string(&Envelope::new(hello)).unwrap();
ws.send(Message::Text(text.into())).await.unwrap();
while let Some(Ok(frame)) = ws.next().await {
let Message::Text(text) = frame else { continue };
let env: Envelope<ClientMsg> = serde_json::from_str(text.as_str()).unwrap();
let reply = match env.msg {
ClientMsg::Resume { .. } => ServerMsg::AuthOk {
uid: "me".into(),
token: "t".into(),
token_expires: 0,
capabilities: Vec::new(),
},
ClientMsg::Ping => {
counted.fetch_add(1, Ordering::SeqCst);
if !pings {
continue;
}
ServerMsg::Pong
}
_ => ServerMsg::Ok,
};
let text = serde_json::to_string(&Envelope::with_id(env.id.unwrap_or(0), reply));
if ws.send(Message::Text(text.unwrap().into())).await.is_err() {
break;
}
}
});
let (ws, _) = tokio_tungstenite::client_async("ws://gw.test/v1", near).await.unwrap();
let (client, pushes) = GatewayClient::start(ws, Login::Token("t".into())).await.unwrap();
(client, pushes, count)
}
#[tokio::test(start_paused = true)]
async fn a_gateway_that_stops_answering_is_left() {
let (client, mut pushes, pings) = gateway(false).await;
let (_tx, mut commands) = mpsc::unbounded_channel();
let (events, _events) = mpsc::unbounded_channel();
let start = tokio::time::Instant::now();
let mut chats = Chats::default();
let ended = relay(
"ws://gw.test/v1",
&client,
&mut pushes,
&mut commands,
&events,
&mut chats,
Instant::now(),
)
.await
.unwrap();
let Ended::Lost { reason, logged_in: true } = ended else { panic!("not lost") };
assert!(reason.contains("ping"), "{reason}");
assert_eq!(millis(start.elapsed()), millis(PING_EVERY + PING_TIMEOUT));
assert_eq!(pings.load(Ordering::SeqCst), 1);
}
#[tokio::test(start_paused = true)]
async fn a_gateway_that_answers_pings_is_kept() {
let (client, mut pushes, pings) = gateway(true).await;
let (_tx, mut commands) = mpsc::unbounded_channel();
let (events, _events) = mpsc::unbounded_channel();
let mut chats = Chats::default();
let relayed = tokio::time::timeout(
// The 20th ping at 600 s, answered.
Duration::from_secs(615),
relay(
"ws://gw.test/v1",
&client,
&mut pushes,
&mut commands,
&events,
&mut chats,
Instant::now(),
),
)
.await;
assert!(relayed.is_err(), "the connection was left");
assert_eq!(pings.load(Ordering::SeqCst), 20);
}
}
+9 -4
View File
@@ -98,6 +98,8 @@ use voelin_stream::{
pub use voice::VoiceOptions;
/// Banners are downloaded and shown by the same rule.
pub use web::is_svg;
/// Pictures from the web go through the desktop's proxy (set at startup).
pub use web::set_proxy_resolver;
pub type SessionId = u64;
@@ -106,9 +108,10 @@ pub type SessionId = u64;
pub enum Command {
/// Main account proof for every current and future voice connection.
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
/// What voice servers are shown of the main account (its certificate
/// and avatar, TeamSpeak 6): sent to every connection that presents the
/// account, once connected and when it changes.
/// What voice servers are shown of the main account (its avatar and
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
/// every connection that presents the account's myTS ID, once connected
/// and when it changes; cleared on a sign-out.
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
ConnectVoice {
session: SessionId,
@@ -119,7 +122,9 @@ pub enum Command {
},
/// Invisible presence and relay chat through a `tsgw` gateway: the first
/// of `urls` (best first, [`discover::gateways`]) that logs in, tried in
/// turn again whenever it is lost.
/// turn again whenever it is lost. Sent again with the same `urls` and
/// identity while it runs, it is not started over; while still
/// connecting, it tries again at once (at most every 5 s).
ObserveGateway {
session: SessionId,
urls: Vec<String>,
+262 -25
View File
@@ -23,7 +23,7 @@ use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
use voelin_stream::ClientState;
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
use crate::cache::{self, Fetch, SharedCache, Waiter};
use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter};
use crate::contacts::{Contacts, Relation};
use crate::files::{self, DownloadTo, Report, RequestId, Sink, TransferId, TransferState};
use crate::gateway::{
@@ -121,7 +121,7 @@ enum SourceEvent {
/// Time to fetch the host banner again (`banner_gfx_interval_s`).
ReloadBanner(String),
/// Image completion is checked against the current connection and presence.
ImageFinished(bool, u64, ImageRequest, Result<PathBuf, String>),
ImageFinished(bool, u64, ImageRequest, Result<PathBuf, FetchError>),
}
/// Identity of a wanted image, independent of its transport.
@@ -156,6 +156,7 @@ struct ImageDownload {
impl ImageDownload {
fn finish(&self, result: Result<(), String>) {
if !self.done.swap(true, Ordering::AcqRel) {
let result = result.map_err(FetchError::from);
self.cache.finish(&self.key, &self.temp, result, max_cache_bytes(&self.settings));
}
}
@@ -169,40 +170,89 @@ impl Drop for ImageDownload {
/// Retries per image version ([`retry_delay`]). Keeping exhausted entries
/// prevents presence traffic from causing a retry storm.
#[derive(Default)]
struct ImageRetry {
failures: u8,
due: Option<Instant>,
/// Its host asked to wait until `due` (`Retry-After`): the host
/// banner's reloads wait too.
busy: bool,
/// Its address was found wrong or gone (HTTP 400, 404, 410).
gone: bool,
}
/// When to try an image again after its `failures`-th failed download:
/// a banner after 1, 4, 16, 60, 300 and 900 seconds, then every 15 minutes
/// while it is shown (its host may be away for a while); avatars and icons
/// after 1, 4 and 16 seconds, then no more.
fn retry_delay(request: &ImageRequest, failures: u8) -> Option<Duration> {
/// When to try an image again after its `failures`-th failed download,
/// which ended as `hint` says (`gone`: its address was found wrong or gone
/// before). A banner after 1, 4, 16, 60, 300 and 900 seconds, then every
/// 15 minutes while it is shown (its host may be away for a while); one
/// whose address is wrong or gone after 15 minutes, then every hour; one
/// whose host is busy when it says. Avatars and icons after 1, 4 and 16
/// seconds, then no more.
fn retry_delay(
request: &ImageRequest,
failures: u8,
hint: RetryHint,
gone: bool,
) -> Option<Duration> {
const BANNERS: [u64; 6] = [1, 4, 16, 60, 300, 900];
let failures = usize::from(failures.max(1));
match request {
ImageRequest::Picture(_) => Some(Duration::from_secs(BANNERS[(failures - 1).min(5)])),
match (request, hint) {
(ImageRequest::Picture(_), RetryHint::Permanent) => {
Some(Duration::from_secs(if gone { 3600 } else { 900 }))
}
(ImageRequest::Picture(_), RetryHint::After(wait)) => Some(wait),
(ImageRequest::Picture(_), RetryHint::Default) => {
Some(Duration::from_secs(BANNERS[(failures - 1).min(5)]))
}
_ if failures <= 3 => Some(Duration::from_secs(1 << (2 * (failures - 1)))),
_ => None,
}
}
/// A failed image download in the log, with what it was and why (the
/// host, never the whole address): banners at once, avatars and icons in
/// the server's files when they give up (their files unreachable, a
/// closed file transfer port).
/// A failed image download in the log, with what it was and why: banners
/// at once, with the address the first time (its host, port and path: a
/// query may be a signed link's secret) and the host after, and once when
/// their address is found wrong or gone (`newly_gone`; `reload_s`: the
/// host banner's reload interval); avatars and icons in the server's files
/// when they give up (their files unreachable, a closed file transfer
/// port).
fn log_image_failure(
request: &ImageRequest,
failures: u8,
retry_in: Option<Duration>,
error: &str,
error: &FetchError,
newly_gone: bool,
reload_s: Option<u64>,
) {
let retry_in_s = retry_in.map(|d| d.as_secs());
match request {
ImageRequest::Picture(url) if failures <= 6 => {
ImageRequest::Picture(url)
if newly_gone || (failures <= 6 && error.retry != RetryHint::Permanent) =>
{
let host = web::host_of(url);
info!(%host, failures, ?retry_in_s, %error, "banner not downloaded");
let url = (failures == 1).then(|| web::loggable(url));
let what = match (newly_gone, reload_s) {
(false, _) => "banner not downloaded",
(true, None) => {
"banner not downloaded: its address is wrong or gone, so it is tried again only \
after 15 minutes, then hourly"
}
(true, Some(_)) => {
"host banner not downloaded: its address is wrong or gone, so it is tried again \
only at the server's reload interval, or hourly"
}
};
match url {
Some(url) => {
info!(%host, %url, failures, ?retry_in_s, ?reload_s, %error, "{what}");
}
None => info!(%host, failures, ?retry_in_s, ?reload_s, %error, "{what}"),
}
}
// Not the address: a query may be a signed link's secret.
ImageRequest::Picture(url) => {
let host = web::host_of(url);
debug!(%host, failures, ?retry_in_s, %error, "banner not downloaded");
}
ImageRequest::MytsAvatar { url, .. } if retry_in.is_none() => {
let host = web::host_of(url);
@@ -246,6 +296,9 @@ struct Session {
gateway_presence: Option<Presence>,
/// The logged-in gateway, for requests.
gateway_client: Option<GatewayClient>,
/// What the running `gateway` observes with: asking again for the same
/// does not start it over.
gateway_observed: Option<gateway::Observed>,
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
@@ -354,6 +407,7 @@ impl Session {
gateway: None,
gateway_presence: None,
gateway_client: None,
gateway_observed: None,
query: None,
query_presence: None,
audio: None,
@@ -480,6 +534,17 @@ impl Session {
}
}
Command::ObserveGateway { urls, identity, .. } => {
// Asked again for the same (the server selected again): not
// started over; while still connecting, it tries again now
// (not every time: a struggling gateway is not hammered).
if let (Some((_, tx)), Some(observed)) = (&self.gateway, &mut self.gateway_observed)
&& observed.same(&urls, &identity)
{
if self.state.observe == ObserveState::Connecting && observed.nudge() {
let _ = tx.send(GatewayCmd::RetryNow);
}
return;
}
self.stop_observing();
if urls.is_empty() {
return;
@@ -492,6 +557,7 @@ impl Session {
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
self.gateway_observed = Some(gateway::Observed::new(&urls, &identity));
tokio::spawn(gateway::run(urls, *identity, cmd_rx, ev_tx));
self.forward(ev_rx, move |e| SourceEvent::Gateway(generation, e));
self.gateway = Some((generation, cmd_tx));
@@ -1027,7 +1093,7 @@ impl Session {
requested: bool,
epoch: u64,
request: ImageRequest,
result: Result<PathBuf, String>,
result: Result<PathBuf, FetchError>,
) {
let wanted = if requested {
match &request {
@@ -1091,14 +1157,23 @@ impl Session {
ImageRequest::Avatar { uid, hash } => Some((uid.clone(), hash.clone())),
_ => None,
};
let retry = self
.image_retries
.entry(request.clone())
.or_insert(ImageRetry { failures: 0, due: None });
// The host banner is asked for again at its reload interval too.
let reload_s = match (&request, &self.banner_reload) {
(ImageRequest::Picture(url), Some((reloaded, every_s, _)))
if url == reloaded =>
{
Some((*every_s).max(web::MIN_RELOAD.as_secs()))
}
_ => None,
};
let retry = self.image_retries.entry(request.clone()).or_default();
retry.failures = retry.failures.saturating_add(1);
let delay = retry_delay(&request, retry.failures);
let delay = retry_delay(&request, retry.failures, error.retry, retry.gone);
retry.due = delay.map(|delay| Instant::now() + delay);
log_image_failure(&request, retry.failures, delay, &error);
retry.busy = matches!(error.retry, RetryHint::After(_));
let newly_gone = error.retry == RetryHint::Permanent && !retry.gone;
retry.gone |= newly_gone;
log_image_failure(&request, retry.failures, delay, &error, newly_gone, reload_s);
// The server's avatar gave up (its files unreachable): the
// myTeamSpeak one, if the client has one.
if let (None, Some((uid, hash))) = (retry.due, avatar_of)
@@ -1224,6 +1299,13 @@ impl Session {
}
}
/// Whether the host of the picture at `url` asked to wait
/// (`Retry-After`) and the wait is not over.
fn picture_host_busy(&self, url: &str) -> bool {
let retry = self.image_retries.get(&ImageRequest::Picture(url.into()));
retry.is_some_and(|r| r.busy && r.due.is_some_and(|due| due > Instant::now()))
}
/// Get the picture at `url` into the cache (again with `fresh`): from
/// the web, or from the server's files through the voice connection.
fn fetch_picture(&self, url: &str, fresh: bool) {
@@ -1647,6 +1729,7 @@ impl Session {
if let Some((_, tx)) = self.gateway.take() {
let _ = tx.send(GatewayCmd::Stop);
}
self.gateway_observed = None;
if let Some((_, tx)) = self.query.take() {
let _ = tx.send(QueryCmd::Stop);
}
@@ -1759,6 +1842,7 @@ impl Session {
if let Some((url, ..)) = &self.banner_reload
&& *url == address
&& self.settings.current().get(&CACHE_FETCH_IMAGES)
&& !self.picture_host_busy(url)
{
self.fetch_picture(url, true);
}
@@ -1777,6 +1861,13 @@ impl Session {
}
self.learn_server_uid(server_uid, Source::Voice);
self.emit_state();
// The server knows our identity now: a gateway that could not
// log us in before (on a server we never joined) tries at once.
if self.state.observe == ObserveState::Connecting
&& let Some((_, tx)) = &self.gateway
{
let _ = tx.send(GatewayCmd::RetryNow);
}
let capabilities = flavor.capabilities();
if capabilities.streams
&& let Some((generation, voice)) = &self.voice
@@ -1925,6 +2016,7 @@ impl Session {
}
GatewayEvent::Disconnected(reason) => {
self.gateway = None;
self.gateway_observed = None;
self.gateway_gone(reason.clone());
self.gateway_presence = None;
self.state.observe = ObserveState::Off;
@@ -2315,13 +2407,136 @@ mod banner_tests {
#[test]
fn banners_keep_trying_avatars_and_icons_give_up() {
let banner = ImageRequest::Picture("https://example.com/b.png".into());
let delays: Vec<_> = (1..=8).map(|f| retry_delay(&banner, f).unwrap().as_secs()).collect();
let delay = |f, hint, gone| retry_delay(&banner, f, hint, gone).map(|d| d.as_secs());
let delays: Vec<_> =
(1..=8).map(|f| delay(f, RetryHint::Default, false).unwrap()).collect();
assert_eq!(delays, [1, 4, 16, 60, 300, 900, 900, 900]);
// An address wrong or gone: after 15 minutes, then every hour.
assert_eq!(delay(1, RetryHint::Permanent, false), Some(900));
assert_eq!(delay(2, RetryHint::Permanent, true), Some(3600));
// A busy host: when it says.
assert_eq!(delay(1, RetryHint::After(Duration::from_secs(120)), false), Some(120));
let icon = ImageRequest::Icon(1234);
let delays: Vec<_> = (1..=4).map(|f| retry_delay(&icon, f).map(|d| d.as_secs())).collect();
let delays: Vec<_> = (1..=4)
.map(|f| retry_delay(&icon, f, RetryHint::Default, false).map(|d| d.as_secs()))
.collect();
assert_eq!(delays, [Some(1), Some(4), Some(16), None]);
}
/// A banner whose address is wrong or gone is tried again after 15
/// minutes, then every hour, until the connection is made again; a
/// busy host's banner waits as long as it asks, and so do its reloads.
#[tokio::test]
async fn banners_wait_as_their_hosts_say() {
let (mut session, _events) = session("hints");
let url = "https://example.com/gone.png";
let request = ImageRequest::Picture(url.into());
let wait = |session: &Session, request: &ImageRequest| {
let due = session.image_retries[request].due.unwrap();
due.saturating_duration_since(Instant::now()).as_secs_f64().round() as u64
};
let gone = || Err(FetchError::new("HTTP 404 Not Found", RetryHint::Permanent));
session.pictures.insert(url.into());
session.image_finished(false, session.image_epoch, request.clone(), gone());
assert_eq!(wait(&session, &request), 900);
assert!(session.image_retries[&request].gone);
session.image_finished(false, session.image_epoch, request.clone(), gone());
assert_eq!(wait(&session, &request), 3600);
// Something else in between: the usual schedule.
let failed = Err("timed out".into());
session.image_finished(false, session.image_epoch, request.clone(), failed);
assert_eq!(wait(&session, &request), 16);
// Connected again: from the start.
session.forget_images();
session.pictures.insert(url.into());
session.image_finished(false, session.image_epoch, request.clone(), gone());
assert_eq!(wait(&session, &request), 900);
// The host banner of a busy host: its reloads wait too.
let banner = "https://example.com/busy.png";
let request = ImageRequest::Picture(banner.into());
session.pictures.insert(banner.into());
let timer = tokio::spawn(async {}).abort_handle();
session.banner_reload = Some((banner.into(), 60, timer));
let busy = FetchError::new("HTTP 429", RetryHint::After(Duration::from_secs(600)));
session.image_finished(false, session.image_epoch, request.clone(), Err(busy));
assert_eq!(wait(&session, &request), 600);
let cache = session.cache.current();
let key = cache::picture_key(banner).unwrap();
// Downloaded here, so a fetch by the session waits for this one.
let reload = |session: &mut Session| {
let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(|_| {})) else {
panic!("own download");
};
session.source_event(SourceEvent::ReloadBanner(banner.into()));
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"picture").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
session.sources_rx.as_mut().unwrap().try_recv().is_ok()
};
assert!(!reload(&mut session), "reloaded while its host is busy");
session.image_retries.get_mut(&request).unwrap().due = Some(Instant::now());
assert!(reload(&mut session), "not reloaded once the wait was over");
std::fs::remove_dir_all(cache.dir()).unwrap();
}
/// What a failed download of `request` logs at info.
fn failure_lines(
session: &mut Session,
request: &ImageRequest,
result: Result<PathBuf, FetchError>,
) -> Vec<String> {
let epoch = session.image_epoch;
let finish = || session.image_finished(false, epoch, request.clone(), result);
web::tests::info_lines(finish).1
}
/// A failing banner's address is logged on its first failure, without
/// its query; that it is wrong or gone, once.
#[tokio::test]
async fn a_failing_banner_is_logged_once_with_its_address() {
let (mut session, _events) = session("log-once");
let url = "https://example.com/gone.png?sig=secret";
let request = ImageRequest::Picture(url.into());
session.pictures.insert(url.into());
let gone = || Err(FetchError::new("HTTP 404 Not Found", RetryHint::Permanent));
let lines = failure_lines(&mut session, &request, gone());
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(
lines[0].starts_with(
"banner not downloaded: its address is wrong or gone, so it is tried again only \
after 15 minutes, then hourly host=example.com url=https://example.com/gone.png \
failures=1 retry_in_s=Some(900)"
),
"{lines:?}"
);
assert!(!lines[0].contains("secret"), "{lines:?}");
assert_eq!(failure_lines(&mut session, &request, gone()), Vec::<String>::new());
// Something else meanwhile: by its host only.
let lines = failure_lines(&mut session, &request, Err("timed out".into()));
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(lines[0].starts_with("banner not downloaded host=example.com failures=3"));
assert!(!lines[0].contains("url="), "{lines:?}");
// The host banner is asked for at the server's reload interval too.
let banner = "https://example.com/host.png";
let request = ImageRequest::Picture(banner.into());
session.pictures.insert(banner.into());
let timer = tokio::spawn(async {}).abort_handle();
session.banner_reload = Some((banner.into(), 30, timer));
let lines = failure_lines(&mut session, &request, gone());
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(
lines[0].starts_with(
"host banner not downloaded: its address is wrong or gone, so it is tried again \
only at the server's reload interval, or hourly"
),
"{lines:?}"
);
assert!(lines[0].contains(" reload_s=Some(60) "), "{lines:?}");
let _ = std::fs::remove_dir_all(session.cache.current().dir());
}
#[tokio::test]
async fn retries_are_bounded_and_obey_policy_presence_and_epoch() {
let (mut session, mut events) = session("retry-guards");
@@ -2549,4 +2764,26 @@ mod banner_tests {
tokio::task::yield_now().await;
assert!(timer.is_finished());
}
#[tokio::test]
async fn voice_connected_wakes_a_gateway_still_connecting() {
let (mut session, _events) = session("gateway-wake");
let (tx, mut rx) = mpsc::unbounded_channel();
session.gateway = Some((session.next_generation(), tx));
let connected = || VoiceEvent::Connected {
name: "test".into(),
flavor: voelin_model::ServerFlavor::Unknown(String::new()),
own_client: 1,
server_uid: "server=".into(),
own_uid: None,
};
session.state.observe = ObserveState::Connecting;
session.voice_event(connected());
assert!(matches!(rx.try_recv(), Ok(GatewayCmd::RetryNow)));
assert!(rx.try_recv().is_err());
// Logged in already: nothing to hurry.
session.state.observe = ObserveState::Observing;
session.voice_event(connected());
assert!(rx.try_recv().is_err());
}
}
+277 -35
View File
@@ -227,6 +227,32 @@ fn now_ms() -> i64 {
.unwrap_or_default()
}
/// What `client_user_tag` is to be set to, if anything: on servers that
/// know it (`user_tags`), the tag `wanted` where `shown` is another (or
/// none), or `again` after a new account proof; empty (cleared) where one
/// is shown that is no longer wanted.
fn user_tag_update(
wanted: Option<&tsclientlib::UserTag>,
shown: Option<&tsclientlib::UserTag>,
user_tags: bool,
again: bool,
now_ms: i64,
) -> Option<String> {
match (wanted, shown) {
_ if !user_tags => None,
(Some(tag), shown) if again || shown != Some(tag) => Some(tag.value(now_ms)),
(None, Some(_)) => Some(String::new()),
_ => None,
}
}
/// Which of the badges sent (`sent`, their ids) the server does not
/// publish (`client_signed_badges`: the ids that verified, joined by `,`).
fn badges_dropped<'a>(sent: &'a [String], published: &str) -> Vec<&'a str> {
let published: Vec<&str> = published.split(',').collect();
sent.iter().map(String::as_str).filter(|id| !published.contains(id)).collect()
}
enum Input {
MytsIdentityChanged,
MytsDataChanged,
@@ -239,8 +265,16 @@ enum Input {
/// A command waiting for the server's answer.
enum Pending {
MytsIdentity(Instant),
/// `updatemytsdata`: its answer is only logged.
MytsData,
/// `updatemytsdata`: whether it showed the avatar and the badges (else
/// it cleared them), and the ids of the badges shown; what the server
/// published is only logged.
MytsData {
avatar: Option<bool>,
badges: Option<bool>,
badge_ids: Vec<String>,
},
/// `clientupdate client_user_tag`: the value (empty: cleared); only logged.
UserTag(String),
Stream(Request),
FileList {
request: RequestId,
@@ -352,6 +386,9 @@ struct Voice {
/// `updatemytsdata` is to be sent once connected again: a reconnect
/// (tsclientlib's own) leaves the server without it.
myts_data_due: bool,
/// What this connection has shown the server of the account (avatar,
/// badges, User Tag): what changes, and what a sign-out clears.
myts_shown: tsclientlib::MytsData,
}
async fn run_inner(
@@ -447,12 +484,13 @@ async fn run_inner(
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
myts_shown: tsclientlib::MytsData::default(),
};
voice.publish_state()?;
// The account's avatar, for everyone on the server (as the official
// client, once connected).
// The account's avatar, badges and User Tag, for everyone on the
// server (as the official client, once connected).
data.borrow_and_update();
voice.send_myts_data();
voice.send_myts_data(true);
let mut tick = tokio::time::interval(Duration::from_millis(250));
let result = loop {
@@ -477,13 +515,14 @@ async fn run_inner(
Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")),
}
// After the proof, what is shown of the account (a sign-in):
// its change, if any, is in this one.
// its change, if any, is in this one. All of it again: the
// server checks it for the myTS ID it holds when it comes.
data.borrow_and_update();
voice.send_myts_data();
voice.send_myts_data(true);
}
Input::MytsDataChanged => {
data.borrow_and_update();
voice.send_myts_data();
voice.send_myts_data(false);
}
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
Input::Item(Some(Err(e))) => break Err(e.into()),
@@ -598,7 +637,7 @@ impl Voice {
}
// Connected again after a reconnect.
if self.myts_data_due {
self.send_myts_data();
self.send_myts_data(true);
}
self.publish_state()?;
}
@@ -682,7 +721,9 @@ impl Voice {
}
StreamItem::DisconnectedTemporarily(reason) => {
warn!(?reason, "voice connection interrupted, reconnecting");
// A new client on the server: it shows nothing of the account.
self.myts_data_due = true;
self.myts_shown = tsclientlib::MytsData::default();
}
_ => {}
}
@@ -841,9 +882,29 @@ impl Voice {
self.link.emit(Event::OfflineMessage { session, request, result });
}
Pending::Quiet | Pending::MytsIdentity(_) => {}
Pending::MytsData => match result {
Ok(()) => debug!("the server took the account's avatar"),
Err(e) => warn!(error = %e, "the server refused the account's avatar"),
Pending::MytsData { avatar, badges, badge_ids } => match result {
Ok(()) => self.myts_published(avatar, badges, &badge_ids),
Err(TsError::ParameterInvalid) => warn!(
"the server refused the account's myTeamSpeak certificate (error 1538): it \
is expired, revoked or not a myTeamSpeak signing certificate, or the \
server could not load myTeamSpeak's revocation list"
),
Err(e) => warn!(error = %e, "the server refused the account's avatar or badges"),
},
Pending::UserTag(value) => match result {
Ok(()) => {
let own = self.con.get_state().ok().and_then(|state| {
state.clients.get(&state.own_client).and_then(|c| c.user_tag.clone())
});
if value.is_empty() {
info!("the server no longer shows a User Tag for the account");
} else if own.as_deref() == Some(value.as_str()) {
info!("the server shows the account's User Tag");
} else {
warn!("the server took the account's User Tag but shows another value");
}
}
Err(e) => warn!(error = %e, "the server refused the account's User Tag"),
},
Pending::Report(what) => {
if let Err(e) = result {
@@ -853,24 +914,126 @@ impl Voice {
}
}
/// Show the server the account's certificate and avatar
/// (`updatemytsdata`), when connected with the account; while
/// What is to be shown of the account on this connection: what the UI
/// gave, when it is for the myTS ID this connection presents; nothing
/// without one (signed out).
fn myts_wanted(&self) -> tsclientlib::MytsData {
let identity = self.link.myts_identity.borrow();
let data = self.link.myts_data.borrow();
match (identity.as_deref(), data.as_deref()) {
(Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(),
_ => tsclientlib::MytsData::default(),
}
}
/// Whether the server knows the User Tag (TeamSpeak 6: it names
/// `client_user_tag` for our client, protocol 8 on).
fn has_user_tags(&self) -> bool {
self.con.get_state().is_ok_and(|state| {
state.server.protocol_version >= 8
|| state.clients.get(&state.own_client).is_some_and(|c| c.user_tag.is_some())
})
}
/// Show the server the account's avatar, badges and User Tag where it
/// shows something else (`updatemytsdata`, `clientupdate`), or clear
/// them; `again`: all of it, after a new account proof. While
/// reconnecting, once connected again.
fn send_myts_data(&mut self) {
fn send_myts_data(&mut self, again: bool) {
self.myts_data_due = false;
if self.link.myts_identity.borrow().is_none() {
if self.con.get_state().is_err() {
self.myts_data_due = true;
return;
}
let data = self.link.myts_data.borrow().clone();
let Some(data) = data.filter(|d| !d.certificate.is_empty()) else {
return;
};
match self.con.send_myts_data(&data) {
Ok(handle) => {
self.pending.insert(handle, Pending::MytsData);
let mut wanted = self.myts_wanted();
let user_tags = self.has_user_tags();
if !user_tags {
wanted.user_tag = None;
}
for update in wanted.updates(&self.myts_shown, again) {
let shows = |part: &Option<Vec<u8>>| part.as_ref().map(|data| !data.is_empty());
let (avatar, badges) = (shows(&update.avatar), shows(&update.badges));
let badge_ids =
if badges == Some(true) { wanted.badge_ids.clone() } else { Vec::new() };
info!(
avatar = ?avatar.map(|shown| if shown { "shown" } else { "cleared" }),
badges = ?badges.map(|shown| if shown { "shown" } else { "cleared" }),
?badge_ids,
"telling the server what to show of the account (updatemytsdata)"
);
match self.con.send_myts_update(&update) {
Ok(handle) => {
let pending = Pending::MytsData { avatar, badges, badge_ids };
self.pending.insert(handle, pending);
}
Err(tsclientlib::Error::NotConnected) => {
self.myts_data_due = true;
return;
}
Err(e) => warn!(error = %e, "the account's avatar or badges were not sent"),
}
Err(tsclientlib::Error::NotConnected) => self.myts_data_due = true,
Err(e) => warn!(error = %e, "the account's avatar was not sent"),
}
let shown = self.myts_shown.user_tag.as_ref();
if let Some(value) =
user_tag_update(wanted.user_tag.as_ref(), shown, user_tags, again, now_ms())
{
match &wanted.user_tag {
Some(tag) if !value.is_empty() => {
info!(tag = %tag.tag, "setting the account's User Tag")
}
_ => info!("clearing the account's User Tag"),
}
match self.con.send_user_tag(&value) {
Ok(handle) => {
self.pending.insert(handle, Pending::UserTag(value));
}
Err(tsclientlib::Error::NotConnected) => {
self.myts_data_due = true;
return;
}
Err(e) => warn!(error = %e, "the account's User Tag was not sent"),
}
}
self.myts_shown = wanted;
}
/// What the server published of an `updatemytsdata` it took: it says so
/// for our client before its answer, and shows nothing of what does not
/// verify, without an error.
fn myts_published(&self, avatar: Option<bool>, badges: Option<bool>, badge_ids: &[String]) {
let Ok(state) = self.con.get_state() else { return };
let Some(own) = state.clients.get(&state.own_client) else { return };
let has_id = own.my_team_speak_id.as_deref().is_some_and(|id| !id.is_empty());
let why = if has_id {
"its signature does not verify with the certificate for the account's myTS ID"
} else {
"the server holds no myTS ID for this client (the account proof was not accepted)"
};
match avatar {
Some(true) if own.my_team_speak_avatar.as_deref().is_some_and(|a| !a.is_empty()) => {
info!("the server shows the account's avatar")
}
Some(true) => warn!(why, "the server took the account's avatar but shows none"),
Some(false) => info!("the server no longer shows an avatar for the account"),
None => {}
}
let published = own.signed_badges.as_deref().unwrap_or_default();
let dropped = badges_dropped(badge_ids, published);
match badges {
Some(true) if published.is_empty() => {
warn!(why, "the server took the account's badges but shows none")
}
Some(true) if dropped.is_empty() => {
info!(published, "the server shows the account's badges")
}
Some(true) => warn!(
published,
?dropped,
"the server shows only some of the account's badges: the others' signatures do \
not verify for the account's myTS ID"
),
Some(false) => info!("the server no longer shows badges for the account"),
None => {}
}
}
@@ -1216,12 +1379,57 @@ mod account_tests {
assert!(network > 0 && timers > 0 && audio > 0);
}
/// A reconnect (tsclientlib's own) leaves the server without the
/// account's avatar: it goes again once connected, not before.
#[tokio::test]
async fn account_data_waits_for_the_connection() {
// A silent UDP peer: never connected.
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
fn account_data(myts_id: &[u8]) -> tsclientlib::MytsData {
let signed = |data: &[u8]| tsclientlib::Signed { certificate: vec![1], data: data.into() };
tsclientlib::MytsData {
myts_id: myts_id.to_vec(),
avatar: signed(b"avatar"),
badges: signed(b"badges"),
badge_ids: vec!["b1".into()],
user_tag: Some(tsclientlib::UserTag {
tag: "a@myteamspeak.com".into(),
token: vec![2],
}),
}
}
/// The User Tag is set where it is not shown yet, or after a new account
/// proof, and cleared where it is no longer wanted: on TeamSpeak 6
/// servers only.
#[test]
fn the_user_tag_is_set_where_it_changed() {
let tag = |tag: &str| tsclientlib::UserTag { tag: tag.into(), token: vec![2] };
let (a, b) = (tag("a@myteamspeak.com"), tag("b@myteamspeak.com"));
let update =
|wanted, shown, user_tags, again| user_tag_update(wanted, shown, user_tags, again, 5);
let set = Some(a.value(5));
assert!(set.as_deref().unwrap().starts_with(r#"{"myts_token":"Ag==","tag":"a@"#));
assert_eq!(update(Some(&a), None, true, false), set);
assert_eq!(update(Some(&a), Some(&a), true, false), None, "unchanged");
assert_eq!(update(Some(&a), Some(&a), true, true), set, "after a new account proof");
assert_eq!(update(Some(&a), Some(&b), true, false), set, "another tag");
assert_eq!(update(None, Some(&a), true, false).as_deref(), Some(""), "cleared");
assert_eq!(update(None, Some(&a), true, true).as_deref(), Some(""));
assert_eq!(update(None, None, true, true), None, "nothing to clear");
// Not a TeamSpeak 6 server: nothing, set or cleared.
assert_eq!(update(Some(&a), None, false, true), None);
assert_eq!(update(None, Some(&a), false, false), None);
}
/// The server publishes the ids of the badges that verified.
#[test]
fn badges_the_server_dropped_are_named() {
let sent: Vec<String> = ["b1", "b2", "b3"].map(String::from).to_vec();
assert!(badges_dropped(&sent, "b1,b2,b3").is_empty());
assert!(badges_dropped(&sent, "b3,b1,b2").is_empty());
assert_eq!(badges_dropped(&sent, "b1,b3"), ["b2"]);
assert_eq!(badges_dropped(&sent, ""), ["b1", "b2", "b3"]);
assert!(badges_dropped(&[], "b1").is_empty());
}
/// A voice source that never connects (a silent UDP peer) presenting
/// the account with myTS ID `[1; 33]`, told to show `data`.
fn unconnected(server: &tokio::net::UdpSocket, data: tsclientlib::MytsData) -> Voice {
// Scalar one and the standard compressed Edwards base point.
let mut private = [0; 32];
private[0] = 1;
@@ -1229,7 +1437,6 @@ mod account_tests {
public[0] = 0x58;
let identity =
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
let data = tsclientlib::MytsData { certificate: vec![1], avatar: Vec::new() };
let (events, _) = broadcast::channel(8);
let link = VoiceLink {
session: 1,
@@ -1238,7 +1445,7 @@ mod account_tests {
myts_identity: watch::channel(Some(Arc::new(identity))).1,
myts_data: watch::channel(Some(Arc::new(data))).1,
};
let mut voice = Voice {
Voice {
con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(),
link,
events: mpsc::unbounded_channel().0,
@@ -1248,19 +1455,54 @@ mod account_tests {
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
};
voice.send_myts_data();
myts_shown: tsclientlib::MytsData::default(),
}
}
/// A reconnect (tsclientlib's own) leaves the server without the
/// account's avatar: it goes again once connected, not before.
#[tokio::test]
async fn account_data_waits_for_the_connection() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let mut voice = unconnected(&server, account_data(&[1; 33]));
voice.send_myts_data(true);
assert!(voice.myts_data_due && voice.pending.is_empty());
assert_eq!(voice.myts_shown, tsclientlib::MytsData::default(), "nothing shown yet");
voice.myts_data_due = false;
voice.myts_shown = account_data(&[1; 33]);
let reconnecting = tsclientlib::TemporaryDisconnectReason::Timeout("test");
voice.item(StreamItem::DisconnectedTemporarily(reconnecting)).unwrap();
assert!(voice.myts_data_due);
assert_eq!(
voice.myts_shown,
tsclientlib::MytsData::default(),
"a new client shows nothing"
);
// Not connected yet: still due.
let _ = voice.item(StreamItem::BookEvents(Vec::new()));
assert!(voice.myts_data_due && voice.pending.is_empty());
timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap();
}
/// Only what is signed for the myTS ID the connection presents is shown.
#[tokio::test]
async fn account_data_is_for_the_presented_myts_id() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let voice = unconnected(&server, account_data(&[1; 33]));
assert_eq!(voice.myts_wanted(), account_data(&[1; 33]));
let other = unconnected(&server, account_data(&[2; 33]));
assert_eq!(other.myts_wanted(), tsclientlib::MytsData::default());
let mut signed_out = unconnected(&server, account_data(&[1; 33]));
signed_out.link.myts_identity = watch::channel(None).1;
assert_eq!(signed_out.myts_wanted(), tsclientlib::MytsData::default());
for voice in [voice, other, signed_out] {
timeout(Duration::from_millis(100), shutdown_connection(voice.con))
.await
.unwrap()
.unwrap();
}
}
#[tokio::test]
async fn shutdown_never_polls_a_connecting_connection() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
File diff suppressed because it is too large. Load diff