Merge PR #11: myTeamSpeak avatar, badges and User Tag; banners; gateway speed and logs

Conflicts and how they were resolved:
- CHANGELOG.md: both sides' lines kept under [Unreleased], each in its
  section; the badges line says TeamSpeak 6's verified badges come first.
- crates/proto/UPSTREAM.md: #11's myTeamSpeak presentation stays patch 15;
  this branch's privilege key (default_token) patch becomes 16.
- voelin-core web.rs: #11's downloader (retry hints, revalidation, proxies,
  per-host limits) as it is. The chat pictures' size limit sits on top as
  web::fetch_chat_picture, which narrows #11's Limits; fetch_within takes
  them by value. The badge pictures go through #11's fetch like banners.
- voelin-core session.rs: both sides' fields kept (chat_pictures and
  unfetchable). Chat pictures ([img]) are an ImageRequest of their own
  (ChatPicture) instead of sharing Picture with banners, so #11's banner
  policy (retried every 15 minutes while shown, logged by address) does
  not apply to them: they keep the 1, 4, 16 s retries and are checked
  against the size they were asked for; their failures are logged by host
  at debug level. Badge pictures stay Pictures next to #11's banner loop
  (with its unfetchable-scheme log).
- voelin-ui servers.rs: #11's imports (Instant, debug) with this branch's
  (no SharedString).

Where the two badge features meet: the presence's badges are now
voelin_model::shown_badges, TeamSpeak 6's client_signed_badges (what #11
sends for our account, and other TS6 users' verified badges) first, then
client_badges, each once; so the badges chosen in Settings → My Account
show in the tree and on the member card like other people's.

Also: docs/ui.md describes My Account's badge choice and User Tag, the
new ui.image_cache_mb default (256), and the picture downloads as #11 left
them (16 at once, 6 per host, 128 MiB, the new timeouts, banner and badge
retries, proxies, BMP and ICO, scaling down past 4096 pixels) with the
chat pictures' own retries; the demo's login:account switch fills in a
badge choice and a User Tag for screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
This commit is contained in:
Claude committed 2026-10-08 02:14:08 +00:00
commit 7ab43bbf60
71 files changed
+9022 -763

No files matched your search

+84 -22
View File
@@ -3,7 +3,7 @@
use tsclientlib::{ClientType, MaxClients, data};
use voelin_model::{
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode,
Presence, ServerDetails, parse_badges,
Presence, ServerDetails, myts_avatar_url, shown_badges,
};
fn group_info(
@@ -46,7 +46,7 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit,
},
banner_url: server.hostbanner_url.clone(),
banner_gfx_url: server.hostbanner_gfx_url.clone(),
banner_gfx_url: server.hostbanner_gfx_url.trim().to_owned(),
banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64,
banner_mode: match server.hostbanner_mode {
tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust,
@@ -117,7 +117,12 @@ pub(crate) fn presence_from_book(
needed_talk_power: c.needed_talk_power.unwrap_or(0),
is_default: c.is_default.unwrap_or(false),
icon: c.icon.map_or(0, |i| i.0),
banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()),
banner_gfx_url: c
.banner_gfx_url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.map(str::to_owned),
// A number the book keeps as text.
banner_mode: c
.banner_mode
@@ -149,11 +154,15 @@ pub(crate) fn presence_from_book(
server_groups,
country: Some(c.country_code.clone()).filter(|c| !c.is_empty()),
avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()),
myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url),
description: Some(c.description.clone()).filter(|d| !d.is_empty()),
talk_power: c.talk_power,
talker: c.talk_power_granted,
channel_group: Some(c.channel_group.0),
badges: parse_badges(&c.badges),
badges: shown_badges(
&c.badges,
c.signed_badges.as_deref().unwrap_or_default(),
),
icon: c.icon.0,
recording: c.is_recording,
priority_speaker: c.is_priority_speaker,
@@ -179,10 +188,8 @@ mod tests {
InMessage::new(&packet.header(), text.as_bytes()).unwrap()
}
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
/// in the channel list, when a channel is created and when it is edited.
#[test]
fn channel_banners() {
/// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`.
fn ts6_book() -> data::Connection {
let InMessage::InitServer(init) = message(concat!(
"initserver virtualserver_name=Test virtualserver_welcomemessage ",
"virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ",
@@ -202,20 +209,29 @@ mod tests {
)) else {
panic!("not an initserver");
};
let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init);
let channel = |cid: u64, order: u64, name: &str, banner: &str| {
format!(
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
channel_storage_quota=4294967295"
)
};
data::Connection::new(EccKeyPrivP256::create().to_pub(), &init)
}
/// A `channellist` entry as TeamSpeak 6 sends it.
fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String {
format!(
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
channel_storage_quota=4294967295"
)
}
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
/// in the channel list, when a channel is created and when it is edited.
#[test]
fn channel_banners() {
let mut book = ts6_book();
let list = format!(
"channellist {}|{}",
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
@@ -269,4 +285,50 @@ mod tests {
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
assert_eq!(p.server.priority_speaker_dimm_db, -18);
}
/// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it:
/// when the client enters and when it changes.
#[test]
fn myts_avatars() {
let mut book = ts6_book();
book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", ""))))
.unwrap();
let enter = |clid: u16, avatar: &str| {
format!(
"notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \
client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \
client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
client_output_hardware=1 client_meta_data client_is_recording=0 \
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \
client_talk_request=0 client_talk_request_msg client_is_talker=0 \
client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \
client_needed_serverquery_view_power=75 client_is_channel_commander=0 \
client_country=RU client_badges client_myteamspeak_id=m{clid} \
client_integrations{avatar}"
)
};
for text in [
enter(
5,
r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png",
),
// A TeamSpeak 3 server, or a client without one.
enter(6, ""),
enter(7, " client_myteamspeak_avatar"),
] {
book.handle_command(&message(&text)).unwrap();
}
let p = presence_from_book(&book, None, |_| false);
let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone();
assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png"));
assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None));
book.handle_command(&message(
r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png",
))
.unwrap();
let p = presence_from_book(&book, None, |_| false);
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
}
}
+270 -7
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 {
@@ -80,16 +177,17 @@ pub(crate) fn icon_key(id: u32) -> String {
/// The largest picture downloaded into the cache, from the web or from the
/// server's files: animated banners of several megabytes are common. The
/// download goes to disk as it arrives, so this bounds the disk, not memory.
pub(crate) const MAX_PICTURE_BYTES: u64 = 64 << 20;
pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
/// The slowest a picture may arrive on average after its first seconds:
/// a large banner on a slow link still arrives, one trickling in forever
/// does not hold a download slot.
pub(crate) const MIN_PICTURE_RATE: u64 = 32 << 10;
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
/// The cache key of a picture on the web: only `http` and `https`
/// addresses.
/// addresses (blanks around one are not part of it).
pub(crate) fn picture_key(url: &str) -> Option<String> {
let url = url.trim();
let (scheme, rest) = url.split_once("://")?;
let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
(web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url)))
@@ -198,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 {
@@ -209,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,
@@ -263,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));
}
}
@@ -296,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`]
@@ -464,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() {
+478 -90
View File
@@ -8,16 +8,31 @@
//! - 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`.
//! `<path>` is `path=…` from a TXT record at the SRV record's name, `/v1`
//! 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 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
//! priority, then the gateway's own answer at that name), and tried in turn
//! ([`crate::Command::ObserveGateway`]): a TLS proxy that fails falls back
//! 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`. 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;
@@ -26,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;
@@ -34,9 +51,14 @@ 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;
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync;
type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec<String>> + Send + Sync;
type ProbeFn = dyn Fn(String) -> BoxFuture<'static, Option<String>> + Send + Sync;
/// Where [`gateway`] gets its answers from; the tests put fakes in.
#[derive(Clone)]
@@ -45,28 +67,47 @@ struct Lookups {
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,
/// The URL a gateway at a name gives for itself (`/.well-known/tsgw`).
probe: Arc<ProbeFn>,
}
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()
@@ -84,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()
@@ -101,30 +144,150 @@ impl Lookups {
.map(Option::unwrap_or_default)
.boxed()
}),
probe_port: DEFAULT_PORT,
probe: Arc::new(|name| {
async move {
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()
}),
}
}
}
/// 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
/// 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
}
}
}
async fn gateway_with(address: &str, lookups: Lookups) -> Option<String> {
/// 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.
pub async fn gateways(address: &str) -> Vec<String> {
gateways_with(address, Lookups::system()).await
}
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() {
return None;
debug!(address, "no gateway discovery for a server nickname");
return Vec::new();
}
if host.parse::<IpAddr>().is_err()
&& host.contains('.')
&& let Some(url) = from_srv(&names, &lookups).await
{
return Some(url);
// 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 {
None
};
// 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, 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()),
}
}
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();
}
}
from_well_known(&names, lookups.probe_port).await
}
/// The host of an address: without the port, the brackets of an IPv6
@@ -155,59 +318,103 @@ fn names(host: &str) -> Vec<&str> {
.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
/// 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| {
[("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))]
[
(*name, "wss", format!("_tsgws._tcp.{name}.")),
(*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)| {
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)
.zip(texts)
.filter_map(|((query, mut records), txt)| {
// 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()
records.retain(|r| r.1 != ".");
records.sort_by_key(|r| r.0);
(!records.is_empty()).then_some((query, records, txt))
})
.collect();
let name = found.first()?.0.0;
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 !published.urls.contains(&url) {
published.urls.push(url);
}
}
}
Some(published)
}
/// 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('/') {
path.insert(0, '/');
}
Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')))
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], 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()?;
/// 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)]
@@ -215,8 +422,8 @@ 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 {
/// port)`, TXT `(name, string)`; no gateway answers for itself.
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)]) -> 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)> =
@@ -231,10 +438,29 @@ mod tests {
let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect();
futures::future::ready(found).boxed()
}),
probe_port,
probe: Arc::new(|_| futures::future::ready(None).boxed()),
}
}
/// `lookups` where the gateway at a name answers `(name, url)`.
fn answering(mut lookups: Lookups, answers: &[(&str, &str)]) -> Lookups {
let answers: Vec<(String, String)> =
answers.iter().map(|(n, u)| (n.to_string(), u.to_string())).collect();
lookups.probe = Arc::new(move |name| {
let url = answers.iter().find(|a| a.0 == name).map(|a| a.1.clone());
futures::future::ready(url).boxed()
});
lookups
}
/// `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()?.ok() }.boxed()
});
lookups
}
/// A port nothing listens on.
fn closed_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
@@ -242,20 +468,22 @@ mod tests {
#[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);
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[]);
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"),
gateways_with(address, lookups.clone()).await,
["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);
assert!(gateways_with("example", lookups).await.is_empty());
}
/// All of the most specific name's gateways, TLS first, by priority; a
/// parent domain's only for a host without its own.
#[tokio::test]
async fn the_most_specific_name_wins_then_tls() {
async fn the_most_specific_name_wins_with_all_its_gateways() {
let lookups = fake(
&[
("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443),
@@ -264,18 +492,181 @@ mod tests {
("_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")
gateways_with("ts.example.test", lookups.clone()).await,
[
"wss://tls.example.test:8443/tsgw/v1",
"wss://backup.example.test:443/tsgw/v1",
"ws://plain.example.test:7788/v1",
]
);
assert_eq!(
gateway_with("voice.example.test", lookups).await.as_deref(),
Some("wss://domain.example.test:443/v1")
gateways_with("voice.example.test", lookups).await,
["wss://domain.example.test:443/v1"]
);
}
/// A TLS proxy in front of tsgw and tsgw itself published next to the
/// server (and again at the domain): TLS first, the plain one after it,
/// once; the gateway's own answer is the plain one again.
#[tokio::test]
async fn a_tls_proxy_falls_back_to_the_published_plain_gateway() {
let lookups = answering(
fake(
&[
("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443),
("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788),
("_tsgw._tcp.example.test.", 0, "ts.example.test.", 7788),
],
&[],
),
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
);
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["wss://gw.example.test:443/v1", "ws://ts.example.test:7788/v1"]
);
}
/// A gateway at the domain fronts another server than one of its hosts
/// that publishes its own: never a fallback for it, nor the domain's own
/// answer.
#[tokio::test]
async fn another_servers_gateway_is_no_fallback() {
let lookups = answering(
fake(
&[
("_tsgws._tcp.ts1.example.test.", 0, "gw1.example.test.", 443),
("_tsgw._tcp.ts1.example.test.", 0, "ts1.example.test.", 7788),
("_tsgws._tcp.example.test.", 0, "gw-main.example.test.", 443),
],
&[],
),
&[("example.test", "ws://main.example.test:7788/v1")],
);
assert_eq!(
gateways_with("ts1.example.test", lookups).await,
["wss://gw1.example.test:443/v1", "ws://ts1.example.test:7788/v1"]
);
}
#[tokio::test]
async fn the_gateways_own_answer_comes_last() {
let lookups = answering(
fake(&[("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788)], &[]),
&[("ts.example.test", "wss://gw.example.test/v1")],
);
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["ws://plain.example.test:7788/v1", "wss://gw.example.test/v1"]
);
}
/// The gateway's plain answer is asked with DNS, but not used.
#[tokio::test]
async fn a_tls_only_publication_is_not_widened() {
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"]
);
}
/// `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]
async fn a_record_that_says_no_service_is_skipped() {
let lookups = fake(
@@ -284,12 +675,8 @@ mod tests {
("_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")
);
assert_eq!(gateways_with("ts.example.test", lookups).await, ["ws://gw.example.test:80/ws"]);
}
/// Without records the gateway next to the server answers at its port,
@@ -313,16 +700,17 @@ mod tests {
socket.write_all(response.as_bytes()).await.unwrap();
}
});
let lookups = fake(&[], &[], port);
let lookups = probing(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"),
gateways_with(address, lookups.clone()).await,
["wss://gw.example.test/v1"],
"{address}"
);
}
// Nothing there.
assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None);
let nothing = probing(fake(&[], &[]), closed_port());
assert!(gateways_with("127.0.0.1", nothing).await.is_empty());
}
#[test]
+520 -52
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,12 +71,16 @@ 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,
}
pub(crate) enum GatewayEvent {
/// Logged in; requests go through `client`.
Connected(GatewayClient),
/// Logged in at the URL; requests go through the client.
Connected(GatewayClient, String),
Presence(Box<Presence>),
/// A push other than presence.
Push(Box<Push>),
@@ -83,42 +97,84 @@ pub async fn connect(
url: &str,
identity: &tsclientlib::Identity,
) -> 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
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_watched(url, login, progress).await
}
/// Observe through the first of `urls` (best first, as published) that
/// logs in.
pub(crate) async fn run(
url: String,
mut urls: Vec<String>,
identity: tsclientlib::Identity,
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
events: mpsc::UnboundedSender<GatewayEvent>,
) {
// A gateway that is away (down, restarting, a network change) is tried
// again until the session stops observing; only a refused login ends it.
// A gateway that is away (down, restarting, a network change, a proxy
// 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;
let mut last_reason = String::new();
let reason = loop {
match attempt(&url, &identity, &mut commands, &events, &mut chats, &mut failures).await {
Ended::Stopped => break None,
Ended::Refused(reason) => break Some(reason),
Ended::Lost(reason) => {
failures += 1;
let delay = retry_delay(failures);
// Once per cause, not every minute of a long absence.
if reason != last_reason {
warn!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway unreachable");
} else {
debug!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway still unreachable");
}
last_reason.clone_from(&reason);
let _ = events.send(GatewayEvent::Retrying(reason));
if !chats.wait(delay, &mut commands).await {
break None;
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();
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 } => {
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;
}
}
}
let Some(reason) = lost else { break None };
failures += 1;
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));
}
@@ -128,15 +184,125 @@ enum Ended {
Stopped,
/// The gateway refused the login: trying again would not help.
Refused(String),
/// Not reached, or lost: try again.
Lost(String),
/// Not reached, not logged in yet, or lost (after logging in): try
/// again.
Lost { reason: String, logged_in: bool },
}
/// 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])
/// 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 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
@@ -166,7 +332,7 @@ impl Chats {
self.unsent.push((target, text));
}
}
GatewayCmd::Stop => {}
GatewayCmd::RetryNow | GatewayCmd::Stop => {}
}
}
@@ -184,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(()),
}
}
@@ -200,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,
@@ -213,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),
},
}
@@ -230,55 +401,153 @@ 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,
failures: &mut u32,
told: &mut Told,
) -> Ended {
let (client, mut pushes) = match connect(url, identity).await {
Ok(connected) => connected,
Err(ClientError::Gateway { code, message }) => {
let url = at.url;
let lost = |reason: String| Ended::Lost { reason, logged_in: false };
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}"));
}
Err(e) => return Ended::Lost(e.to_string()),
// 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");
}
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);
}
};
*failures = 0;
info!(%url, server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
match relay(&client, &mut pushes, commands, events, chats).await {
Ok(ended) => ended,
Err(e) => Ended::Lost(e.to_string()),
*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) => {
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,
pushes: &mut mpsc::UnboundedReceiver<Push>,
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
// chats (older gateways answer `unknown_type` as a push; ignored).
if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) {
client.send(ClientMsg::Enable { features: Vec::new() })?;
}
let _ = events.send(GatewayEvent::Connected(client.clone()));
let _ = events.send(GatewayEvent::Connected(client.clone(), url.to_owned()));
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! {
push = pushes.recv() => match push {
None | Some(Push::Disconnected(None)) => {
return Ok(Ended::Lost("the gateway closed the connection".into()));
return Ok(lost("the gateway closed the connection".into()));
}
Some(Push::Disconnected(Some(reason))) => return Ok(Ended::Lost(reason)),
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)) => {
@@ -289,7 +558,7 @@ async fn relay(
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
// The gateway forgot the login (restarted): log in again.
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
return Ok(Ended::Lost(format!("gateway session lost: {message}")));
return Ok(lost(format!("gateway session lost: {message}")));
}
Some(push) => {
let _ = events.send(GatewayEvent::Push(Box::new(push)));
@@ -299,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));
}
}
}
}
}
@@ -528,6 +803,8 @@ pub struct Pin {
pub enum GatewayUpdate {
/// Logged in.
Connected {
/// Where: the first of the published URLs that logged in.
url: String,
gateway_id: String,
server_uid: String,
server_name: String,
@@ -873,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);
}
}
+32 -5
View File
@@ -96,6 +96,10 @@ use voelin_stream::{
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
};
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;
@@ -108,6 +112,11 @@ pub const POKE_MESSAGE_MAX: usize = 100;
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 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,
options: Box<VoiceOptions>,
@@ -115,10 +124,14 @@ pub enum Command {
DisconnectVoice {
session: SessionId,
},
/// Invisible presence and relay chat through a `tsgw` gateway.
/// 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. 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,
url: String,
urls: Vec<String>,
identity: Box<tsclientlib::Identity>,
},
/// Invisible presence and relay chat with own ServerQuery credentials.
@@ -671,9 +684,10 @@ pub enum Event {
request: RequestId,
result: Result<(), String>,
},
/// A client's avatar is in the cache: `path`, its MD5 `hash`
/// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears
/// with an avatar and when it changes.
/// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a
/// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address
/// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]).
/// Comes when the client appears with an avatar and when it changes.
AvatarReady {
session: SessionId,
client_uid: String,
@@ -849,6 +863,7 @@ async fn run(
contacts.load().await;
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let (myts_identity, _) = watch::channel(None);
let (myts_data, _) = watch::channel(None);
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
@@ -906,6 +921,16 @@ async fn run(
});
continue;
}
Command::SetMytsData(data) => {
myts_data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
continue;
}
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
@@ -982,6 +1007,7 @@ async fn run(
settings.clone(),
engine.clone(),
myts_identity.subscribe(),
myts_data.subscribe(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -1061,6 +1087,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. }
+581 -53
View File
@@ -15,7 +15,7 @@ use std::time::Duration;
use tokio::time::Instant;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::{debug, warn};
use tracing::{debug, info, warn};
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
@@ -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::{
@@ -87,10 +87,12 @@ impl SessionHandle {
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(
Session::new(id, events, frames, audio_settings, shared, myts_identity).run(rx),
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
.run(rx),
);
Self { tx }
}
@@ -119,15 +121,26 @@ 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.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum ImageRequest {
Avatar { uid: String, hash: String },
Avatar {
uid: String,
hash: String,
},
/// A client's myTeamSpeak avatar (TeamSpeak 6), on the web.
MytsAvatar {
uid: String,
url: String,
},
Icon(u32),
Picture(String),
/// A picture a chat message shows ([`Command::FetchPicture`]), on the
/// web.
ChatPicture(String),
}
/// An image download over the voice connection, finished in the cache
@@ -146,6 +159,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));
}
}
@@ -157,11 +171,113 @@ impl Drop for ImageDownload {
}
}
/// At most three retries (after 1, 4 and 16 seconds) per image version.
/// Keeping exhausted entries prevents presence traffic from causing a retry storm.
/// 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,
/// 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, icons and chat pictures 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, 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: 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: &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 newly_gone || (failures <= 6 && error.retry != RetryHint::Permanent) =>
{
let host = web::host_of(url);
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);
info!(%host, %error, "myTeamSpeak avatar not downloaded");
}
ImageRequest::Avatar { .. } | ImageRequest::Icon(_) if retry_in.is_none() => {
info!(?request, %error, "server file not downloaded (avatar or icon)");
}
// Not the address: someone's message gave it.
ImageRequest::ChatPicture(url) => {
let host = web::host_of(url);
debug!(%host, failures, ?retry_in_s, %error, "chat picture not downloaded");
}
_ => debug!(?request, failures, ?retry_in_s, %error, "image download failed"),
}
}
/// Whether an explicitly requested image belongs to the voice connection
/// (downloaded over it, so dropped with it); a myTeamSpeak avatar is on the
/// web.
fn voice_bound(request: &ImageRequest) -> bool {
!matches!(request, ImageRequest::MytsAvatar { .. })
}
/// Our live stream, for the gateway's directory.
@@ -175,6 +291,7 @@ struct OwnStream {
struct Session {
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
@@ -187,6 +304,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>,
@@ -222,6 +342,13 @@ struct Session {
contacts_rx: Option<watch::Receiver<u64>>,
/// Avatars reported per client unique id (their hash), voice only.
avatars: HashMap<String, String>,
/// myTeamSpeak avatars wanted per client unique id (their link), any
/// presence: where the server's avatar is not shown.
myts_avatars: HashMap<String, String>,
/// Server avatars that could not be downloaded (retries used up), per
/// client unique id (their hash): the client's myTeamSpeak avatar is
/// shown instead, until it sets another.
server_avatars_failed: HashMap<String, String>,
/// Icons reported or being fetched, voice only.
icons: HashSet<u32>,
/// Pictures on the web (banners, badges) reported or being fetched, by
@@ -231,6 +358,9 @@ struct Session {
/// fetched, by address, with the size they may have
/// ([`Command::FetchPicture`]).
chat_pictures: HashMap<String, u64>,
/// Banner addresses that cannot be fetched at all (another scheme),
/// logged once.
unfetchable: HashSet<String>,
image_epoch: u64,
images_enabled: bool,
image_retries: HashMap<ImageRequest, ImageRetry>,
@@ -257,19 +387,24 @@ impl Session {
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
let contacts_rx = Some(contacts.watch());
Self {
myts_identity,
myts_data,
cache,
contacts,
contacts_rx,
avatars: HashMap::new(),
myts_avatars: HashMap::new(),
server_avatars_failed: HashMap::new(),
icons: HashSet::new(),
pictures: HashSet::new(),
chat_pictures: HashMap::new(),
unfetchable: HashSet::new(),
image_epoch: 0,
images_enabled: settings.current().get(&CACHE_FETCH_IMAGES),
image_retries: HashMap::new(),
@@ -290,6 +425,7 @@ impl Session {
gateway: None,
gateway_presence: None,
gateway_client: None,
gateway_observed: None,
query: None,
query_presence: None,
audio: None,
@@ -398,6 +534,7 @@ impl Session {
}
let link = VoiceLink {
myts_identity: self.myts_identity.clone(),
myts_data: self.myts_data.clone(),
session: self.id,
events: self.events.clone(),
settings: self.settings.clone(),
@@ -414,13 +551,32 @@ impl Session {
let _ = tx.send(VoiceCmd::Disconnect);
}
}
Command::ObserveGateway { url, identity, .. } => {
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;
}
let generation = self.next_generation();
self.known_server(format!("gateway:{url}"));
// Each is published for this server (history before its
// unique id is known).
for url in &urls {
self.known_server(format!("gateway:{url}"));
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx));
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));
self.state.observe = ObserveState::Connecting;
@@ -676,9 +832,13 @@ impl Session {
.voice_presence
.as_ref()
.and_then(|p| p.client_by_uid(&client_uid))
.and_then(|c| c.avatar.clone());
if let Some(hash) = hash {
.and_then(|c| c.avatar.clone())
.filter(|hash| self.server_avatars_failed.get(&client_uid) != Some(hash));
let myts = self.shown_client(&client_uid).and_then(|c| c.myts_avatar.clone());
if let Some(hash) = hash.filter(|_| self.voice.is_some()) {
self.fetch_avatar(&client_uid, &hash, true);
} else if let Some(url) = myts {
self.fetch_myts_avatar(&client_uid, &url, true);
}
}
Command::FetchPicture { url, max_bytes, .. } => {
@@ -687,7 +847,7 @@ impl Session {
&& !self.chat_pictures.contains_key(&url)
{
self.chat_pictures.insert(url.clone(), max_bytes);
self.fetch_picture(&url, false);
self.fetch_chat_picture(&url);
}
}
Command::ListOfflineMessages { request, .. } => {
@@ -718,6 +878,7 @@ impl Session {
}
// Engine-wide.
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
@@ -840,9 +1001,12 @@ impl Session {
self.image_epoch += 1;
self.image_retries.clear();
self.avatars.clear();
self.myts_avatars.clear();
self.server_avatars_failed.clear();
self.icons.clear();
self.pictures.clear();
self.chat_pictures.clear();
self.unfetchable.clear();
self.contact_audio.clear();
self.priority_audio = Default::default();
self.stream_friends.clear();
@@ -880,7 +1044,7 @@ impl Session {
}
fn image_waiter(&self, request: ImageRequest, requested: bool) -> Waiter {
let epoch = if requested {
let epoch = if requested && voice_bound(&request) {
self.voice.as_ref().map_or(0, |(generation, _)| *generation)
} else {
self.image_epoch
@@ -898,6 +1062,45 @@ impl Session {
self.fetch_image(key, files::avatar_path(uid).map(|path| (0, path)), false, waiter);
}
/// The myTeamSpeak avatars of the presence shown (any source) where the
/// server's avatar is not shown: none set, no voice connection to
/// download it over, or its download gave up. As the official client:
/// the server's avatar first.
fn fetch_myts_avatars(&mut self, p: &Presence) {
if !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
let mut wanted = HashMap::with_capacity(self.myts_avatars.len());
for c in p.clients.values() {
let (Some(uid), Some(url)) = (&c.uid, &c.myts_avatar) else { continue };
let server_avatar = c.avatar.is_some()
&& self.voice.is_some()
&& self.server_avatars_failed.get(uid) != c.avatar.as_ref();
if server_avatar {
continue;
}
if self.myts_avatars.get(uid) != Some(url) {
self.fetch_myts_avatar(uid, url, false);
}
wanted.insert(uid.clone(), url.clone());
}
self.myts_avatars = wanted;
}
fn fetch_myts_avatar(&self, uid: &str, url: &str, requested: bool) {
let request = ImageRequest::MytsAvatar { uid: uid.into(), url: url.into() };
let waiter = self.image_waiter(request, requested);
web::fetch_avatar(self.cache.current(), url, max_cache_bytes(&self.settings), waiter);
}
/// The client shown (any presence) with this unique id.
fn shown_client(&self, uid: &str) -> Option<&voelin_model::ClientInfo> {
[&self.voice_presence, &self.gateway_presence, &self.query_presence]
.into_iter()
.find_map(|p| p.as_ref())
.and_then(|p| p.client_by_uid(uid))
}
fn fetch_icon(&self, icon: u32) {
let waiter = self.image_waiter(ImageRequest::Icon(icon), false);
self.fetch_image(cache::icon_key(icon), Some((0, files::icon_path(icon))), false, waiter);
@@ -908,19 +1111,10 @@ impl Session {
ImageRequest::Avatar { uid, hash } => {
self.voice.is_some() && self.avatars.get(uid) == Some(hash)
}
ImageRequest::MytsAvatar { uid, url } => self.myts_avatars.get(uid) == Some(url),
ImageRequest::Icon(id) => self.voice.is_some() && self.icons.contains(id),
ImageRequest::Picture(url) => {
self.pictures.contains(url) || self.chat_pictures.contains_key(url)
}
}
}
/// How large the picture at `url` may be: a chat picture as large as
/// it was asked for, unless it is also a banner or badge.
fn picture_limit(&self, url: &str) -> u64 {
match self.chat_pictures.get(url) {
Some(max) if !self.pictures.contains(url) => (*max).min(cache::MAX_PICTURE_BYTES),
_ => cache::MAX_PICTURE_BYTES,
ImageRequest::Picture(url) => self.pictures.contains(url),
ImageRequest::ChatPicture(url) => self.chat_pictures.contains_key(url),
}
}
@@ -929,16 +1123,28 @@ impl Session {
requested: bool,
epoch: u64,
request: ImageRequest,
result: Result<PathBuf, String>,
result: Result<PathBuf, FetchError>,
) {
let wanted = if requested {
matches!(&request, ImageRequest::Avatar { uid, hash }
if self.voice.is_some() && self.voice_presence.as_ref()
.and_then(|p| p.client_by_uid(uid)).and_then(|c| c.avatar.as_ref()) == Some(hash))
match &request {
ImageRequest::Avatar { uid, hash } => {
self.voice.is_some()
&& self
.voice_presence
.as_ref()
.and_then(|p| p.client_by_uid(uid))
.and_then(|c| c.avatar.as_ref())
== Some(hash)
}
ImageRequest::MytsAvatar { uid, url } => {
self.shown_client(uid).and_then(|c| c.myts_avatar.as_ref()) == Some(url)
}
_ => false,
}
} else {
self.wants_image(&request)
};
let current = if requested {
let current = if requested && voice_bound(&request) {
self.is_current(Source::Voice, epoch)
} else {
epoch == self.image_epoch
@@ -949,13 +1155,24 @@ impl Session {
match result {
Ok(path) => {
self.image_retries.remove(&request);
// A server avatar given up on came after all (asked for
// again): it is shown again in place of the myTeamSpeak one.
if let ImageRequest::Avatar { uid, hash } = &request
&& self.server_avatars_failed.get(uid) == Some(hash)
{
self.server_avatars_failed.remove(uid);
if let Some(presence) = self.voice_presence.clone() {
self.fetch_myts_avatars(&presence);
}
}
if !requested && !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
// A chat picture already in the cache may be larger than
// asked for now.
if let ImageRequest::Picture(url) = &request
&& std::fs::metadata(&path).is_ok_and(|m| m.len() > self.picture_limit(url))
if let ImageRequest::ChatPicture(url) = &request
&& let Some(max) = self.chat_pictures.get(url)
&& std::fs::metadata(&path).is_ok_and(|m| m.len() > *max)
{
return;
}
@@ -964,23 +1181,49 @@ impl Session {
ImageRequest::Avatar { uid: client_uid, hash } => {
Event::AvatarReady { session, client_uid, hash, path }
}
// The address in place of a hash: it changes with the
// picture.
ImageRequest::MytsAvatar { uid: client_uid, url } => {
Event::AvatarReady { session, client_uid, hash: url, path }
}
ImageRequest::Icon(icon) => Event::IconReady { session, icon, path },
ImageRequest::Picture(url) => Event::PictureReady { session, url, path },
ImageRequest::Picture(url) | ImageRequest::ChatPicture(url) => {
Event::PictureReady { session, url, path }
}
});
}
Err(error) => {
debug!(?request, %error, "image download failed");
let retry = self
.image_retries
.entry(request)
.or_insert(ImageRetry { failures: 0, due: None });
retry.failures = retry.failures.saturating_add(1);
retry.due = match retry.failures {
1..=3 => {
Some(Instant::now() + Duration::from_secs(1 << (2 * (retry.failures - 1))))
let avatar_of = match &request {
ImageRequest::Avatar { uid, hash } => Some((uid.clone(), hash.clone())),
_ => 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, error.retry, retry.gone);
retry.due = delay.map(|delay| Instant::now() + delay);
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)
&& self.server_avatars_failed.get(&uid) != Some(&hash)
{
self.server_avatars_failed.insert(uid, hash);
if let Some(presence) = self.voice_presence.clone() {
self.fetch_myts_avatars(&presence);
}
}
}
}
}
@@ -991,6 +1234,8 @@ impl Session {
self.images_enabled = enabled;
self.image_epoch += 1;
self.avatars.clear();
self.myts_avatars.clear();
self.server_avatars_failed.clear();
self.icons.clear();
self.pictures.clear();
self.chat_pictures.clear();
@@ -1029,8 +1274,10 @@ impl Session {
for request in ready {
match request {
ImageRequest::Avatar { uid, hash } => self.fetch_avatar(&uid, &hash, false),
ImageRequest::MytsAvatar { uid, url } => self.fetch_myts_avatar(&uid, &url, false),
ImageRequest::Icon(icon) => self.fetch_icon(icon),
ImageRequest::Picture(url) => self.fetch_picture(&url, true),
ImageRequest::ChatPicture(url) => self.fetch_chat_picture(&url),
}
}
}
@@ -1075,17 +1322,25 @@ impl Session {
if !enabled {
return;
}
let all = std::iter::once(&p.server.banner_gfx_url)
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref()))
.filter(|u| !u.is_empty());
let mut urls = HashSet::new();
for url in all {
if self.can_fetch_picture(url) {
urls.insert(url.clone());
} else if files::server_image(url).is_none() && self.unfetchable.insert(url.clone()) {
let scheme = url.split(':').next().unwrap_or_default();
info!(%scheme, "banner not downloaded: only http, https and ts3image addresses");
}
}
// The badges shown, from TeamSpeak's server.
let badge_urls = p
.clients
.values()
.flat_map(|c| c.badges.iter().take(badges::SHOWN))
.filter_map(|guid| badges::icon_url(guid));
let urls: HashSet<String> = std::iter::once(p.server.banner_gfx_url.clone())
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.clone()))
.chain(badge_urls)
.filter(|u| self.can_fetch_picture(u))
.collect();
urls.extend(badge_urls);
self.pictures.retain(|url| urls.contains(url));
for url in &urls {
if self.pictures.insert(url.clone()) {
@@ -1094,6 +1349,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) {
@@ -1103,11 +1365,19 @@ impl Session {
let key = cache::server_picture_key(server, url);
self.fetch_image(key, Some(file), fresh, waiter);
} else {
let (max_cache, max) = (max_cache_bytes(&self.settings), self.picture_limit(url));
web::fetch(self.cache.current(), url, fresh, max_cache, max, waiter);
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
}
}
/// Get the picture a chat message shows at `url` into the cache, if it
/// is no larger than it was asked for ([`Command::FetchPicture`]).
fn fetch_chat_picture(&self, url: &str) {
let Some(&max_bytes) = self.chat_pictures.get(url) else { return };
let waiter = self.image_waiter(ImageRequest::ChatPicture(url.into()), false);
let max_cache = max_cache_bytes(&self.settings);
web::fetch_chat_picture(self.cache.current(), url, max_cache, max_bytes, waiter);
}
/// Get `key` from the cache, downloading `file` (channel and path) once
/// (again with `fresh`).
fn fetch_image(&self, key: String, file: Option<(u64, String)>, fresh: bool, waiter: Waiter) {
@@ -1531,6 +1801,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);
}
@@ -1643,6 +1914,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);
}
@@ -1661,6 +1933,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
@@ -1773,7 +2052,7 @@ impl Session {
fn gateway_event(&mut self, e: GatewayEvent) {
match e {
GatewayEvent::Connected(client) => {
GatewayEvent::Connected(client, url) => {
self.state.observe = ObserveState::Observing;
let info = client.info().clone();
self.gateway_client = Some(client.clone());
@@ -1783,6 +2062,7 @@ impl Session {
self.learn_server_uid(info.server_uid.clone(), Source::Gateway);
self.emit_state();
self.gateway_update(GatewayUpdate::Connected {
url,
gateway_id: info.gateway_id,
server_uid: info.server_uid,
server_name: info.server_name,
@@ -1809,6 +2089,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;
@@ -1981,6 +2262,7 @@ impl Session {
self.emit_state();
}
self.fetch_pictures(&presence);
self.fetch_myts_avatars(&presence);
let presence = Arc::new(presence);
self.contacts.presence(self.id, presence.clone());
self.emit(Event::Presence { session: self.id, presence });
@@ -2009,7 +2291,17 @@ mod banner_tests {
// No myTeamSpeak account; its source stays open, as the engine's does
// (a closed one ends voice connections).
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
(Session::new(1, events, frames, AudioSettings::default(), shared, myts_identity), receiver)
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let session = Session::new(
1,
events,
frames,
AudioSettings::default(),
shared,
myts_identity,
myts_data,
);
(session, receiver)
}
#[tokio::test]
@@ -2185,6 +2477,143 @@ mod banner_tests {
let _ = std::fs::remove_dir_all(cache.dir());
}
#[test]
fn banners_keep_trying_avatars_and_icons_give_up() {
let banner = ImageRequest::Picture("https://example.com/b.png".into());
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, RetryHint::Default, false).map(|d| d.as_secs()))
.collect();
assert_eq!(delays, [Some(1), Some(4), Some(16), None]);
// So does a chat picture, not shown as a banner.
let chat = ImageRequest::ChatPicture("https://example.com/b.png".into());
assert_eq!(retry_delay(&chat, 3, RetryHint::Default, false), Some(Duration::from_secs(16)));
assert_eq!(retry_delay(&chat, 4, RetryHint::Permanent, false), 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");
@@ -2200,7 +2629,8 @@ mod banner_tests {
);
let retry = &session.image_retries[&request];
assert_eq!(retry.failures, failure);
assert_eq!(retry.due.is_some(), failure <= 3);
// A banner is tried again while it is shown.
assert!(retry.due.is_some());
}
assert!(events.try_recv().is_err());
// Disabling fetch invalidates pending retries and completions.
@@ -2317,6 +2747,82 @@ mod banner_tests {
std::fs::remove_dir_all(cache.dir()).unwrap();
}
/// myTeamSpeak avatars (TeamSpeak 6) come from the web where the
/// server's avatar is not shown: none set, no voice connection to get it
/// over (observing), or its download gave up.
#[tokio::test]
async fn myts_avatars_where_the_servers_is_not_shown() {
let (mut session, mut events) = session("myts-avatar");
let cache = session.cache.current();
let client = |id, uid: &str, avatar: Option<&str>, myts: &str| voelin_model::ClientInfo {
id,
uid: Some(uid.into()),
avatar: avatar.map(Into::into),
myts_avatar: Some(myts.into()),
..Default::default()
};
let (a, b) = ("https://a.example.test/a.png", "https://a.example.test/b.png");
let hash = "0123456789abcdef0123456789abcdef";
let mut presence = Presence::default();
presence.clients.insert(1, client(1, "A=", None, a));
presence.clients.insert(2, client(2, "B=", Some(hash), b));
// Owned here, so nothing goes to the network.
let temps: Vec<_> = [a, b]
.iter()
.map(|url| {
let key = cache::picture_key(url).unwrap();
let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else {
panic!("first download");
};
(key, temp)
})
.collect();
// Observing: both, even the one with a server avatar.
session.gateway_presence = Some(presence.clone());
session.publish_presence();
assert_eq!(session.myts_avatars.len(), 2);
for (key, temp) in &temps {
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(temp, b"\x89PNG\r\n\x1a\npicture").unwrap();
cache.finish(key, temp, Ok(()), 0);
let done = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(done);
}
let mut ready = Vec::new();
while let Ok(event) = events.try_recv() {
if let Event::AvatarReady { client_uid, hash, .. } = event {
ready.push((client_uid, hash));
}
}
ready.sort();
assert_eq!(ready, [("A=".to_owned(), a.to_owned()), ("B=".to_owned(), b.to_owned())]);
// With voice the server's avatar is shown where there is one.
let (tx, _rx) = mpsc::unbounded_channel();
session.voice = Some((1, tx));
session.voice_presence = Some(presence.clone());
session.publish_presence();
assert_eq!(session.myts_avatars.keys().collect::<Vec<_>>(), ["A="]);
// Until its download gives up (the server's files unreachable).
let request = ImageRequest::Avatar { uid: "B=".into(), hash: hash.into() };
session.avatars.insert("B=".into(), hash.into());
for _ in 0..4 {
session.image_finished(
false,
session.image_epoch,
request.clone(),
Err("refused".into()),
);
}
assert_eq!(session.myts_avatars.get("B=").map(String::as_str), Some(b));
// A new server avatar is tried again: the failure was that one's.
let presence = session.voice_presence.as_mut().unwrap();
presence.clients.get_mut(&2).unwrap().avatar =
Some("fedcba9876543210fedcba9876543210".into());
session.publish_presence();
assert_eq!(session.myts_avatars.keys().collect::<Vec<_>>(), ["A="]);
std::fs::remove_dir_all(cache.dir()).unwrap();
}
#[tokio::test]
async fn enabling_images_replays_current_presence_without_server_updates() {
let (mut session, mut events) = session("policy-enable");
@@ -2463,4 +2969,26 @@ mod banner_tests {
assert_eq!(sent(), [(vec![], -30.0)]);
session.stop_all();
}
#[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());
}
}
+2 -2
View File
@@ -1121,8 +1121,8 @@ pub static CHAT_RETENTION_DAYS: Key<u32> = Key::new(
pub static CACHE_MAX_MB: Key<u64> = Key::new(
"cache.max_mb",
Kind::UInt { min: 0 },
"Size of the avatar and icon cache in MiB (0: no limit).",
|| 256,
"Size of the picture cache (avatars, icons, banners) in MiB (0: no limit).",
|| 1024,
);
/// Download the avatars, icons, banners and badges of servers we are on,
+374 -13
View File
@@ -76,6 +76,8 @@ impl VoiceOptions {
#[derive(Clone)]
pub(crate) struct VoiceLink {
pub myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
pub myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
pub session: SessionId,
pub events: broadcast::Sender<Event>,
pub settings: SharedSettings,
@@ -231,8 +233,35 @@ 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,
AccountSourceClosed,
Item(Option<Result<StreamItem, tsclientlib::Error>>),
Cmd(Option<VoiceCmd>),
@@ -242,6 +271,16 @@ enum Input {
/// A command waiting for the server's answer.
enum Pending {
MytsIdentity(Instant),
/// `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,
@@ -300,17 +339,21 @@ impl Job {
}
}
/// How long a picture of `size` bytes may take to arrive: half a minute,
/// plus its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on
/// slow links while a stalled transfer still ends.
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
fn image_download_time(size: u64) -> Duration {
Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE)
Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30);
/// Bound background image handshakes without imposing a deadline on user transfers.
fn expire_image_jobs(jobs: &mut HashMap<FiletransferHandle, Job>, now: Instant) {
jobs.retain(|_, job| {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= Duration::from_secs(15)) {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) {
job.report()(TransferState::Failed("image transfer negotiation timed out".into()));
false
} else {
@@ -350,6 +393,12 @@ struct Voice {
pending: HashMap<MessageHandle, Pending>,
jobs: HashMap<FiletransferHandle, Job>,
transfers: HashMap<TransferId, Slot>,
/// `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(
@@ -382,6 +431,7 @@ async fn run_inner(
builder = builder.default_token(token.clone());
}
let mut identity = link.myts_identity.clone();
let mut data = link.myts_data.clone();
// A changed account invalidates an in-flight handshake. Drop that connection
// and take a fresh snapshot before publishing any connected state.
let mut con = timeout(Duration::from_secs(30), async {
@@ -449,8 +499,14 @@ async fn run_inner(
pending: HashMap::new(),
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
myts_shown: tsclientlib::MytsData::default(),
};
voice.publish_state()?;
// 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(true);
let mut tick = tokio::time::interval(Duration::from_millis(250));
let result = loop {
@@ -461,7 +517,9 @@ async fn run_inner(
}) {
break Err(anyhow::anyhow!("myTeamSpeak account update timed out"));
}
let input = next_input(&mut voice.con.events(), commands, &mut tick, &mut identity).await;
let input =
next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data)
.await;
match input {
Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")),
Input::MytsIdentityChanged => {
@@ -472,6 +530,15 @@ 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. 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(true);
}
Input::MytsDataChanged => {
data.borrow_and_update();
voice.send_myts_data(false);
}
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
Input::Item(Some(Err(e))) => break Err(e.into()),
@@ -504,6 +571,7 @@ async fn next_input(
commands: &mut mpsc::UnboundedReceiver<VoiceCmd>,
tick: &mut tokio::time::Interval,
identity: &mut watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
data: &mut watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Input {
tokio::select! {
biased;
@@ -512,6 +580,11 @@ async fn next_input(
} else {
Input::AccountSourceClosed
},
changed = data.changed() => if changed.is_ok() {
Input::MytsDataChanged
} else {
Input::AccountSourceClosed
},
input = async {
// Keep account changes first without starving network or timers when
// the audio command queue remains ready.
@@ -578,6 +651,10 @@ impl Voice {
self.message(target, invoker, message);
}
}
// Connected again after a reconnect.
if self.myts_data_due {
self.send_myts_data(true);
}
self.publish_state()?;
}
StreamItem::Audio(packet) => {
@@ -660,6 +737,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();
}
_ => {}
}
@@ -825,6 +905,30 @@ impl Voice {
}
}
Pending::Quiet | Pending::MytsIdentity(_) => {}
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 {
let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}")));
@@ -833,6 +937,129 @@ impl Voice {
}
}
/// 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, again: bool) {
self.myts_data_due = false;
if self.con.get_state().is_err() {
self.myts_data_due = true;
return;
}
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"),
}
}
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 => {}
}
}
fn send(&mut self, cmd: OutCommand, pending: Pending) -> anyhow::Result<()> {
let handle = cmd.send_with_result(&mut self.con)?;
self.pending.insert(handle, pending);
@@ -1195,10 +1422,10 @@ mod image_download_tests {
},
);
}
expire_image_jobs(&mut jobs, started + Duration::from_secs(14));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1));
assert_eq!(jobs.len(), 2);
assert!(reports.lock().unwrap().is_empty());
expire_image_jobs(&mut jobs, started + Duration::from_secs(15));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION);
assert_eq!(jobs.len(), 1);
assert!(jobs.contains_key(&FiletransferHandle(2)));
assert!(
@@ -1210,10 +1437,10 @@ mod image_download_tests {
#[test]
fn large_pictures_get_time_to_arrive() {
assert_eq!(image_download_time(0), Duration::from_secs(30));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(33));
assert_eq!(image_download_time(0), Duration::from_secs(60));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048));
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384));
}
}
@@ -1224,6 +1451,7 @@ mod account_tests {
#[tokio::test(start_paused = true)]
async fn account_priority_preserves_ready_network_and_timer_progress() {
let (account, mut identity) = watch::channel(None);
let (account_data, mut data) = watch::channel(None);
let (commands, mut receiver) = mpsc::unbounded_channel();
for _ in 0..512 {
commands.send(VoiceCmd::SetInputMuted(false)).unwrap();
@@ -1234,14 +1462,22 @@ mod account_tests {
let mut tick = tokio::time::interval(Duration::from_millis(1));
account.send_replace(None);
assert!(matches!(
next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await,
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
Input::MytsIdentityChanged
));
identity.borrow_and_update();
// What is shown of the account changes too, ahead of the rest.
account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default())));
assert!(matches!(
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
Input::MytsDataChanged
));
data.borrow_and_update();
let (mut network, mut timers, mut audio) = (0, 0, 0);
for _ in 0..512 {
tokio::time::advance(Duration::from_millis(1)).await;
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await {
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await
{
Input::Item(_) => network += 1,
Input::Tick => timers += 1,
Input::Cmd(_) => audio += 1,
@@ -1251,6 +1487,130 @@ mod account_tests {
assert!(network > 0 && timers > 0 && audio > 0);
}
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;
let mut public = [0x66; 32];
public[0] = 0x58;
let identity =
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
let (events, _) = broadcast::channel(8);
let link = VoiceLink {
session: 1,
events,
settings: SharedSettings::new(crate::settings::Settings::default()),
myts_identity: watch::channel(Some(Arc::new(identity))).1,
myts_data: watch::channel(Some(Arc::new(data))).1,
};
Voice {
con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(),
link,
events: mpsc::unbounded_channel().0,
server_uid: String::new(),
talking: HashMap::new(),
pending: HashMap::new(),
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
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();
@@ -1276,6 +1636,7 @@ mod account_tests {
events,
settings: SharedSettings::new(crate::settings::Settings::default()),
myts_identity: identity,
myts_data: watch::channel(None).1,
};
let (_commands, commands) = mpsc::unbounded_channel();
let (events, mut received) = mpsc::unbounded_channel();
File diff suppressed because it is too large. Load diff