diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 6a68b0b..46b1534 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -3,13 +3,23 @@ name: CI # Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md. # Off for pushes and pull requests: run by hand only. on: + push: + branches: ["main"] + paths: + - "**" + - "!docs/**" + - "!**/*.md" + - "THIRD_PARTY_NOTICES.md" + pull_request: + paths: + - "**" + - "!docs/**" + - "!**/*.md" + - "THIRD_PARTY_NOTICES.md" workflow_dispatch: env: CARGO_TERM_COLOR: always - CARGO_BUILD_JOBS: "1" - CARGO_INCREMENTAL: "0" - RUST_BACKTRACE: "0" jobs: linux: diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index ea53e69..eea4818 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -84,7 +84,7 @@ jobs: run: | set -euo pipefail mkdir -p dist/release - for file in dist/{linux,windows,android,flatpak,gateway}/*; do + for file in dist/{linux,windows,android,gateway}/*; do [[ -f "$file" && ! -L "$file" ]] || { echo "Missing package: $file" >&2; exit 1; } name=$(basename "$file") [[ "$name" != SHA256SUMS* ]] || continue diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ed52189..f3c9749 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,6 +20,12 @@ permissions: env: CARGO_TERM_COLOR: always RUST_BACKTRACE: "0" + # GitHub's runners have 16 GB: the generated UI library does not fit + # in that next to other crates, and the runner is killed. The Gitea + # workflow keeps Cargo's default job count. The Flatpak job sets it in + # the manifest too. + CARGO_BUILD_JOBS: "1" + CARGO_INCREMENTAL: "0" jobs: package-linux: @@ -108,6 +114,13 @@ jobs: python3 -m venv /tmp/venv /tmp/venv/bin/pip install --quiet "aiohttp>=3.9.5,<4" "tomlkit>=0.13.3,<1" "PyYAML>=6.0.2,<7" /tmp/venv/bin/python /tmp/flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json + # flatpak-builder does not pass the job's environment into its sandbox, + # and the manifest keeps Cargo's default job count for Gitea: one job + # here, as for the other packages. + - name: One Cargo job + run: | + sed -i 's/^ CARGO_NET_OFFLINE: "true"$/&\n CARGO_BUILD_JOBS: "1"/' packaging/flatpak/io.github.faumaray.Voelin.yml + grep -q '^ CARGO_BUILD_JOBS: "1"$' packaging/flatpak/io.github.faumaray.Voelin.yml - uses: flatpak/flatpak-github-actions/flatpak-builder@v6 with: bundle: voelin.flatpak diff --git a/CHANGELOG.md b/CHANGELOG.md index 01b8111..26eea85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,66 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows decoders work without installing FFmpeg. - AV1 decoding through dav1d in every desktop build. - 122 more signed client versions (`Versions.csv`). +- Icon buttons show their name on hover (desktop), also while they are + disabled. +- The voice channel view on desktop can copy an invite link to the channel, + as the phone's Invite button does. +- Other people's myTeamSpeak badges: up to three pictures after their name + in the channel tree and the members panel, and their names on the member + card (what each is for on hover). On TeamSpeak 6 the badges the server + verified come first, the ones you chose in Settings → My Account + included. +- Links in chat open in the browser; one whose text is not its address + first shows where it goes. A right-click on a link opens or copies it. +- `ts3server://` and `teamspeak://` links in chat (and `tmspk.gg/s/…`) + open the server dialog filled in from the link, its channel and key + included, or move you into the link's channel when you are in voice on + that server. Nothing connects before Connect, and a saved server keeps + its nickname. `tmspk.gg` invite codes can't be opened yet. +- Every message can be quoted into the composer (`> ` lines) and its text + copied, from the actions on hover or a right-click menu, also on servers + without a gateway. +- A "New" line above the first unread message of a chat, and a bar that + counts the new messages with a jump to the first; unread counts survive + restarts. Messages count as read only while their chat is on screen in + the focused window. +- Other users' myTeamSpeak avatars (TeamSpeak 6), as the official client + shows them: where the server has no avatar of them, its avatar could not + be downloaded, or the server is only observed. +- Voice connections show servers the account's avatar, the badges chosen + in Settings → My Account (up to three) and its User Tag, as the official + client does, so other TeamSpeak 6 users see them; again after a + reconnect or an account change, and cleared on sign-out. A saved session + is enough: the avatar, its certificate, the signed badges and the User + Tag's token come from myTeamSpeak's services, and Voelin checks each + signature as the server does before sending it. The log says what the + server published. +- Settings → My Account shows the account's User Tag and lets you choose the + badges servers show. +- Pictures (banners, avatars) go through the desktop's proxy where the + desktop portal names one (Linux), and through the system proxy on + Windows and macOS; SOCKS proxies work too. +- tsgw logs what it does: a startup summary, the address the TeamSpeak + server sees for its queries (with a hint when that address is not + allowlisted), every app connection with its logins and how long they + took, refused logins, slow requests, ServerQuery failures, relays and the + observer. `log.level` (`TSGW_LOG_LEVEL`) sets what is logged, `log.file` + (`TSGW_LOG_FILE`) also writes to a file that is rotated at 20 MB (five + kept); colour only on a terminal. +- Every gateway a server publishes is tried in turn (TLS first, 20 seconds + each) before waiting to try again, so a TLS proxy that fails falls back to + the plain gateway published next to it. +- A call bar on the desktop's voice channel page: mute, deafen, share, the + voice settings and Leave, under the people and streams (Voice Settings + and Leave left the header). A smaller stage, one row of people and the + streams as rows, leaves about 200 px more for the chat; it is remembered, + and windows under 800 px tall always have it. +- A theatre mode for streams: the stream viewer's new button fills the + window with the stream and its chat, without the servers, the channels + and the members. Escape leaves it, and full screen too. +- Streams pop out into a window of their own on the desktop, optionally + kept on top of other windows, while the main window goes on; closing it + brings the stream back. ### Changed @@ -48,11 +108,119 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - A server's published gateway replaces one stored before (found or typed into an older version), so a gateway that moved is followed. - zbus's warnings about desktop portal requests are left out of the logs. +- Pop-ups, menus and tooltips have a clearer edge, and the member card, the + emoji picker and the notifications panel dim the window behind them. +- Double-clicking a channel of a server without voice connects into it + (it said "not connected with voice"). +- Older chat messages load when scrolling up, above the messages on screen, + which stay in place; the Older messages button remains for a chat that + fits on the screen. +- One dialog adds a server, with Save and Connect (Enter connects). + Connect connects only a server it saved (Join connected the server shown + before when saving failed). +- A slimmer top bar on desktop: only the search and the bell. The bell's + panel opens under the bell and is as tall as its notices; the members + button is in the voice channel's header (as in the chat's), About in + Settings. The user card has no settings gear (the rail's stays); its + avatar and name open your account. +- Home shows where you left off (the last voice channel, joined in one + click) and your unread mentions; the welcome banner shows only before the + first server. Friends show once, the quick actions are gone, and the + sidebar lists your recent private chats. +- Each server has a colour of its own (two often shared a blue), and small + server icons are drawn sharp at twice their size instead of stretched. + Small avatars, as in the channel tree, show one letter. +- Channels have one icon everywhere, the speaker, and are named without a + `#` in tabs and elsewhere. +- The members panel shows a hand on those who need talk power to speak, + instead of everyone's talk power as a bare number (the member card still + has it). +- The chat header's pinned messages and topics are icon buttons with a + count, so the channel's topic has room. +- Private chats live on the Direct Messages page, not in the server's chat + tabs, and their unread messages count there (on the phone, on the Home + tab) instead of on the server rail. +- Stream cards show the streamer: their avatar on a painted scene in their + colour, with what they share, instead of a bare screen icon (TeamSpeak + streams have no preview pictures). Your own stream from the Stream Studio + shows its picture. +- The stream viewer's controls hide while you watch, 2.5 s after the + pointer last moved over the picture (in full screen the cursor too; on a + touch screen a tap shows or hides them), and the streamer, the title and + LIVE are in the header above the picture instead of over it. +- The phone's voice screen has one header: the top bar shows the channel on + its banner, the server below it instead of the channel's topic, and Back; + Leave is only in the bottom bar. Pinned messages and topics are in the + More menu and the row of people is smaller, so the chat has about 130 px + more room. With push-to-talk, Hold to talk is the bottom bar's middle + button instead of the microphone button by the composer; Go Live and + Share are one Share button that opens the share menu (a screen, or the + Stream Studio) as on desktop. The microphone button says Mic on or Mic + off. +- The phone's Servers tab is titled Servers; the server's name and counts + are only in the server card below the server icons, no longer in the top + bar too. The voice card shows only your channel, on desktop too. +- Banners: up to 128 MiB, more time on slow hosts, BMP and ICO too, and + SVG after a comment or DOCTYPE; pictures larger than 4096 pixels on a + side are scaled down. A banner that fails is tried again for as long as + it is shown (every 15 minutes at most), and the log says why it is + missing (HTTP status, an HTML page, a video, too large). The picture + cache defaults to 1 GiB, the decoded images to 256 MB. +- Banners that fail: the log names the URL (without its query) the first + time, says when a connection stalled and after how much data, and when it + could not connect at all. A banner that is not there (HTTP 400, 404, 410) + is tried again after 15 minutes and then hourly; a host that asks to wait + (429, 503) is waited for. A banner shown again is only checked for + changes (ETag, Last-Modified), not downloaded again. At most 6 downloads + run per host, so a slow host cannot hold up the others. +- The gateway: only a refused login stops observing; anything else is tried + again after 1, 2, 5, 10, 20, then every 30 seconds, and at once when voice + connects. A connection that stops answering is noticed within 90 seconds. + Finding a server's gateway asks DNS and the gateway at once instead of one + after the other. The log says what was found, which gateway was tried, + how long each step took and why one failed. +- tsgw answers faster: each ServerQuery command takes under 2 ms instead of + about 45 ms (TCP_QUICKACK), so logins and startup take milliseconds. + TeamSpeak's flood protection is shared by all of tsgw's query + connections, so tsgw no longer earns a 600 second ban. It starts while + the TeamSpeak server is still down and connects once it is up, its + `/health` says what is missing, and it stops cleanly on SIGTERM. ### Fixed - The account's avatar is downloaded from its own link; it was asked for as an upload link and refused with HTTP 403. +- Hover help in the Stream Studio (a source's error, the status details) + shows each time and closes when the pointer leaves; it showed only once, + and stayed open until a click. +- Spacer channels: `[spacer]`, `[lspacer]`, `[rspacer]` and `[*spacer]` lines + are drawn as TeamSpeak draws them, like `[cspacer]` was, and chats, search + results, notifications and the other screens show a spacer's text instead + of its raw name. +- Locked channels ask for their password (kept until voice disconnects, and + asked again when it is wrong), and joining a full channel or one the + server refuses says why; joining did nothing before. +- Pokes can carry a message (up to 100 characters); they were always sent + empty. +- While a priority speaker talks, everyone else (watched streams too) is + dimmed by the server's setting, as in TeamSpeak; nobody was dimmed before. +- BBCode from other clients shows as formatting (bold, colours, links, + quotes, lists, code, pictures) instead of raw tags, and the server's + welcome message opens the server chat. Messages with emoji keep their + line breaks. +- Joining a friend in a subchannel of a server without voice connects into + that subchannel; it connected into the default channel. +- Closing a chat tab left of the selected one keeps the selected chat; the + one after it was selected. +- Connecting with voice from a private chat (Direct Messages) keeps that + conversation open; it turned into the voice channel's chat, and the + composer sent there. +- Observing no longer stops for the whole run the first time a server is + joined with a new identity (the gateway did not know it yet). +- tsgw reconnects its query connection for logins when the TeamSpeak server + restarts; before, every login was refused until tsgw was restarted. +- Push-to-talk controls (Hold to talk) showed in voice activation and + continuous mode until the settings had been opened once. ## [0.0.1-alpha] - 2026-10-04 diff --git a/Cargo.lock b/Cargo.lock index 47951aa..9158e7c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3534,9 +3534,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -7869,6 +7871,7 @@ dependencies = [ "i-slint-backend-android-activity", "i-slint-backend-linuxkms", "i-slint-backend-selector", + "i-slint-backend-winit", "i-slint-common", "i-slint-core", "i-slint-core-macros", @@ -9692,9 +9695,13 @@ version = "0.1.0" dependencies = [ "anyhow", "base64 0.22.1", + "bytes", "dirs", "futures", + "h2", "hickory-resolver", + "http", + "httpdate", "md5", "reqwest", "rusqlite", @@ -9826,9 +9833,11 @@ dependencies = [ "aes-gcm", "base64 0.22.1", "ctr 0.10.1", + "curve25519-dalek 4.1.3", "pbkdf2", "reqwest", "schema-api", + "sha2 0.10.9", "subtle", "thiserror 2.0.21", "tokio", @@ -9862,6 +9871,7 @@ dependencies = [ "tracing", "windows 0.62.2", "x11rb", + "zbus", ] [[package]] @@ -9872,6 +9882,7 @@ dependencies = [ "russh", "serde", "serde_json", + "socket2", "thiserror 2.0.21", "tokio", "tracing", diff --git a/crates/proto/UPSTREAM.md b/crates/proto/UPSTREAM.md index 481464f..fbeaf37 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -129,3 +129,21 @@ against or offered back to upstream. Tests cover an independent signature vector, persistence validation/redaction, wire field names, clearing and reconnect snapshot replacement. The account UUID and the ordinary server identity remain separate. +15. **myTeamSpeak presentation, TeamSpeak 6** (`tsproto/src/license.rs`, + `tsproto/src/myts.rs`, `tsclientlib/src/myts.rs`, `tsclientlib/src/lib.rs`, + `tsproto-packets/src/packets.rs`, `tsproto-structs/declarations/Book.toml`). + License block types 4–7 (Token, License_Sign, MyTsId_Sign, Updater), which + carry nothing after the header. `myts::Certificate` checks a myTeamSpeak + certificate chain as a TeamSpeak 6 server does: leaf type, validity window, + key derived from a given root, cofactorless Ed25519 with a reduced S; + `Identity::id_bytes` and `public_signature_certificate`. `MytsData` holds the + avatar and the badges, each with the certificate that verifies it, and the + User Tag; `MytsData::updates` builds `updatemytsdata` (split by certificate, + bare parameters to clear) and `clientupdate client_user_tag`, which + `Connection::send_myts_update` and `send_user_tag` send. The escaped writer + also escapes `\a` and `\b`, as TeamSpeak does for binary values. Book: + `Client::my_team_speak_avatar`, `my_team_speak_id` and `signed_badges`. +16. **Privilege key when connecting** (`tsclientlib/src/lib.rs`, "Voelin patch"). + `ConnectOptions::default_token` sets `client_default_token` of `clientinit`, + which upstream always sent empty, so a privilege key (a bookmark's, or the + `token=` of a `ts3server://` link) can be used on connect. diff --git a/crates/proto/tsclientlib/src/lib.rs b/crates/proto/tsclientlib/src/lib.rs index 41d7fe4..75695c7 100644 --- a/crates/proto/tsclientlib/src/lib.rs +++ b/crates/proto/tsclientlib/src/lib.rs @@ -61,6 +61,7 @@ pub use ts_bookkeeping::messages::s2c::InMessage; pub use ts_bookkeeping::*; pub use tsproto::resend::{ConnectionStats, PacketStat}; pub use tsproto::Identity; +pub use myts::{MytsData, MytsUpdate, Signed, UserTag}; pub use tsproto_types::errors::Error as TsError; /// Wait this time for initserver, in seconds. @@ -392,6 +393,7 @@ impl Connection { channel: None, channel_password: None, password: None, + default_token: None, input_muted: false, output_muted: false, input_hardware_enabled: true, @@ -556,7 +558,7 @@ impl Connection { version_sign: Cow::Borrowed(client_version_sign.as_ref()), client_key_offset: counter, phonetic_name: "".into(), - default_token: "".into(), + default_token: Cow::Borrowed(options.default_token.as_deref().unwrap_or_default()), hardware_id: Cow::Borrowed(options.hardware_id.as_ref()), badges: None, signed_badges: None, @@ -1730,6 +1732,7 @@ pub struct ConnectOptions { channel: Option>, channel_password: Option>, password: Option>, + default_token: Option>, input_muted: bool, output_muted: bool, input_hardware_enabled: bool, @@ -1944,6 +1947,20 @@ impl ConnectOptions { self } + /// Use a privilege key (token) when connecting. + /// Voelin patch: sent as `client_default_token` in `clientinit`. + /// + /// # Example + /// ``` + /// # use tsclientlib::Connection; + /// let opts = Connection::build("localhost").default_token("My privilege key"); + /// ``` + #[inline] + pub fn default_token>>(mut self, token: S) -> Self { + self.default_token = Some(token.into()); + self + } + /// Connect to the server in a muted state. /// /// # Example @@ -2064,6 +2081,10 @@ impl ConnectOptions { #[inline] pub fn get_password(&self) -> Option<&str> { self.password.as_ref().map(AsRef::as_ref) } #[inline] + pub fn get_default_token(&self) -> Option<&str> { + self.default_token.as_ref().map(AsRef::as_ref) + } + #[inline] pub fn get_input_muted(&self) -> bool { self.input_muted } #[inline] pub fn get_output_muted(&self) -> bool { self.output_muted } diff --git a/crates/proto/tsclientlib/src/myts.rs b/crates/proto/tsclientlib/src/myts.rs index 91bd276..1bda40c 100644 --- a/crates/proto/tsclientlib/src/myts.rs +++ b/crates/proto/tsclientlib/src/myts.rs @@ -1,5 +1,6 @@ //! Voelin patch: connection-bound myTeamSpeak proof and live account changes. +use base64::prelude::*; use tsproto::myts::Identity; use tsproto_packets::packets::{Direction, Flags, OutCommand, PacketType}; @@ -14,7 +15,184 @@ impl ConnectOptions { } } +/// What a voice server is shown of the myTeamSpeak account (TeamSpeak 6) +/// besides its myTS ID, as myTeamSpeak signed it for that ID: its avatar, +/// its badges and its User Tag. The server checks the avatar and the badges +/// with the one certificate of each `updatemytsdata` and shows nothing of +/// what does not verify, so each comes with the certificate that verifies +/// it. Viewers check the User Tag's token themselves. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct MytsData { + /// The raw myTS ID all of it is signed for: shown only on a connection + /// that presents it. + pub myts_id: Vec, + /// An `AvatarData` as it came (`client_myteamspeak_avatar`). + pub avatar: Signed, + /// A `UserBadgesSignedList`, the badges chosen to show, in order + /// (`client_signed_badges`). + pub badges: Signed, + /// The ids of those badges, as in the list: the server publishes the + /// ones that verify. + pub badge_ids: Vec, + pub user_tag: Option, +} + +/// Something signed and the certificate that verifies it; empty: nothing. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct Signed { + pub certificate: Vec, + pub data: Vec, +} + +/// The User Tag (`client_user_tag`): the account's primary chat identifier +/// and the token that proves it (a `MatrixIdentifierToken` as it came). +#[derive(Clone, Default, PartialEq, Eq)] +pub struct UserTag { + pub tag: String, + pub token: Vec, +} + +impl std::fmt::Debug for MytsData { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MytsData") + .field("avatar", &self.avatar.data.len()) + .field("badges", &self.badge_ids) + .field("user_tag", &self.user_tag.as_ref().map(|t| &t.tag)) + .finish() + } +} + +impl Signed { + pub fn is_empty(&self) -> bool { self.data.is_empty() } +} + +impl UserTag { + /// `client_user_tag` as the official client sets it: compact JSON with + /// the token (standard base64), the tag and when it was set (`updated`, + /// milliseconds since 1970), in this order. + pub fn value(&self, updated_ms: i64) -> String { + let mut tag = String::with_capacity(self.tag.len()); + for c in self.tag.chars() { + match c { + '"' => tag.push_str("\\\""), + '\\' => tag.push_str("\\\\"), + '\n' => tag.push_str("\\n"), + '\r' => tag.push_str("\\r"), + '\t' => tag.push_str("\\t"), + '\u{8}' => tag.push_str("\\b"), + '\u{c}' => tag.push_str("\\f"), + c if u32::from(c) < 0x20 => tag.push_str(&format!("\\u{:04x}", u32::from(c))), + c => tag.push(c), + } + } + format!( + "{{\"myts_token\":\"{}\",\"tag\":\"{}\",\"updated\":{}}}", + BASE64_STANDARD.encode(&self.token), + tag, + updated_ms + ) + } +} + +/// One `updatemytsdata`: a value is shown (checked with `certificate`), an +/// empty one clears what is shown, `None` leaves it as it is. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct MytsUpdate { + pub certificate: Vec, + pub badges: Option>, + pub avatar: Option>, +} + +/// What to do about one part of what is shown. +enum Part<'a> { + Keep, + Show(&'a Signed), + Clear, +} + +fn part<'a>(wanted: &'a Signed, shown: &Signed, again: bool) -> Part<'a> { + if wanted.is_empty() { + if shown.is_empty() { Part::Keep } else { Part::Clear } + } else if again || wanted != shown { + Part::Show(wanted) + } else { + Part::Keep + } +} + +impl MytsData { + /// The `updatemytsdata` commands that make a server that shows `shown` + /// show `self`. `again`: everything once more, after a new account proof + /// (`updatemytsid`), which the server does not check them for again. + /// The avatar and the badges go together when one certificate verifies + /// both (certificate, badges, avatar, as the official client sends + /// them), apart otherwise; clearing needs no certificate. + pub fn updates(&self, shown: &MytsData, again: bool) -> Vec { + let avatar = part(&self.avatar, &shown.avatar, again); + let badges = part(&self.badges, &shown.badges, again); + let mut updates = Vec::new(); + match (&badges, &avatar) { + (Part::Show(badges), Part::Show(avatar)) if badges.certificate == avatar.certificate => { + updates.push(MytsUpdate { + certificate: avatar.certificate.clone(), + badges: Some(badges.data.clone()), + avatar: Some(avatar.data.clone()), + }); + } + _ => { + if let Part::Show(avatar) = avatar { + updates.push(MytsUpdate { + certificate: avatar.certificate.clone(), + avatar: Some(avatar.data.clone()), + ..Default::default() + }); + } + if let Part::Show(badges) = badges { + updates.push(MytsUpdate { + certificate: badges.certificate.clone(), + badges: Some(badges.data.clone()), + ..Default::default() + }); + } + } + } + let clear_badges = matches!(badges, Part::Clear); + let clear_avatar = matches!(avatar, Part::Clear); + if clear_badges || clear_avatar { + updates.push(MytsUpdate { + certificate: Vec::new(), + badges: if clear_badges { Some(Vec::new()) } else { None }, + avatar: if clear_avatar { Some(Vec::new()) } else { None }, + }); + } + updates + } +} + impl Connection { + /// Show the server the account's avatar or badges, or clear them + /// (`updatemytsdata`), as the official client does once connected and + /// after a sign-in, after the account proof (`updatemytsid`). The server + /// answers before the result: the own client's + /// `client_myteamspeak_avatar` and `client_signed_badges`, empty for what + /// did not verify. Await the returned handle's + /// `StreamItem::MessageResult` for the answer. + pub fn send_myts_update(&mut self, update: &MytsUpdate) -> Result { + if !matches!(self.state, ConnectionState::Connected { .. }) { + return Err(Error::NotConnected); + } + self.send_command_with_result(data_packet(update)) + } + + /// Set the User Tag (`clientupdate client_user_tag`), as built by + /// [`UserTag::value`]; empty clears it. TeamSpeak 6 servers only. + pub fn send_user_tag(&mut self, value: &str) -> Result { + if !matches!(self.state, ConnectionState::Connected { .. }) { + return Err(Error::NotConnected); + } + self.send_command_with_result(user_tag_packet(value)) + } + /// Publish a connection-bound account proof, or clear the account identity. /// /// Always updates the reconnect options, even if currently disconnected or @@ -34,6 +212,29 @@ impl Connection { } } +/// The values are the raw bytes with TeamSpeak's escaping only (no +/// base64), as the official client sends them; an empty one is the bare +/// name, which clears. +fn data_packet(update: &MytsUpdate) -> OutCommand { + let mut packet = + OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsdata"); + packet.write_bin_arg("myts_certificate", &update.certificate); + if let Some(badges) = &update.badges { + packet.write_bin_arg("myts_signed_badge", badges); + } + if let Some(avatar) = &update.avatar { + packet.write_bin_arg("myts_avatar", avatar); + } + packet +} + +fn user_tag_packet(value: &str) -> OutCommand { + let mut packet = + OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "clientupdate"); + packet.write_arg("client_user_tag", &value); + packet +} + fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand { let mut packet = OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "updatemytsid"); @@ -50,6 +251,99 @@ fn update_packet(identity: Option<&Identity>, iv: &[u8; 64]) -> OutCommand { mod tests { use super::*; + fn signed(certificate: &[u8], data: &[u8]) -> Signed { + Signed { certificate: certificate.to_vec(), data: data.to_vec() } + } + + fn wire(update: &MytsUpdate) -> Vec { data_packet(update).into_packet().content().to_vec() } + + #[test] + fn account_data_goes_raw_and_escaped() { + let update = MytsUpdate { + certificate: b"a b/c|d\\\x07\x08\x00\xff".to_vec(), + badges: Some(vec![0x0a, 0x01, b' ']), + avatar: Some(vec![0x0a, 0x02, b'h', b'i']), + }; + assert_eq!( + wire(&update), + b"updatemytsdata myts_certificate=a\\sb\\/c\\pd\\\\\\a\\b\x00\xff \ + myts_signed_badge=\\n\x01\\s myts_avatar=\\n\x02hi" + ); + // Without badges: the certificate and the avatar. + let update = MytsUpdate { badges: None, ..update }; + assert!(!wire(&update).windows(17).any(|w| w == b"myts_signed_badge")); + // Clearing: bare names, no certificate needed. + let clear = MytsUpdate { + certificate: Vec::new(), + badges: Some(Vec::new()), + avatar: Some(Vec::new()), + }; + assert_eq!(wire(&clear), b"updatemytsdata myts_certificate myts_signed_badge myts_avatar"); + } + + #[test] + fn what_one_certificate_verifies_goes_together() { + let data = MytsData { + myts_id: vec![1; 33], + avatar: signed(b"C", b"avatar"), + badges: signed(b"C", b"badges"), + badge_ids: vec!["b1".into()], + user_tag: None, + }; + let none = MytsData::default(); + assert_eq!(data.updates(&none, false), [MytsUpdate { + certificate: b"C".to_vec(), + badges: Some(b"badges".to_vec()), + avatar: Some(b"avatar".to_vec()), + }]); + assert_eq!( + wire(&data.updates(&none, false)[0]), + b"updatemytsdata myts_certificate=C myts_signed_badge=badges myts_avatar=avatar" + ); + // Unchanged: nothing, unless after a new account proof. + assert!(data.updates(&data, false).is_empty()); + assert_eq!(data.updates(&data, true).len(), 1); + // Two certificates: two commands, each with its own. + let apart = MytsData { badges: signed(b"D", b"badges"), ..data.clone() }; + let updates: Vec<_> = apart.updates(&none, false).iter().map(wire).collect(); + assert_eq!(updates, [ + b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(), + b"updatemytsdata myts_certificate=D myts_signed_badge=badges".to_vec(), + ]); + // Only what changed. + let newer = MytsData { avatar: signed(b"C", b"newer"), ..data.clone() }; + let updates: Vec<_> = newer.updates(&data, false).iter().map(wire).collect(); + assert_eq!(updates, [b"updatemytsdata myts_certificate=C myts_avatar=newer".to_vec()]); + // What is no longer there is cleared; what never was is left alone. + let fewer = MytsData { badges: Signed::default(), ..data.clone() }; + let updates: Vec<_> = fewer.updates(&data, true).iter().map(wire).collect(); + assert_eq!(updates, [ + b"updatemytsdata myts_certificate=C myts_avatar=avatar".to_vec(), + b"updatemytsdata myts_certificate myts_signed_badge".to_vec(), + ]); + let updates: Vec<_> = none.updates(&data, true).iter().map(wire).collect(); + assert_eq!(updates, [b"updatemytsdata myts_certificate myts_signed_badge myts_avatar".to_vec()]); + assert!(none.updates(&none, true).is_empty()); + } + + #[test] + fn the_user_tag_is_set_as_the_official_client_sets_it() { + let tag = UserTag { tag: "alex@myteamspeak.com".into(), token: vec![0xfb, 0xff, 0x01, 0x02] }; + assert_eq!( + tag.value(1_759_740_000_123), + r#"{"myts_token":"+/8BAg==","tag":"alex@myteamspeak.com","updated":1759740000123}"# + ); + let odd = UserTag { tag: "a\"b\\c\n\u{1}é".into(), token: Vec::new() }; + assert_eq!(odd.value(1), r#"{"myts_token":"","tag":"a\"b\\c\n\u0001é","updated":1}"#); + // TeamSpeak's escaping on the wire; empty clears. + let packet = user_tag_packet(&tag.value(5)).into_packet(); + assert_eq!( + packet.content(), + &br#"clientupdate client_user_tag={"myts_token":"+\/8BAg==","tag":"alex@myteamspeak.com","updated":5}"#[..] + ); + assert_eq!(user_tag_packet("").into_packet().content(), b"clientupdate client_user_tag"); + } + #[test] fn clear_contains_no_previous_account_proof() { let packet = update_packet(None, &[0; 64]).into_packet(); diff --git a/crates/proto/tsproto-packets/src/packets.rs b/crates/proto/tsproto-packets/src/packets.rs index bc4c7a8..5e085c2 100644 --- a/crates/proto/tsproto-packets/src/packets.rs +++ b/crates/proto/tsproto-packets/src/packets.rs @@ -968,6 +968,10 @@ impl io::Write for EscapedWriter<'_> { self.0.reserve(buf.len()); for c in buf { match c { + // Voelin patch: \a and \b as TeamSpeak escapes them (binary + // values, e.g. `updatemytsdata`). + b'\x07' => self.0.extend_from_slice(b"\\a"), + b'\x08' => self.0.extend_from_slice(b"\\b"), b'\x0b' => self.0.extend_from_slice(b"\\v"), b'\x0c' => self.0.extend_from_slice(b"\\f"), b'\\' => self.0.extend_from_slice(b"\\\\"), diff --git a/crates/proto/tsproto-structs/declarations/Book.toml b/crates/proto/tsproto-structs/declarations/Book.toml index e84e844..24c55a0 100644 --- a/crates/proto/tsproto-structs/declarations/Book.toml +++ b/crates/proto/tsproto-structs/declarations/Book.toml @@ -192,6 +192,9 @@ properties = [ { name="InheritedChannelGroupFromChannel", type="ChannelId" }, { name="Badges", type="str" }, { name="UserTag", type="str", opt=true }, + { name="MyTeamSpeakAvatar", type="str", opt=true, doc="`,;…` of the myTeamSpeak avatar (TeamSpeak 6)" }, + { name="MyTeamSpeakId", type="str", opt=true, doc="The myTeamSpeak ID the server accepted (base64), empty without one" }, + { name="SignedBadges", type="str", opt=true, doc="Comma-separated ids of the myTeamSpeak badges the server verified (TeamSpeak 6)" }, { name="PermissionHints", type="ClientPermissionHint", opt=true }, { name="OptionalData", type="OptionalClientData", opt=true }, { name="ConnectionData", type="ConnectionClientData", opt=true }, diff --git a/crates/proto/tsproto/src/license.rs b/crates/proto/tsproto/src/license.rs index b0084a9..609f143 100644 --- a/crates/proto/tsproto/src/license.rs +++ b/crates/proto/tsproto/src/license.rs @@ -102,8 +102,17 @@ pub enum LicenseBlockType { /// Ts3_Server Server, Code, - // Not existing in the license parameter: - // 4: Token, 5: License_Sign, 6: MyTsId_Sign, 7: Updater + // Not existing in the license parameter. Like `Ephemeral`, these blocks + // carry nothing after the header. + /// 4, Token + Token, + /// 5, License_Sign + LicenseSign, + /// 6, MyTsId_Sign: the key that signs myTeamSpeak data (avatars, badges, + /// identifier tokens). + MytsIdSign, + /// 7, Updater + Updater, /// Ts_Server_License Ts5Server = 8, /// 32, Ephemeral_Key @@ -413,8 +422,12 @@ impl License { (InnerLicense::Ts5Server { properties }, pos) } - LicenseBlockType::Ephemeral => (InnerLicense::Other, 0), - _ => { + LicenseBlockType::Token + | LicenseBlockType::LicenseSign + | LicenseBlockType::MytsIdSign + | LicenseBlockType::Updater + | LicenseBlockType::Ephemeral => (InnerLicense::Other, 0), + LicenseBlockType::Website | LicenseBlockType::Code => { return Err(Error::UnknownBlockType(typ_i)); } }; @@ -710,7 +723,11 @@ impl fmt::Debug for DebugLicense<'_> { d.field("properties", &"error"); } } - LicenseBlockType::Ephemeral => {} + LicenseBlockType::Token + | LicenseBlockType::LicenseSign + | LicenseBlockType::MytsIdSign + | LicenseBlockType::Updater + | LicenseBlockType::Ephemeral => {} } d.finish()?; @@ -727,7 +744,11 @@ impl LicenseBlockType { Self::Website | Self::Code => 1, Self::Server => 6, Self::Ts5Server => 2, - Self::Ephemeral => 0, + Self::Token + | Self::LicenseSign + | Self::MytsIdSign + | Self::Updater + | Self::Ephemeral => 0, } } } @@ -923,6 +944,27 @@ mod tests { YrUET9sEbz1CATKgK8EyqrfA==").unwrap()).unwrap(); } + #[test] + fn parse_blocks_without_payload() { + // Token, License_Sign, MyTsId_Sign and Updater blocks end with their + // header, as Ephemeral blocks do. + for typ in [4, 5, 6, 7] { + let mut data = vec![1, 0]; + data.extend_from_slice(&[0x58; 32]); + data.push(typ); + data.extend_from_slice(&[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff]); + let licenses = Licenses::parse_ignore_expired(data.clone()).unwrap(); + assert_eq!(licenses.blocks.len(), 1); + assert_eq!(licenses.blocks[0].len, BLOCK_MIN_LEN); + let block = licenses.blocks[0].get_type(&data[1..]).unwrap(); + assert_eq!(block.to_u8(), Some(typ)); + // Anything after the header is the next block. + data.push(0); + assert!(Licenses::parse_ignore_expired(data).is_err()); + } + assert_eq!(LicenseBlockType::from_u8(6), Some(LicenseBlockType::MytsIdSign)); + } + #[test] fn derive_public_key() { let licenses = Licenses::parse_ignore_expired(BASE64_STANDARD.decode("AQA1hUFJiiSs0wFXkYuPUJVcDa6XCrZTcsvkB0Ffzz4CmwIITRXgCqeTYAcAAAAgQW5vbnltb3VzAAC4R+5mos+UQ/KCbkpQLMI5WRp4wkQu8e5PZY4zU+/FlyAJwaE8CcJJ/A==").unwrap()).unwrap(); diff --git a/crates/proto/tsproto/src/myts.rs b/crates/proto/tsproto/src/myts.rs index 06cf39a..2468e03 100644 --- a/crates/proto/tsproto/src/myts.rs +++ b/crates/proto/tsproto/src/myts.rs @@ -6,13 +6,17 @@ use std::fmt; use base64::prelude::*; +use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint}; use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar}; use serde::{Deserialize, Deserializer, Serialize}; use sha2::{Digest, Sha256, Sha512}; use thiserror::Error; use tsproto_packets::packets::OutCommand; +use tsproto_types::crypto::EccKeyPubEd25519; use zeroize::Zeroize; +use crate::license::{self, LicenseBlockType, Licenses}; + /// An account identity; distinct from the account UUID and server identity. #[derive(Clone, Serialize)] pub struct Identity { @@ -94,6 +98,13 @@ impl Identity { pub fn id(&self) -> String { BASE64_STANDARD.encode(&self.myts_id) } + /// The myTS ID's 33 bytes: what myTeamSpeak signs the account's avatar, + /// badges and identifier token for. + pub fn id_bytes(&self) -> &[u8] { &self.myts_id } + + /// The certificate of the myTS ID's signature (`pubSignCert`): public. + pub fn public_signature_certificate(&self) -> &[u8] { &self.public_signature[64..] } + /// Sign this connection's challenge with the original raw private scalar. /// This is not Ed25519's seed expansion: the account already stores a scalar. pub fn proof(&self, shared_iv: &[u8; 64]) -> Proof { @@ -131,6 +142,91 @@ impl Identity { } } +/// A myTeamSpeak certificate: a TeamSpeak license chain whose last block's +/// key signs what myTeamSpeak hands out for an account (its avatar, badges +/// and identifier token). Checked as a TeamSpeak 6 server and the official +/// client check it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Certificate { + block_type: Option, + /// Unix seconds. + not_valid_before: i64, + not_valid_after: i64, + /// The leaf's key, derived along the chain from the root. + key: [u8; 32], +} + +#[derive(Debug, Error)] +pub enum CertificateError { + #[error("myTeamSpeak certificate must start with version 1")] + Version, + #[error("myTeamSpeak certificate holds no key")] + Empty, + #[error("myTeamSpeak certificate does not parse: {0}")] + License(#[from] license::Error), +} + +impl Certificate { + /// Parse a certificate whose chain starts at `root` (the TeamSpeak root + /// key, [`crate::ROOT_KEY`]). Nested validity windows are checked here, + /// the leaf's against a time by [`Self::valid_at`]. + pub fn parse(data: &[u8], root: &[u8; 32]) -> Result { + if data.first() != Some(&1) { + return Err(CertificateError::Version); + } + let licenses = Licenses::parse_ignore_expired(data.to_vec())?; + let leaf = licenses.blocks.last().ok_or(CertificateError::Empty)?; + let leaf_data = &data[data.len() - leaf.len..]; + let key = licenses.derive_public_key(EccKeyPubEd25519::from_bytes(*root))?; + Ok(Self { + block_type: leaf.get_type(leaf_data).ok(), + not_valid_before: leaf.get_not_valid_before(leaf_data)?.unix_timestamp(), + not_valid_after: leaf.get_not_valid_after(leaf_data)?.unix_timestamp(), + key: key.compress().to_bytes(), + }) + } + + /// Whether the leaf is a key that signs for myTS IDs (`MYTSID_SIGN`): + /// a TeamSpeak 6 server takes no other for an avatar or badges. + pub fn signs_myts_data(&self) -> bool { self.block_type == Some(LicenseBlockType::MytsIdSign) } + + /// Whether the leaf is valid at `unix` seconds. + pub fn valid_at(&self, unix: i64) -> bool { + self.not_valid_before <= unix && unix < self.not_valid_after + } + + /// Until when the leaf is valid, Unix seconds. + pub fn not_valid_after(&self) -> i64 { self.not_valid_after } + + /// Whether the leaf's key signed `message` (Ed25519, as TeamSpeak checks + /// it: SHA-512 over R, the key and the message, without the cofactor; + /// a signature whose S is not reduced is refused). + pub fn verifies(&self, message: &[u8], signature: &[u8]) -> bool { + verify_ed25519(&self.key, message, signature) + } +} + +fn verify_ed25519(key: &[u8; 32], message: &[u8], signature: &[u8]) -> bool { + if signature.len() != 64 { + return false; + } + let Some(public) = CompressedEdwardsY(*key).decompress() else { + return false; + }; + let mut s = [0; 32]; + s.copy_from_slice(&signature[32..]); + let Some(s) = Option::::from(Scalar::from_canonical_bytes(s)) else { + return false; + }; + let mut hash = Sha512::new(); + hash.update(&signature[..32]); + hash.update(key); + hash.update(message); + let k = Scalar::from_bytes_mod_order_wide(&hash.finalize().into()); + let r = EdwardsPoint::vartime_double_scalar_mul_basepoint(&k, &-public, &s); + r.compress().as_bytes() == &signature[..32] +} + /// Public, connection-bound authentication values. Never contains private keys. #[derive(Clone)] pub struct Proof { @@ -244,4 +340,136 @@ mod tests { ]); assert!(!wire.contains("private")); } + + /// A chain from a synthetic root (secret `root`): an intermediate block + /// when `outer` is set, then a leaf of `kind` with the key `leaf`·B, valid + /// from `from` to `to` (Unix seconds). Also the leaf's derived secret. + fn chain( + root: Scalar, outer: Option<(i64, i64)>, leaf: Scalar, kind: u8, from: i64, to: i64, + ) -> (Vec, Scalar) { + fn block(key: &Scalar, kind: u8, from: i64, to: i64, extra: &[u8]) -> (Vec, Scalar) { + let mut block = vec![0]; + block.extend_from_slice((ED25519_BASEPOINT_TABLE * key).compress().as_bytes()); + block.push(kind); + for time in [from, to] { + block.extend_from_slice(&((time - license::TIMESTAMP_OFFSET) as u32).to_be_bytes()); + } + block.extend_from_slice(extra); + let mut hash: [u8; 64] = Sha512::digest(&block[1..]).into(); + hash[0] &= 248; + hash[31] &= 63; + hash[31] |= 64; + let mut low = [0; 32]; + low.copy_from_slice(&hash[..32]); + (block, Scalar::from_bytes_mod_order(low)) + } + let mut data = vec![1]; + let mut secret = root; + if let Some((from, to)) = outer { + let key = Scalar::from_bytes_mod_order([3; 32]); + let (outer, hash) = block(&key, 0, from, to, b"\0\0\0\0Synthetic\0"); + data.extend_from_slice(&outer); + secret += key * hash; + } + let (leaf_block, hash) = block(&leaf, kind, from, to, &[]); + data.extend_from_slice(&leaf_block); + (data, secret + leaf * hash) + } + + fn sign(secret: &Scalar, message: &[u8]) -> Vec { + let public = (ED25519_BASEPOINT_TABLE * secret).compress().to_bytes(); + let nonce = Scalar::from_bytes_mod_order_wide( + &Sha512::new().chain_update(secret.as_bytes()).chain_update(message).finalize().into(), + ); + let r = (ED25519_BASEPOINT_TABLE * &nonce).compress().to_bytes(); + let k = Scalar::from_bytes_mod_order_wide( + &Sha512::new().chain_update(r).chain_update(public).chain_update(message).finalize().into(), + ); + let mut signature = r.to_vec(); + signature.extend_from_slice((k * secret + nonce).as_bytes()); + signature + } + + const NOW: i64 = 1_790_000_000; + + #[test] + fn certificate_key_signs_along_the_chain() { + let root = Scalar::from_bytes_mod_order([5; 32]); + let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes(); + let leaf = Scalar::from_bytes_mod_order([7; 32]); + for outer in [None, Some((NOW - 1000, NOW + 1000))] { + let (data, secret) = chain(root, outer, leaf, 6, NOW - 10, NOW + 10); + let certificate = Certificate::parse(&data, &root_key).unwrap(); + assert!(certificate.signs_myts_data()); + assert!(certificate.valid_at(NOW - 10) && certificate.valid_at(NOW + 9)); + assert!(!certificate.valid_at(NOW - 11) && !certificate.valid_at(NOW + 10)); + assert_eq!(certificate.not_valid_after(), NOW + 10); + let signature = sign(&secret, b"message"); + assert!(certificate.verifies(b"message", &signature)); + assert!(!certificate.verifies(b"messagE", &signature)); + assert!(!certificate.verifies(b"message", &signature[..63])); + let mut flipped = signature.clone(); + flipped[5] ^= 1; + assert!(!certificate.verifies(b"message", &flipped)); + // The same S plus the group order: refused, though it is the same + // point (S must be reduced). + let mut s = [0u8; 32]; + s.copy_from_slice(&signature[32..]); + let order: [u8; 32] = [ + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, + 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10, + ]; + let mut carry = 0u16; + for (s, l) in s.iter_mut().zip(order) { + let sum = u16::from(*s) + u16::from(l) + carry; + *s = sum as u8; + carry = sum >> 8; + } + let mut unreduced = signature.clone(); + unreduced[32..].copy_from_slice(&s); + assert!(!certificate.verifies(b"message", &unreduced)); + // Another root: another key. + let other = Certificate::parse(&data, &crate::ROOT_KEY).unwrap(); + assert!(!other.verifies(b"message", &signature)); + } + } + + #[test] + fn ed25519_matches_rfc_8032() { + // RFC 8032, 7.1, tests 1 and 2. + let key = hex::<32>("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"); + let signature = hex::<64>( + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + ); + assert!(verify_ed25519(&key, b"", &signature)); + assert!(!verify_ed25519(&key, b"\x72", &signature)); + let key = hex::<32>("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"); + let signature = hex::<64>( + "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00", + ); + assert!(verify_ed25519(&key, b"\x72", &signature)); + assert!(!verify_ed25519(&key, b"\x73", &signature)); + } + + #[test] + fn certificate_kinds_windows_and_format() { + let root = Scalar::from_bytes_mod_order([5; 32]); + let root_key = (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes(); + let leaf = Scalar::from_bytes_mod_order([7; 32]); + for kind in [4, 5, 7, 32] { + let (data, _) = chain(root, None, leaf, kind, NOW - 10, NOW + 10); + assert!(!Certificate::parse(&data, &root_key).unwrap().signs_myts_data(), "{}", kind); + } + // A leaf valid longer than the block above it. + let (data, _) = chain(root, Some((NOW - 5, NOW + 5)), leaf, 6, NOW - 10, NOW + 10); + assert!(Certificate::parse(&data, &root_key).is_err()); + let (mut data, _) = chain(root, None, leaf, 6, NOW - 10, NOW + 10); + data[0] = 0; + assert!(matches!(Certificate::parse(&data, &root_key), Err(CertificateError::Version))); + assert!(matches!(Certificate::parse(&[1], &root_key), Err(CertificateError::Empty))); + assert!(Certificate::parse(&[], &root_key).is_err()); + data[0] = 1; + data[34] = 9; + assert!(Certificate::parse(&data, &root_key).is_err()); + } } diff --git a/crates/voelin-android/src/foreground.rs b/crates/voelin-android/src/foreground.rs index e48434e..afe59c4 100644 --- a/crates/voelin-android/src/foreground.rs +++ b/crates/voelin-android/src/foreground.rs @@ -13,7 +13,7 @@ use std::sync::Arc; use voelin_core::stream::{StreamState, ViewerInfo, ViewerState}; use voelin_core::{Event, SessionId, VoiceState}; -use voelin_model::Presence; +use voelin_model::{Presence, channel_title}; /// What the voice notification shows. #[derive(Clone, Debug, PartialEq, Eq)] @@ -72,13 +72,13 @@ impl Session { self.name.as_deref().unwrap_or("a server") } - /// Our channel's name and how many are in it. + /// Our channel's name (a spacer's text) and how many are in it. fn channel(&self) -> Option<(&str, usize)> { let id = self.own_channel?; let channel = self.presence.channels.get(&id)?; let people = self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count(); - Some((channel.name.as_str(), people)) + Some((channel_title(channel).0, people)) } } @@ -222,8 +222,11 @@ mod tests { fn presence(people: u16) -> Event { let mut p = Presence::default(); - p.channels - .insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() }); + // A spacer shows its text. + p.channels.insert( + 2, + ChannelInfo { id: 2, name: "[cspacer1]Chill Zone".into(), ..Default::default() }, + ); for id in 1..=people { p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() }); } diff --git a/crates/voelin-audio/src/mixer.rs b/crates/voelin-audio/src/mixer.rs index 1b56142..e022426 100644 --- a/crates/voelin-audio/src/mixer.rs +++ b/crates/voelin-audio/src/mixer.rs @@ -1,5 +1,6 @@ //! Incoming voice: per-client jitter buffer, decoder and mixer, with a -//! volume and mute per client. +//! volume and mute per client, and everyone else dimmed while a priority +//! speaker talks. //! //! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per //! sender it keeps a queue of Opus packets and adapts its length: @@ -24,16 +25,44 @@ use tsclientlib::ClientId; use tsclientlib::audio::{AudioHandler, Error as QueueError}; use tsproto_packets::packets::InAudioBuf; +use crate::pcm::FRAME_SAMPLES; + /// Loudest per-client volume: +12 dB. pub const MAX_CLIENT_VOLUME: f32 = 4.0; +/// Most a priority speaker dims the others (dB). +const MAX_DIMM_DB: f32 = -60.0; +/// The dimming for a priority speaker fades in and out over this many +/// samples (5 frames, 100 ms) instead of jumping. +const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES; /// Jitter buffer, decoder and mixer for incoming voice, keyed by sender. /// Output is interleaved stereo at 48 kHz. -#[derive(Default)] pub struct Mixer { handler: AudioHandler, volumes: HashMap, muted: HashSet, + /// While one of them talks, everyone else is dimmed. + priority: HashSet, + /// Linear gain of the others while a priority speaker talks (1: none). + dimm: f32, + /// How far the dimming has faded in (0..=1). + fade: f32, + /// The others' mix while the dimming fades (reused). + others: Vec, +} + +impl Default for Mixer { + fn default() -> Self { + Self { + handler: AudioHandler::new(), + volumes: HashMap::new(), + muted: HashSet::new(), + priority: HashSet::new(), + dimm: 1.0, + fade: 0.0, + others: Vec::new(), + } + } } impl Mixer { @@ -53,18 +82,63 @@ impl Mixer { } /// Add the next `buf.len() / 2` stereo frames of all talkers to `buf` - /// (not cleared first), each scaled by its volume. Returns the clients - /// that stopped talking. + /// (not cleared first), each scaled by its volume, and dimmed while a + /// priority speaker talks. Returns the clients that stopped talking. pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec { - for (id, queue) in self.handler.get_mut_queues() { - queue.volume = if self.muted.contains(id) { + let queues = self.handler.get_mut_queues(); + // A priority speaker with a queue (talking or buffering) dims all + // other queues, streams too, unless we muted it. + let dim = queues.keys().any(|id| self.priority.contains(id) && !self.muted.contains(id)); + let frames = buf.len() / 2; + let step = frames as f32 / DIMM_RAMP_SAMPLES as f32; + let from = self.fade; + self.fade = if dim { (from + step).min(1.0) } else { (from - step).max(0.0) }; + let to = self.fade; + let dimm = self.dimm; + let gain = |fade: f32| 1.0 + (dimm - 1.0) * fade; + let fading = from != to; + // While fading, the others are mixed into a buffer of their own and + // ramped sample by sample; the priority speakers go straight to `buf`. + let mut priority = Vec::new(); + for (id, queue) in queues { + // Muted talkers are still decoded so their queues stay in sync. + let volume = if self.muted.contains(id) { 0.0 } else { self.volumes.get(id).copied().unwrap_or(1.0) }; + queue.volume = if self.priority.contains(id) { + if fading { + priority.push((*id, volume)); + 0.0 + } else { + volume + } + } else if fading { + volume + } else { + volume * gain(to) + }; } - // Muted talkers are still decoded so their queues stay in sync. - self.handler.fill_buffer(buf) + if !fading { + return self.handler.fill_buffer(buf); + } + self.others.clear(); + self.others.resize(buf.len(), 0.0); + let stopped = self.handler.fill_buffer_with_proc(&mut self.others, |id, samples| { + if let Some(&(_, volume)) = priority.iter().find(|(p, _)| p == id) { + for (out, s) in buf.iter_mut().zip(samples) { + *out += s * volume; + } + } + }); + // From the last frame's gain to this one's. + for (i, (out, s)) in buf.chunks_exact_mut(2).zip(self.others.chunks_exact(2)).enumerate() { + let g = gain(from + (to - from) * (i + 1) as f32 / frames as f32); + out[0] += s[0] * g; + out[1] += s[1] * g; + } + stopped } /// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`]. @@ -99,6 +173,16 @@ impl Mixer { self.muted.contains(&id) } + /// The priority speakers, and how much everyone else is dimmed while + /// one of them talks: dB, clamped to -60..=0 (NaN: not at all). + /// Replaces the previous set; [`forget`](Self::forget) leaves it alone, + /// the caller sends a new set when the clients change. + pub fn set_priority(&mut self, clients: impl IntoIterator, dimm_db: f32) { + self.priority = clients.into_iter().collect(); + let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) }; + self.dimm = 10f32.powf(db / 20.0); + } + /// Forget volume and mute of a client (e.g. it left the server; client /// ids are reused). pub fn forget(&mut self, id: ClientId) { @@ -129,6 +213,8 @@ impl std::fmt::Debug for Mixer { .field("talkers", &self.handler.get_queues().len()) .field("volumes", &self.volumes) .field("muted", &self.muted) + .field("priority", &self.priority) + .field("dimm", &self.dimm) .finish() } } @@ -199,6 +285,136 @@ mod tests { assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4); } + /// A priority speaker dims the other talker by the server's -18 dB, fading + /// in and out, but not itself, and not while we muted it. + #[test] + fn priority_speaker_dims_others() { + let (a, p) = (ClientId(3), ClientId(5)); + let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let tone_a = pcm::sine(500.0, 4.0, 0.2); + let tone_p = pcm::sine(1300.0, 4.0, 0.2); + let frame = |tone: &[f32], i: u16| { + let at = i as usize * FRAME_SAMPLES; + tone[at..at + FRAME_SAMPLES].to_vec() + }; + + let mut mixer = Mixer::new(); + mixer.set_priority([p], -18.0); + let (mut id_a, mut id_p) = (0u16, 0u16); + // `frames` frames with a talking and p too if `with_p`; returns the + // second half of the mix. + let mut play = |mixer: &mut Mixer, frames: u16, with_p: bool| { + let mut out = Vec::new(); + for _ in 0..frames { + let fa = frame(&tone_a, id_a); + mixer + .handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap())) + .unwrap(); + id_a += 1; + if with_p { + let fp = frame(&tone_p, id_p); + let data = enc_p.encode_to_bytes(&fp).unwrap(); + mixer.handle_packet(p, packet(5, id_p, data)).unwrap(); + id_p += 1; + } + let mut buf = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut buf); + out.extend(pcm::to_mono(&buf, 2)); + } + out.split_off(out.len() / 2) + }; + let power = |out: &[f32], f| pcm::goertzel_power(out, f, SAMPLE_RATE); + let db = |level: f32, full: f32| 10.0 * (level / full).log10(); + + let alone = play(&mut mixer, 30, false); + let full = power(&alone, 500.0); + assert!(full > 1e-4); + // The dimming fades in over 5 frames: 1/5 of the way after the first. + play(&mut mixer, 1, true); + assert!((mixer.fade - 0.2).abs() < 1e-6, "fade {}", mixer.fade); + let both = play(&mut mixer, 50, true); + let dimmed = db(power(&both, 500.0), full); + assert!((dimmed + 18.0).abs() < 1.0, "dimmed by {dimmed} dB"); + let own = db(power(&both, 1300.0), full); + assert!(own.abs() < 1.0, "priority speaker at {own} dB"); + + // p stops: its queue ends after three lost frames, and a is back. + let after = play(&mut mixer, 40, false); + assert_eq!(mixer.talkers().collect::>(), vec![a]); + assert_eq!(mixer.fade, 0.0); + let back = db(power(&after, 500.0), full); + assert!(back.abs() < 1.0, "after the priority speaker: {back} dB"); + + // A priority speaker we muted dims nobody. + mixer.set_muted(p, true); + let muted = play(&mut mixer, 40, true); + assert_eq!(mixer.talkers().count(), 2); + let level = db(power(&muted, 500.0), full); + assert!(level.abs() < 1.0, "muted priority speaker: {level} dB"); + assert!(power(&muted, 1300.0) < 1e-6); + } + + /// The dimming fades in and out sample by sample, not in a step per + /// frame: the other talker's level (per period of its tone) never jumps. + #[test] + fn priority_dimming_ramps_per_sample() { + let (a, p) = (ClientId(3), ClientId(5)); + let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let tone = pcm::sine(500.0, 2.0, 0.2); + let mut mixer = Mixer::new(); + mixer.set_priority([p], -18.0); + // p is not heard (volume 0) but dims, so the mix is a's tone alone. + mixer.set_volume(p, 0.0); + let mut out = Vec::new(); + // p talks from frame 30 to 59. + for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() { + let id = i as u16; + mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap(); + if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) { + let data = enc_p.encode_to_bytes(frame).unwrap(); + mixer.handle_packet(p, packet(5, j as u16, data)).unwrap(); + } + let mut buf = vec![0.0; FRAME_SAMPLES * 2]; + mixer.fill_buffer(&mut buf); + out.extend(pcm::to_mono(&buf, 2)); + } + assert_eq!(mixer.fade, 0.0); + // The level per period of the 500 Hz tone (96 samples, 10 a frame). + let level: Vec = out.chunks_exact(96).map(|c| pcm::energy(c).sqrt()).collect(); + let full = level[200..300].iter().sum::() / 100.0; + let mean = |range: std::ops::Range| { + level[range.clone()].iter().sum::() / range.len() as f32 / full + }; + let jump = level[200..].windows(2).map(|w| (w[1] - w[0]).abs() / full).fold(0.0, f32::max); + assert!(jump < 0.05, "the level jumps by {jump} of full"); + // Fully dimmed after 5 frames, and back after p's queue ended. + let dimmed = mean(350..600); + assert!((dimmed - 0.126).abs() < 0.02, "dimmed to {dimmed}"); + let back = mean(800..1000); + assert!((back - 1.0).abs() < 0.05, "back to {back}"); + } + + #[test] + fn priority_dimm_bounds() { + let mut mixer = Mixer::new(); + assert_eq!(mixer.dimm, 1.0); + mixer.set_priority([ClientId(1)], -18.0); + assert!((mixer.dimm - 0.1259).abs() < 1e-3); + mixer.set_priority([ClientId(1)], 6.0); + assert_eq!(mixer.dimm, 1.0); + mixer.set_priority([ClientId(1)], f32::NEG_INFINITY); + assert!((mixer.dimm - 0.001).abs() < 1e-6); + mixer.set_priority([ClientId(1)], f32::NAN); + assert_eq!(mixer.dimm, 1.0); + // Forgetting a client keeps the set: the caller replaces it. + mixer.forget(ClientId(1)); + assert!(mixer.priority.contains(&ClientId(1))); + mixer.set_priority([], -18.0); + assert!(mixer.priority.is_empty()); + } + #[test] fn volume_bounds_and_forget() { let mut mixer = Mixer::new(); diff --git a/crates/voelin-core/Cargo.toml b/crates/voelin-core/Cargo.toml index 254f67b..7b71e37 100644 --- a/crates/voelin-core/Cargo.toml +++ b/crates/voelin-core/Cargo.toml @@ -29,8 +29,15 @@ futures = "0.3" # Finding a server's gateway in DNS (the voice resolver's version). hickory-resolver = "0.26" md5 = "0.8" +# A stalled HTTP/2 connection's error, told apart (the version reqwest's hyper +# uses). +h2 = "0.4" +# Retry-After dates (already in the tree through hyper). +httpdate = "1" # Banners on the web; the client the workspace has (voelin-query, voelin-media). -reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] } +# `system-proxy`: the proxy settings of Windows and macOS; `socks`: SOCKS +# proxies (from the desktop's settings or ALL_PROXY). +reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "socks", "system-proxy"] } # Reading the official clients' settings.db when importing identities. rusqlite = { version = "0.40.2", features = ["bundled"] } serde = { version = "1", features = ["derive"] } @@ -57,6 +64,9 @@ tsproto-packets = { path = "../proto/tsproto-packets" } tsproto-types = { path = "../proto/tsproto-types" } [dev-dependencies] +# An HTTP/2 connection in a test (both already in the tree through h2). +bytes = "1" +http = "1" # Already in the app's graph (reqwest); for one_rustls_crypto_provider. rustls = { version = "0.23", default-features = false } voelin-myts = { path = "../voelin-myts" } diff --git a/crates/voelin-core/src/audio.rs b/crates/voelin-core/src/audio.rs index 5d4602f..cdac01b 100644 --- a/crates/voelin-core/src/audio.rs +++ b/crates/voelin-core/src/audio.rs @@ -42,6 +42,12 @@ pub(crate) enum AudioIn { }, /// The client left; client ids are reused, so forget its volume. ClientLeft(ClientId), + /// The priority speakers: while one talks, everyone else (streams too) + /// is dimmed by `dimm_db` (the server's setting, e.g. -18). + PrioritySpeakers { + clients: Vec, + dimm_db: f32, + }, /// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time /// on the 48 kHz clock. StreamAudio { @@ -208,6 +214,9 @@ impl Pipeline { AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume), AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted), AudioIn::ClientLeft(client) => self.mixer.forget(client), + AudioIn::PrioritySpeakers { clients, dimm_db } => { + self.mixer.set_priority(clients, dimm_db); + } AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data), AudioIn::StreamVolume { stream, volume } => { if let Some(s) = self.streams.get(&stream) { @@ -547,7 +556,7 @@ mod devices { #[cfg(test)] mod tests { - use voelin_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise}; + use voelin_audio::pcm::{SAMPLE_RATE, energy, goertzel_power, sine, white_noise}; use voelin_audio::{ProcessingSettings, VadSettings}; use super::*; @@ -668,6 +677,44 @@ mod tests { assert!(!p.mixer.is_muted(ClientId(3))); } + /// While a priority speaker talks, another talker and a watched stream + /// are dimmed by the server's setting. + #[test] + fn priority_speaker() { + let mut p = pipeline(TransmitMode::PushToTalk); + p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 }); + let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap(); + let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap(); + let tone = sine(700.0, 2.0, 0.3); + let stream = pcm::from_mono(&sine(1100.0, 2.0, 0.3), 2); + let other = sine(1700.0, 1.0, 0.3); + let mut out = Vec::new(); + for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() { + p.handle(incoming(1, i as u16, voice.encode_to_bytes(frame).unwrap())); + let frame = &stream[i * FRAME_SAMPLES * 2..(i + 1) * FRAME_SAMPLES * 2]; + let data: Arc<[u8]> = music.encode_to_bytes(frame).unwrap().into(); + let time = i as u64 * OPUS_FRAME; + p.handle(AudioIn::StreamAudio { stream: "s".into(), time, data }); + // The priority speaker talks during the second second. + if let Some(j) = i.checked_sub(50) { + let frame = &other[j * FRAME_SAMPLES..(j + 1) * FRAME_SAMPLES]; + p.handle(incoming(2, j as u16, priority.encode_to_bytes(frame).unwrap())); + } + out.extend(p.playback_frame()); + } + // The second half of each second. + let half = SAMPLE_RATE as usize / 2; + let level = |second: usize, freq: f32| { + let from = second * 2 * half + half; + goertzel_power(&out[from..from + half], freq, SAMPLE_RATE) + }; + for freq in [700.0, 1100.0] { + let ratio_db = 10.0 * (level(1, freq) / level(0, freq)).log10(); + assert!((ratio_db + 12.0).abs() < 1.0, "{freq} Hz dimmed by {ratio_db} dB"); + } + } + /// End to end: a remote talker is played, the speakers leak into the /// microphone 30 ms later, and the echo canceller (fed with what was /// played) removes it from what we would send. diff --git a/crates/voelin-core/src/book.rs b/crates/voelin-core/src/book.rs index 83c65d3..98cc7f7 100644 --- a/crates/voelin-core/src/book.rs +++ b/crates/voelin-core/src/book.rs @@ -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, @@ -60,6 +60,8 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails { platform: server.platform.clone(), version: server.version.clone(), max_clients: server.max_clients, + // `as` saturates (and turns NaN into 0); the mixer clamps it. + priority_speaker_dimm_db: server.priority_speaker_dimm_modificator.round() as i32, default_server_group: Some(server.default_server_group.0), default_channel_group: Some(server.default_channel_group.0), } @@ -115,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 @@ -147,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, @@ -177,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 ", @@ -200,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"), @@ -265,5 +283,52 @@ mod tests { assert_eq!(p.server.banner_gfx_interval_s, 60); assert_eq!(p.server.banner_mode, BannerMode::KeepAspect); 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")); } } diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs index adab3fd..4410be4 100644 --- a/crates/voelin-core/src/cache.rs +++ b/crates/voelin-core/src/cache.rs @@ -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/`: 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) + Send>; +pub(crate) type Waiter = Box) + 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, retry: RetryHint) -> Self { + Self { text: text.into(), retry } + } +} + +impl From 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, + pub last_modified: Option, +} + +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 { + 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, + 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 { + 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() { diff --git a/crates/voelin-core/src/discover.rs b/crates/voelin-core/src/discover.rs index 804b8e5..e1da0cb 100644 --- a/crates/voelin-core/src/discover.rs +++ b/crates/voelin-core/src/discover.rs @@ -8,16 +8,31 @@ //! - SRV `_tsgws._tcp.`: `wss://:`, //! - SRV `_tsgw._tcp.`: `ws://:`, //! -//! TLS first at the same name; `` is `path=…` from a TXT record at the -//! SRV record's name, `/v1` without one. Without any such record, as TSDNS -//! has its well-known port, the gateway itself is asked at tsgw's default -//! port: `http://:7788/.well-known/tsgw` answers `{"url": "…"}`. For an -//! IP address (or `localhost`) only that is tried. What an admin publishes is -//! in `docs/gateway-admin.md`. +//! `` 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://: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> + Send + Sync; +type ProbeFn = dyn Fn(String) -> BoxFuture<'static, Option> + Send + Sync; /// Where [`gateway`] gets its answers from; the tests put fakes in. #[derive(Clone)] @@ -45,28 +67,47 @@ struct Lookups { srv: Arc, /// The strings of the TXT records at a name. txt: Arc, - /// 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, } 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 { - gateway_with(address, Lookups::system()).await +/// A DNS answer, the failure logged (no record at most names is normal). +fn dns_answer( + name: &str, + kind: &str, + started: Instant, + lookup: Result, +) -> Option { + 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 { +/// 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 { + gateways_with(address, Lookups::system()).await +} + +async fn gateways_with(address: &str, lookups: Lookups) -> Vec { + 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::().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::().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>)>); + +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 { + 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 { - 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, + /// The TXT strings at the records' names. + txt: Vec, +} + +/// 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> { + 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 { - let answers = - join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await; - answers.into_iter().find_map(|answer| answer.ok().flatten()) -} - -/// tsgw's answer at `http://:/.well-known/tsgw`. -async fn well_known(host: &str, port: u16) -> Option { - let mut stream = TcpStream::connect((host, port)).await.ok()?; +/// tsgw's answer at `http://:/.well-known/tsgw`; else what +/// happened instead. +async fn well_known(host: &str, port: u16) -> Result { + 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] diff --git a/crates/voelin-core/src/gateway.rs b/crates/voelin-core/src/gateway.rs index a75eb9f..f534544 100644 --- a/crates/voelin-core/src/gateway.rs +++ b/crates/voelin-core/src/gateway.rs @@ -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), /// A push other than presence. Push(Box), @@ -83,42 +97,84 @@ pub async fn connect( url: &str, identity: &tsclientlib::Identity, ) -> Result<(GatewayClient, mpsc::UnboundedReceiver), 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), 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, identity: tsclientlib::Identity, mut commands: mpsc::UnboundedReceiver, events: mpsc::UnboundedSender, ) { - // 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 = 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, + /// 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, +} + +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, events: &mpsc::UnboundedSender, 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, commands: &mut mpsc::UnboundedReceiver, events: &mpsc::UnboundedSender, chats: &mut Chats, + connected: Instant, ) -> Result { + 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 = (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 = (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, Arc) { + 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 = 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); + } +} diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index e9424f6..8a15086 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -39,9 +39,9 @@ //! [`Event::Poke`]), private messages to any client (a //! [`ChatTarget::Private`] chat, stored under the peer's unique id), the //! channels' file browsers, avatars and icons ([`files`], cached in -//! [`cache`]) and offline messages ([`offline`]). The host banner and -//! channel banners are pictures on the web, fetched into the same cache -//! ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person +//! [`cache`]) and offline messages ([`offline`]). The host banner, channel +//! banners and the clients' badges are pictures on the web, fetched into the +//! same cache ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person //! volume) are engine-wide ([`contacts`]). mod audio; @@ -96,14 +96,27 @@ 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; +/// The longest poke message servers take, in characters; a longer one is +/// cut ([`Command::Poke`]). +pub const POKE_MESSAGE_MAX: usize = 100; + /// What the UI asks for. #[derive(Clone, Debug)] pub enum Command { /// Main account proof for every current and future voice connection. SetMytsIdentity(Option>), + /// 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>), ConnectVoice { session: SessionId, options: Box, @@ -111,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, identity: Box, }, /// Invisible presence and relay chat with own ServerQuery credentials. @@ -153,6 +170,7 @@ pub enum Command { session: SessionId, request: GatewayRequest, }, + /// Refusals come as [`Event::JoinFailed`]. MoveToChannel { session: SessionId, channel: ChannelId, @@ -273,7 +291,8 @@ pub enum Command { volume: f32, }, /// Poke a client (voice): the server shows it a notification with - /// `message`. Failures come as [`Event::Error`]. + /// `message`, cut to [`POKE_MESSAGE_MAX`] characters. Failures come as + /// [`Event::Error`]. Poke { session: SessionId, client: u16, @@ -365,6 +384,14 @@ pub enum Command { session: SessionId, client_uid: String, }, + /// Get a picture on the web that a chat message shows (`[img]`) into + /// the cache ([`Event::PictureReady`]) while `cache.fetch_images` is on; + /// one larger than `max_bytes` is not reported. + FetchPicture { + session: SessionId, + url: String, + max_bytes: u64, + }, /// Our offline messages ([`Event::OfflineMessages`]); see [`offline`]. ListOfflineMessages { session: SessionId, @@ -469,6 +496,17 @@ pub struct SessionState { pub server_uid: Option, } +/// Why the server did not let us into a channel ([`Event::JoinFailed`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum JoinFailure { + /// The channel's password is missing or wrong. + Password, + /// The channel, or the channel with its subchannels, is full. + Full, + /// Anything else, as a sentence for the user. + Other(String), +} + /// What the engine reports. #[derive(Clone, Debug)] pub enum Event { @@ -534,6 +572,12 @@ pub enum Event { session: SessionId, message: String, }, + /// The server refused [`Command::MoveToChannel`] into `channel`. + JoinFailed { + session: SessionId, + channel: ChannelId, + reason: JoinFailure, + }, /// The streams in our channel (TeamSpeak 6), full list. StreamsChanged { session: SessionId, @@ -640,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, @@ -656,9 +701,11 @@ pub enum Event { path: PathBuf, }, /// A picture on the web is in the cache: the host banner - /// ([`ServerDetails::banner_gfx_url`]) or a channel's - /// ([`voelin_model::ChannelInfo::banner_gfx_url`]) at `url` (setting - /// `cache.fetch_images`). Comes again when the host banner was reloaded + /// ([`ServerDetails::banner_gfx_url`]), a channel's + /// ([`voelin_model::ChannelInfo::banner_gfx_url`]), a badge's + /// ([`voelin_model::badges::icon_url`]) or one a chat message shows + /// ([`Command::FetchPicture`]) at `url` (setting `cache.fetch_images`). + /// Comes again when the host banner was reloaded /// (`banner_gfx_interval_s`, at least a minute): the file at `path` /// changed. PictureReady { @@ -816,6 +863,7 @@ async fn run( contacts.load().await; let mut sessions: HashMap = 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)); @@ -873,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() { @@ -949,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())); @@ -1020,6 +1079,7 @@ fn command_session(command: &Command) -> SessionId { | Command::CreateDirectory { session, .. } | Command::SetAvatar { session, .. } | Command::FetchAvatar { session, .. } + | Command::FetchPicture { session, .. } | Command::ListOfflineMessages { session, .. } | Command::GetOfflineMessage { session, .. } | Command::SendOfflineMessage { session, .. } @@ -1027,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 { .. } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index e011d1c..348fae5 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -15,15 +15,15 @@ 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}; -use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails}; +use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, badges}; 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>>, + myts_data: watch::Receiver>>, ) -> 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), + ImageFinished(bool, u64, ImageRequest, Result), } /// 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, + /// 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 { + 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, + error: &FetchError, + newly_gone: bool, + reload_s: Option, +) { + 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>>, + myts_data: watch::Receiver>>, id: SessionId, events: broadcast::Sender, state: SessionState, @@ -187,6 +304,9 @@ struct Session { gateway_presence: Option, /// The logged-in gateway, for requests. gateway_client: Option, + /// What the running `gateway` observes with: asking again for the same + /// does not start it over. + gateway_observed: Option, query: Option<(u64, mpsc::UnboundedSender)>, query_presence: Option, audio: Option, @@ -222,10 +342,25 @@ struct Session { contacts_rx: Option>, /// Avatars reported per client unique id (their hash), voice only. avatars: HashMap, + /// myTeamSpeak avatars wanted per client unique id (their link), any + /// presence: where the server's avatar is not shown. + myts_avatars: HashMap, + /// 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, /// Icons reported or being fetched, voice only. icons: HashSet, - /// Pictures on the web (banners) reported or being fetched, by address. + /// Pictures on the web (banners, badges) reported or being fetched, by + /// address. pictures: HashSet, + /// Pictures on the web that chat messages show, reported or being + /// fetched, by address, with the size they may have + /// ([`Command::FetchPicture`]). + chat_pictures: HashMap, + /// Banner addresses that cannot be fetched at all (another scheme), + /// logged once. + unfetchable: HashSet, image_epoch: u64, images_enabled: bool, image_retries: HashMap, @@ -234,6 +369,9 @@ struct Session { banner_reload: Option<(String, u64, tokio::task::AbortHandle)>, /// Contact volume and mute applied per client. contact_audio: HashMap, + /// Priority speakers and the server's dimming (dB) as told to the + /// audio thread. + priority_audio: (BTreeSet, i32), /// Friends' client ids, as last told to the streams. stream_friends: BTreeSet, /// The server's details and groups as last reported. @@ -249,23 +387,30 @@ impl Session { audio_settings: AudioSettings, shared: Shared, myts_identity: watch::Receiver>>, + myts_data: watch::Receiver>>, ) -> 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(), banner_reload: None, contact_audio: HashMap::new(), + priority_audio: Default::default(), stream_friends: BTreeSet::new(), details: None, groups: None, @@ -280,6 +425,7 @@ impl Session { gateway: None, gateway_presence: None, gateway_client: None, + gateway_observed: None, query: None, query_presence: None, audio: None, @@ -388,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(), @@ -404,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; @@ -666,9 +832,22 @@ 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, .. } => { + if self.settings.current().get(&CACHE_FETCH_IMAGES) + && cache::picture_key(&url).is_some() + && !self.chat_pictures.contains_key(&url) + { + self.chat_pictures.insert(url.clone(), max_bytes); + self.fetch_chat_picture(&url); } } Command::ListOfflineMessages { request, .. } => { @@ -699,6 +878,7 @@ impl Session { } // Engine-wide. Command::SetMytsIdentity(_) + | Command::SetMytsData(_) | Command::CloseSession { .. } | Command::TestMicrophone { .. } | Command::SetSetting { .. } @@ -821,9 +1001,14 @@ 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(); self.details = None; self.groups = None; @@ -859,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 @@ -877,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); @@ -887,8 +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), + ImageRequest::ChatPicture(url) => self.chat_pictures.contains_key(url), } } @@ -897,16 +1123,28 @@ impl Session { requested: bool, epoch: u64, request: ImageRequest, - result: Result, + result: Result, ) { 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 @@ -917,31 +1155,75 @@ 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::ChatPicture(url) = &request + && let Some(max) = self.chat_pictures.get(url) + && std::fs::metadata(&path).is_ok_and(|m| m.len() > *max) + { + return; + } let session = self.id; self.emit(match request { 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); + } + } } } } @@ -952,8 +1234,11 @@ 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(); self.image_retries.clear(); if let Some((.., timer)) = self.banner_reload.take() { timer.abort(); @@ -989,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), } } } @@ -1002,8 +1289,9 @@ impl Session { || (self.voice_presence.is_some() && files::server_image(url).is_some()) } - /// Fetch the banners of the presence shown (any source) that are new, - /// and have the host banner reloaded as often as the server asks. + /// Fetch the banners and the clients' badges of the presence shown (any + /// source) that are new, and have the host banner reloaded as often as + /// the server asks. fn fetch_pictures(&mut self, p: &Presence) { let enabled = self.settings.current().get(&CACHE_FETCH_IMAGES); let reload = Some((&p.server.banner_gfx_url, p.server.banner_gfx_interval_s)) @@ -1034,11 +1322,25 @@ impl Session { if !enabled { return; } - let urls: HashSet<_> = std::iter::once(&p.server.banner_gfx_url) + 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| self.can_fetch_picture(u)) - .cloned() - .collect(); + .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)); + urls.extend(badge_urls); self.pictures.retain(|url| urls.contains(url)); for url in &urls { if self.pictures.insert(url.clone()) { @@ -1047,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) { @@ -1060,6 +1369,15 @@ impl Session { } } + /// 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) { @@ -1139,6 +1457,19 @@ impl Session { } } + /// Tell the audio thread who the priority speakers are and how much they + /// dim the others, when that changed (voice presence). + fn apply_priority(&mut self, p: &Presence) { + let Some(a) = &self.audio else { return }; + let clients = p.clients.values().filter(|c| c.priority_speaker).map(|c| c.id).collect(); + let wanted = (clients, p.server.priority_speaker_dimm_db); + if wanted != self.priority_audio { + let clients = wanted.0.iter().map(|c| ClientId(*c)).collect(); + a.send(AudioIn::PrioritySpeakers { clients, dimm_db: wanted.1 as f32 }); + self.priority_audio = wanted; + } + } + /// Report the server's details and groups when they changed. fn report_details(&mut self, p: &Presence) { if self.details.as_deref() != Some(&p.server) { @@ -1470,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); } @@ -1582,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); } @@ -1600,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 @@ -1649,6 +1989,7 @@ impl Session { self.report_details(&p); self.fetch_images(&p); self.apply_contacts(&p); + self.apply_priority(&p); self.voice_presence = Some(*p); self.publish_presence(); } @@ -1711,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()); @@ -1721,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, @@ -1747,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; @@ -1919,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 }); @@ -1947,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] @@ -2123,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, + ) -> Vec { + 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::::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"); @@ -2138,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. @@ -2211,6 +2703,126 @@ mod banner_tests { std::fs::remove_dir_all(cache.dir()).unwrap(); } + /// A picture a chat message shows comes only with `cache.fetch_images`, + /// is fetched once, and is reported only while it is no larger than + /// asked for. + #[tokio::test] + async fn chat_pictures_obey_policy_and_their_size() { + let (mut session, mut events) = session("chat-pictures"); + let url = "https://example.com/meme.png"; + let cache = session.cache.current(); + let key = cache::picture_key(url).unwrap(); + let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else { + panic!("first download"); + }; + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(&temp, b"cached image").unwrap(); + cache.finish(&key, &temp, Ok(()), 0); + let fetch = |max_bytes| Command::FetchPicture { session: 1, url: url.into(), max_bytes }; + let ready = |events: &mut broadcast::Receiver| { + let mut ready = false; + while let Ok(event) = events.try_recv() { + ready |= + matches!(event, Event::PictureReady { url: address, .. } if address == url); + } + ready + }; + session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap(); + session.command(fetch(100)); + assert!(session.chat_pictures.is_empty()); + session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap(); + session.command(fetch(100)); + let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap(); + session.source_event(completion); + assert!(ready(&mut events)); + // Asked for again: nothing more. + session.command(fetch(100)); + assert!(session.sources_rx.as_mut().unwrap().try_recv().is_err()); + // The file is larger than asked for now: not reported. + session.forget_images(); + session.command(fetch(4)); + let completion = session.sources_rx.as_mut().unwrap().recv().await.unwrap(); + session.source_event(completion); + assert!(!ready(&mut events)); + 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::>(), ["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::>(), ["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"); @@ -2273,4 +2885,110 @@ mod banner_tests { tokio::task::yield_now().await; assert!(timer.is_finished()); } + + /// The pictures of the badges clients show (the first three of each, the + /// known ones) come with the presence, and only with + /// `cache.fetch_images`. + #[tokio::test] + async fn badge_pictures_come_with_the_presence() { + let (mut session, _) = session("badges"); + let guids = [ + "4b27be5a-b92a-4b30-8b2d-14b59653f427", + "00000000-0000-0000-0000-000000000000", + "2bf80270-8efe-46dc-a472-3280a0479145", + "05114019-6b46-4b13-b5a1-e5179ef69fb5", + ]; + let mut presence = Presence::default(); + let client = voelin_model::ClientInfo { + id: 1, + badges: guids.iter().map(|g| g.to_string()).collect(), + ..Default::default() + }; + presence.clients.insert(1, client); + // Own the downloads, so none goes to the network. + let cache = session.cache.current(); + let urls: Vec = guids.iter().filter_map(|g| badges::icon_url(g)).collect(); + for url in &urls { + let _pending = cache.fetch(&cache::picture_key(url).unwrap(), false, Box::new(|_| {})); + } + session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap(); + session.fetch_pictures(&presence); + assert!(session.pictures.is_empty()); + session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap(); + session.fetch_pictures(&presence); + let mut fetched: Vec<_> = session.pictures.iter().cloned().collect(); + fetched.sort(); + let mut shown = urls[..2].to_vec(); + shown.sort(); + assert_eq!( + fetched, shown, + "the unknown second badge has no picture; the fourth is not shown" + ); + // Gone with the client. + session.fetch_pictures(&Presence::default()); + assert!(session.pictures.is_empty()); + let _ = std::fs::remove_dir_all(cache.dir()); + } + + /// The priority speakers and the server's dimming reach the audio thread + /// once, and again when either changes. + #[tokio::test] + async fn priority_speakers_reach_the_audio_thread_when_changed() { + let (mut session, _) = session("priority"); + let (audio, rx) = AudioHandle::channel(); + session.audio = Some(audio); + let mut presence = Presence::default(); + presence.server.priority_speaker_dimm_db = -18; + for (id, priority_speaker) in [(2, false), (5, true)] { + let client = voelin_model::ClientInfo { id, priority_speaker, ..Default::default() }; + presence.clients.insert(id, client); + } + let sent = || -> Vec<(Vec, f32)> { + rx.try_iter() + .filter_map(|msg| match msg { + AudioIn::PrioritySpeakers { clients, dimm_db } => { + Some((clients.iter().map(|c| c.0).collect(), dimm_db)) + } + _ => None, + }) + .collect() + }; + session.apply_priority(&presence); + assert_eq!(sent(), [(vec![5], -18.0)]); + session.apply_priority(&presence); + assert!(sent().is_empty()); + presence.server.priority_speaker_dimm_db = -30; + session.apply_priority(&presence); + assert_eq!(sent(), [(vec![5], -30.0)]); + presence.clients.get_mut(&5).unwrap().priority_speaker = false; + session.apply_priority(&presence); + assert_eq!(sent(), [(vec![], -30.0)]); + // A new connection has a new audio thread: told again. + session.forget_images(); + session.apply_priority(&presence); + 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()); + } } diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 4b42fb1..10996bb 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1121,15 +1121,16 @@ pub static CHAT_RETENTION_DAYS: Key = Key::new( pub static CACHE_MAX_MB: Key = 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 and banners of servers we are on. +/// Download the avatars, icons, banners and badges of servers we are on, +/// and the pictures their chats show (`[img]`). pub static CACHE_FETCH_IMAGES: Key = Key::new( "cache.fetch_images", Kind::Bool, - "Download avatars, icons and banners of the servers we are on.", + "Download avatars, icons, banners and badges of the servers we are on, and pictures in chat.", || true, ); diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index a4687d9..898355a 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -33,7 +33,7 @@ use crate::cache; use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState}; use crate::offline::{OfflineMessage, OfflineMessageInfo}; use crate::settings::{FILES_PROGRESS_MS, SharedSettings}; -use crate::{Event, SessionId}; +use crate::{Event, JoinFailure, POKE_MESSAGE_MAX, SessionId}; #[derive(Clone, Debug)] pub struct VoiceOptions { @@ -43,8 +43,12 @@ pub struct VoiceOptions { /// Signed compatibility version; `None` selects the native platform's tuple. pub client_version: Option, pub server_password: Option, - /// Channel path to join, e.g. `Lobby/Sub`. + /// Channel path to join, e.g. `Lobby/Sub`, or `/`. pub channel: Option, + /// The password of `channel`. + pub channel_password: Option, + /// A privilege key to use when connecting. + pub token: Option, /// Open the audio devices (capture and playback). pub audio: bool, /// Network settings for stream peer connections (TeamSpeak 6). @@ -60,6 +64,8 @@ impl VoiceOptions { client_version: None, server_password: None, channel: None, + channel_password: None, + token: None, audio: false, stream_peer: PeerConfig::default(), } @@ -70,6 +76,8 @@ impl VoiceOptions { #[derive(Clone)] pub(crate) struct VoiceLink { pub myts_identity: watch::Receiver>>, + /// What the server is shown of the account ([`crate::Command::SetMytsData`]). + pub myts_data: watch::Receiver>>, pub session: SessionId, pub events: broadcast::Sender, pub settings: SharedSettings, @@ -225,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 { + 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>), Cmd(Option), @@ -236,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, + badges: Option, + badge_ids: Vec, + }, + /// `clientupdate client_user_tag`: the value (empty: cleared); only logged. + UserTag(String), Stream(Request), FileList { request: RequestId, @@ -253,6 +298,10 @@ enum Pending { id: u32, message: Option, }, + /// Moving ourselves; refusals are reported as [`Event::JoinFailed`]. + Move { + channel: ChannelId, + }, /// Failures are reported as [`VoiceEvent::Error`] with this label. Report(&'static str), /// Best effort: the answer does not matter. @@ -290,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, 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 { @@ -340,6 +393,12 @@ struct Voice { pending: HashMap, jobs: HashMap, transfers: HashMap, + /// `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( @@ -365,7 +424,14 @@ async fn run_inner( if let Some(channel) = &options.channel { builder = builder.channel(channel.clone()); } + if let Some(pw) = options.channel_password.as_ref().filter(|p| !p.is_empty()) { + builder = builder.channel_password(pw.clone()); + } + if let Some(token) = &options.token { + 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 { @@ -433,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 { @@ -445,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 => { @@ -456,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()), @@ -488,6 +571,7 @@ async fn next_input( commands: &mut mpsc::UnboundedReceiver, tick: &mut tokio::time::Interval, identity: &mut watch::Receiver>>, + data: &mut watch::Receiver>>, ) -> Input { tokio::select! { biased; @@ -496,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. @@ -562,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) => { @@ -644,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(); } _ => {} } @@ -801,7 +897,38 @@ impl Voice { }; self.link.emit(Event::OfflineMessage { session, request, result }); } + Pending::Move { channel } => { + if let Err(e) = result + && let Some(reason) = join_failure(e) + { + self.link.emit(Event::JoinFailed { session, channel, reason }); + } + } 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}"))); @@ -810,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>| 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, badges: Option, 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); @@ -840,13 +1090,15 @@ impl Voice { self.send(out, Pending::Report("message"))?; } VoiceCmd::Move(channel, password) => { - let state = self.con.get_state()?; - let own = &state.clients[&state.own_client]; - let mut part = own.client_move(tsclientlib::ChannelId(channel)); - if let Some(pw) = &password { - part = part.set_password(pw); - } - part.send(&mut self.con)?; + let own = self.con.get_state()?.own_client; + let cpw = encode_password(password.as_deref()); + let cmd = + c2s::OutClientMoveMessage::new(&mut std::iter::once(c2s::OutClientMovePart { + client_id: own, + channel_id: tsclientlib::ChannelId(channel), + channel_password: (!cpw.is_empty()).then_some(cpw.as_str().into()), + })); + self.send(cmd, Pending::Move { channel })?; } VoiceCmd::SetInputMuted(muted) => { self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?; @@ -864,7 +1116,7 @@ impl Voice { let cmd = c2s::OutClientPokeRequestMessage::new(&mut std::iter::once( c2s::OutClientPokeRequestPart { client_id: tsclientlib::ClientId(client), - message: message.as_str().into(), + message: poke_message(&message).into(), }, )); self.send(cmd, Pending::Report("poke"))?; @@ -1053,6 +1305,48 @@ impl Voice { } } +/// Why a move into a channel failed, for the user; `None` when there is +/// nothing to tell (we are in that channel already). +fn join_failure(error: TsError) -> Option { + let text = match error { + TsError::ChannelAlreadyIn => return None, + TsError::ChannelInvalidPassword => return Some(JoinFailure::Password), + TsError::ChannelMaxclientsReached | TsError::ChannelMaxfamilyReached => { + return Some(JoinFailure::Full); + } + TsError::ChannelInvalidId => "The channel does not exist any more.".to_owned(), + TsError::PermissionsClientInsufficient | TsError::Permissions => { + "You are not allowed to join this channel.".to_owned() + } + TsError::ClientIsFlooding => "Too many requests: try again in a moment.".to_owned(), + // The error's name in words (its Display is the name). + e => format!("The server refused to move you: {}.", error_words(e)), + }; + Some(JoinFailure::Other(text)) +} + +/// A poke's message as servers take it: its first [`POKE_MESSAGE_MAX`] +/// characters (not bytes, so a letter is never cut in half). +fn poke_message(message: &str) -> &str { + match message.char_indices().nth(POKE_MESSAGE_MAX) { + Some((end, _)) => &message[..end], + None => message, + } +} + +/// A TeamSpeak error's name in lowercase words: +/// `ChannelIsPrivateChannel` is "channel is private channel". +fn error_words(error: TsError) -> String { + let mut words = String::new(); + for c in format!("{error:?}").chars() { + if c.is_ascii_uppercase() && !words.is_empty() { + words.push(' '); + } + words.push(c.to_ascii_lowercase()); + } + words +} + /// A failed transfer, for the user. fn transfer_error(error: &tsclientlib::Error) -> String { match error { @@ -1063,6 +1357,47 @@ fn transfer_error(error: &tsclientlib::Error) -> String { } } +#[cfg(test)] +mod join_tests { + use super::*; + + #[test] + fn refused_moves_say_why() { + assert_eq!(join_failure(TsError::ChannelInvalidPassword), Some(JoinFailure::Password)); + assert_eq!(join_failure(TsError::ChannelMaxclientsReached), Some(JoinFailure::Full)); + assert_eq!(join_failure(TsError::ChannelMaxfamilyReached), Some(JoinFailure::Full)); + // Moving to the channel we are in. + assert_eq!(join_failure(TsError::ChannelAlreadyIn), None); + let other = |text: &str| Some(JoinFailure::Other(text.into())); + assert_eq!( + join_failure(TsError::PermissionsClientInsufficient), + other("You are not allowed to join this channel.") + ); + // The rest in words, not the error's name. + assert_eq!( + join_failure(TsError::ChannelIsPrivateChannel), + other("The server refused to move you: channel is private channel.") + ); + } +} + +#[cfg(test)] +mod poke_tests { + use super::*; + + #[test] + fn long_pokes_are_cut_by_characters() { + assert_eq!(poke_message("hi"), "hi"); + assert_eq!(poke_message(""), ""); + let exact = "x".repeat(POKE_MESSAGE_MAX); + assert_eq!(poke_message(&exact), exact); + // Two bytes each: cut after 100 letters, not 100 bytes. + let long = "ä".repeat(150); + assert_eq!(poke_message(&long), "ä".repeat(POKE_MESSAGE_MAX)); + assert_eq!(poke_message(&"🙂".repeat(101)).chars().count(), POKE_MESSAGE_MAX); + } +} + #[cfg(test)] mod image_download_tests { use super::*; @@ -1087,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!( @@ -1102,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)); } } @@ -1116,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(); @@ -1126,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, @@ -1143,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 = ["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(); @@ -1168,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(); diff --git a/crates/voelin-core/src/web.rs b/crates/voelin-core/src/web.rs index 9af4ddf..a806ab3 100644 --- a/crates/voelin-core/src/web.rs +++ b/crates/voelin-core/src/web.rs @@ -1,69 +1,360 @@ //! Pictures from the web: the host banner and TeamSpeak 6 channel banners, -//! which servers give as `http(s)` addresses on any host. +//! which servers give as `http(s)` addresses on any host, myTeamSpeak +//! avatars, the pictures of the clients' badges on TeamSpeak's server +//! ([`voelin_model::badges::icon_url`]) and pictures in chat messages. //! //! They go into the engine's cache ([`crate::cache`], named by the MD5 hash //! of the address) like avatars and icons, and only with //! `cache.fetch_images`: fetching one contacts a host the server chose, as //! the official client does. A picture is at most -//! [`cache::MAX_PICTURE_BYTES`] and goes to disk as it arrives; it connects -//! within [`CONNECT_TIMEOUT`], and a download fails when nothing arrives for -//! [`READ_TIMEOUT`] or, after [`GRACE`], when it averages less than -//! [`cache::MIN_PICTURE_RATE`]: a large banner on a slow host still arrives. -//! It is kept only if its content is a picture the UI shows (PNG, JPEG, -//! GIF, WebP, SVG), whatever its address or the server say. The client is -//! the workspace's reqwest with rustls: system proxies (`HTTPS_PROXY`, -//! `NO_PROXY`, …) and the platform's certificate store. +//! [`cache::MAX_PICTURE_BYTES`] and goes to disk as it arrives. It is kept +//! only if its content is a picture the UI shows (PNG, JPEG, GIF, WebP, +//! SVG), whatever its address or the server say. Asked for again (a retry, +//! the host banner's reload), a cached picture is downloaded only if its +//! host says it changed (`If-None-Match`, `If-Modified-Since`; a `304` +//! answer has no body). +//! +//! Time limits: a connection (DNS, TCP and TLS) is made within +//! [`CONNECT_TIMEOUT`]. The answer must begin within [`READ_TIMEOUT`] of the +//! request (one deadline, not per read); then a download fails when nothing +//! arrives for [`READ_TIMEOUT`] or, after [`GRACE`], when it averages less +//! than [`cache::MIN_PICTURE_RATE`]: a large banner on a slow host still +//! arrives. A connection whose data stops (the network drops it, as some +//! ISPs do after the first 16 KB to some hosts) ends sooner on Linux and +//! Android: its keepalive probes (after [`KEEPALIVE`]) go unanswered, and +//! the kernel closes it about `TCP_USER_TIMEOUT` (30 s) after its last +//! data; on Windows and macOS [`READ_TIMEOUT`] ends it. The log calls a +//! stop in the data a stall, and says when the connection was HTTP/2's, +//! which carries a host's downloads together (what arrived is this +//! download's share). Before the answer began, on Windows and macOS, a +//! stall cannot be told from a slow host: "no answer within 60 s". A +//! connection never made is told apart. +//! +//! A failure tells when to try again ([`RetryHint`]): an address that is +//! wrong or gone (HTTP 400, 404, 410) not soon, a host that asks to wait +//! (HTTP 429, 503, `Retry-After`) after that wait. +//! +//! The client is the workspace's reqwest with rustls and the platform's +//! certificate store. Proxies: the one the desktop's settings name for an +//! address ([`set_proxy_resolver`]; GNOME's or KDE's through +//! xdg-desktop-portal on Linux), HTTP or SOCKS; when it names none, the +//! system's: the `HTTPS_PROXY`, `ALL_PROXY` and `NO_PROXY` variables, and on +//! Windows and macOS the system settings. Redirects are followed here, so +//! each hop goes through its own proxy; the log tells which proxy the +//! desktop names when that changes. At most [`PER_HOST`] downloads run per +//! host (a redirect's target counts), 16 in all: a host whose connections +//! stall does not hold them all. //! //! Banners in the server's own files (`ts3image://`) come through the voice //! connection instead ([`crate::files::server_image`]). +use std::collections::HashMap; +use std::future::Future; +use std::io::ErrorKind; use std::path::Path; -use std::sync::LazyLock; -use std::time::Duration; +use std::pin::Pin; +use std::sync::{Arc, LazyLock, Mutex, PoisonError, RwLock}; +use std::time::{Duration, SystemTime}; +use reqwest::header::{self, HeaderMap}; +use reqwest::{StatusCode, Url, Version}; use tokio::io::AsyncWriteExt; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; +use tracing::{debug, info}; -use crate::cache::{self, Cache, Fetch, Waiter}; +use crate::cache::{self, Arrived, Cache, Fetch, FetchError, RetryHint, Validators, Waiter}; -const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -const READ_TIMEOUT: Duration = Duration::from_secs(20); +const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); +const READ_TIMEOUT: Duration = Duration::from_secs(60); +/// Quiet time before keepalive probes, and between them. +const KEEPALIVE: Duration = Duration::from_secs(15); +/// Linux, Android: how long what was sent (keepalive probes too) may stay +/// unanswered before the kernel ends the connection. +#[cfg(any(target_os = "linux", target_os = "android"))] +const TCP_USER_TIMEOUT: Duration = Duration::from_secs(30); /// How long a download may start slowly before its rate counts. -const GRACE: Duration = Duration::from_secs(30); -/// The first bytes, enough to tell a picture from an error page. -const SNIFF: usize = 1024; +const GRACE: Duration = Duration::from_secs(120); +/// The first bytes, enough to tell a picture from an error page (SVG with +/// a comment or a DOCTYPE before it too). +const SNIFF: usize = 4096; /// The pictures the UI decodes, so a host choosing between formats /// (`Accept`) does not answer with one it cannot show (AVIF, JPEG XL). -const ACCEPT: &str = "image/png,image/jpeg,image/gif,image/webp,image/svg+xml;q=0.9,*/*;q=0.1"; +const ACCEPT: &str = "image/png,image/jpeg,image/gif,image/webp,image/svg+xml,image/bmp,\ + image/x-icon;q=0.9,*/*;q=0.1"; /// Fetch independent URLs in parallel without letting a large channel tree /// open unbounded connections or buffer unbounded image data. -static DOWNLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(8); +static DOWNLOADS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(16); +/// Downloads from one host (and port) at once, as browsers allow. +const PER_HOST: usize = 6; +/// Redirects followed, as many as a browser does. +const REDIRECTS: usize = 20; /// The host banner is reloaded at most this often, whatever the server /// asks (TeamSpeak 3 and 6 servers refuse intervals below a minute). pub(crate) const MIN_RELOAD: Duration = Duration::from_secs(60); +/// The shortest and the longest wait a busy host's `Retry-After` gets. +const RETRY_AFTER: (Duration, Duration) = (Duration::from_secs(60), Duration::from_secs(3600)); +/// Characters of an address in the log ([`loggable`]). +const LOGGED_URL: usize = 300; -static CLIENT: LazyLock> = LazyLock::new(|| { - reqwest::Client::builder() +/// Names the proxy for an address: see [`set_proxy_resolver`]. +type ProxyResolver = + Arc Pin> + Send>> + Send + Sync>; + +/// Have pictures go through the proxy `resolve` names for each address +/// (given as `scheme://host:port/`): an HTTP or SOCKS proxy's URL as +/// reqwest takes it (`http://host:port`, `socks5h://host:port`), or `None` +/// for the system's (environment variables; on Windows and macOS the +/// system settings). On Linux: the desktop's settings, +/// `voelin_platform::proxy::proxy_for`. A later call replaces it. +pub fn set_proxy_resolver(resolve: F) +where + F: Fn(String) -> R + Send + Sync + 'static, + R: Future> + Send + 'static, +{ + CLIENTS.set_resolver(Arc::new(move |origin| Box::pin(resolve(origin)))); +} + +static CLIENTS: LazyLock = LazyLock::new(|| Clients::new(READ_TIMEOUT)); + +/// The clients pictures are downloaded with: the system's, and one for +/// each proxy the resolver named. +struct Clients { + read_timeout: Duration, + resolver: RwLock>, + direct: Result, + proxied: Mutex>, + /// The proxy pictures from each origin went through last, for the log + /// (without its user and password); `None`: the system's. + routes: Mutex>>, +} + +impl Clients { + fn new(read_timeout: Duration) -> Self { + Self { + read_timeout, + resolver: RwLock::new(None), + direct: build_client(read_timeout, None), + proxied: Mutex::default(), + routes: Mutex::default(), + } + } + + fn set_resolver(&self, resolver: ProxyResolver) { + *self.resolver.write().unwrap_or_else(PoisonError::into_inner) = Some(resolver); + } + + /// The client for `url`, and the proxy it goes through. + async fn for_url(&self, url: &Url) -> Result<(reqwest::Client, Option), String> { + let resolver = self.resolver.read().unwrap_or_else(PoisonError::into_inner).clone(); + let origin = origin_of(url); + let proxy = match resolver { + Some(resolve) => resolve(origin.clone()).await, + None => None, + }; + let proxied = proxy.and_then(|proxy| self.proxied(proxy)); + self.note_route(&origin, proxied.as_ref().map(|(_, proxy)| proxy.as_str())); + match proxied { + Some((client, proxy)) => Ok((client, Some(proxy))), + None => self.direct.clone().map(|client| (client, None)), + } + } + + /// The client through `proxy`, and `proxy`; `None` if reqwest refuses + /// it. + fn proxied(&self, proxy: String) -> Option<(reqwest::Client, String)> { + let mut proxied = self.proxied.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(client) = proxied.get(&proxy) { + return Some((client.clone(), proxy)); + } + match build_client(self.read_timeout, Some(&proxy)) { + Ok(client) => { + proxied.insert(proxy.clone(), client.clone()); + Some((client, proxy)) + } + Err(error) => { + // Not one reqwest takes: as if there were none. + let proxy = without_credentials(&proxy); + debug!(%proxy, %error, "the desktop's proxy cannot be used for pictures"); + None + } + } + } + + /// Log which proxy pictures from `origin` go through when that changes: + /// once for each proxy the first time, then whenever an origin's + /// changes (a desktop's proxy turned on or off). The system's at first + /// is as without the desktop's settings: not told. + fn note_route(&self, origin: &str, proxy: Option<&str>) { + let proxy = proxy.map(without_credentials); + let mut routes = self.routes.lock().unwrap_or_else(PoisonError::into_inner); + let known = routes.values().any(|route| route.is_some() && *route == proxy); + match (routes.insert(origin.to_owned(), proxy.clone()), proxy) { + (Some(before), now) if before == now => {} + (None, None) => {} + (None, Some(proxy)) => { + if !known { + info!(%proxy, "pictures go through the desktop's proxy"); + } + } + (Some(_), Some(proxy)) => { + info!(%origin, %proxy, "pictures from this host go through the desktop's proxy now"); + } + (Some(_), None) => { + info!(%origin, "pictures from this host go without the desktop's proxy now"); + } + } + } +} + +/// A client, through `proxy` or the system's. +fn build_client(read_timeout: Duration, proxy: Option<&str>) -> Result { + let mut builder = reqwest::Client::builder() .connect_timeout(CONNECT_TIMEOUT) - .read_timeout(READ_TIMEOUT) - .user_agent(concat!("Voelin/", env!("CARGO_PKG_VERSION"))) - .build() - .map_err(|e| e.to_string()) -}); + .read_timeout(read_timeout) + .tcp_keepalive(KEEPALIVE) + .tcp_keepalive_interval(KEEPALIVE) + // Followed by `download`, each hop through its own proxy. + .redirect(reqwest::redirect::Policy::none()); + #[cfg(any(target_os = "linux", target_os = "android"))] + { + builder = builder.tcp_user_timeout(TCP_USER_TIMEOUT); + } + if let Some(proxy) = proxy { + builder = builder.proxy(reqwest::Proxy::all(proxy).map_err(|e| e.to_string())?); + } + builder.build().map_err(|e| e.to_string()) +} + +/// What a proxy is asked about: `url`'s scheme, host and port. +fn origin_of(url: &Url) -> String { + let host = url.host_str().unwrap_or_default(); + match url.port_or_known_default() { + Some(port) => format!("{}://{host}:{port}/", url.scheme()), + None => format!("{}://{host}/", url.scheme()), + } +} + +/// A proxy's URL for the log: without its user and password. +fn without_credentials(proxy: &str) -> String { + match Url::parse(proxy) { + Ok(url) => { + let port = url.port().map(|p| format!(":{p}")).unwrap_or_default(); + format!("{}://{}{port}", url.scheme(), url.host_str().unwrap_or("?")) + } + Err(_) => "?".to_owned(), + } +} + +/// What pictures are asked as: the app, and where to reach its makers (as +/// hosts such as Wikimedia ask). +fn user_agent() -> String { + user_agent_of(&voelin_platform::crash::app_version()) +} + +/// [`user_agent`] of the app's version `app` (none: this crate's). +fn user_agent_of(app: &str) -> String { + let version = if app.is_empty() { env!("CARGO_PKG_VERSION") } else { app }; + format!("Voelin/{version} (+https://github.com/Faumaray/Voelin)") +} + +/// The hosts with downloads running or waiting, [`PER_HOST`] slots each. +static HOSTS: LazyLock>>> = LazyLock::new(Mutex::default); + +/// One of a host's [`PER_HOST`] download slots. +struct HostSlot { + host: String, + permit: Option, +} + +impl HostSlot { + async fn acquire(host: String) -> Self { + let slots = HOSTS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(host.clone()) + .or_insert_with(|| Arc::new(Semaphore::new(PER_HOST))) + .clone(); + let permit = slots.acquire_owned().await.expect("host slots stay open"); + Self { host, permit: Some(permit) } + } +} + +impl Drop for HostSlot { + fn drop(&mut self) { + let Some(permit) = self.permit.take() else { return }; + let slots = permit.semaphore().clone(); + drop(permit); + let mut hosts = HOSTS.lock().unwrap_or_else(PoisonError::into_inner); + // The map's and this one: no other download runs or waits. + if Arc::strong_count(&slots) == 2 + && hosts.get(&self.host).is_some_and(|s| Arc::ptr_eq(s, &slots)) + { + hosts.remove(&self.host); + } + } +} + +/// A download's turn to ask a host: one of its slots, then one of the 16 +/// (the slot first: waiting for it holds none of the others). +struct Turn { + _permit: tokio::sync::SemaphorePermit<'static>, + slot: HostSlot, +} + +impl Turn { + async fn take(host: String) -> Self { + let slot = HostSlot::acquire(host).await; + let permit = DOWNLOADS.acquire().await.expect("download semaphore stays open"); + Self { _permit: permit, slot } + } +} /// Get the picture at `url` into `cache`, downloading it once however many -/// ask (again with `fresh`: it changes at its address); `waiter` is told -/// where it is. `max_cache_bytes`: `cache.max_mb` in bytes. +/// ask (again with `fresh`: it changes at its address, so its host is +/// asked whether it did); `waiter` is told where it is. +/// `max_cache_bytes`: `cache.max_mb` in bytes. pub(crate) fn fetch(cache: Cache, url: &str, fresh: bool, max_cache_bytes: u64, waiter: Waiter) { + fetch_within(cache, url, fresh, max_cache_bytes, LIMITS, waiter); +} + +/// [`fetch`] a myTeamSpeak avatar: a picture of at most +/// [`AVATAR_LIMITS`]'s size, once (its link changes with it). +pub(crate) fn fetch_avatar(cache: Cache, url: &str, max_cache_bytes: u64, waiter: Waiter) { + fetch_within(cache, url, false, max_cache_bytes, AVATAR_LIMITS, waiter); +} + +/// [`fetch`] a picture a chat message shows: one of at most `max_bytes` +/// (up to [`cache::MAX_PICTURE_BYTES`]), once. +pub(crate) fn fetch_chat_picture( + cache: Cache, + url: &str, + max_cache_bytes: u64, + max_bytes: u64, + waiter: Waiter, +) { + let limits = Limits { max_bytes: max_bytes.min(LIMITS.max_bytes), ..LIMITS }; + fetch_within(cache, url, false, max_cache_bytes, limits, waiter); +} + +fn fetch_within( + cache: Cache, + url: &str, + fresh: bool, + max_cache_bytes: u64, + limits: Limits, + waiter: Waiter, +) { let Some(key) = cache::picture_key(url) else { waiter(Err("not an http or https address".into())); return; }; let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return }; - let url = url.to_owned(); + // Asked for again: downloaded only if it changed. + let validators = if fresh { cache.validators(&key) } else { None }; + let url = url.trim().to_owned(); tokio::spawn(async move { - let _permit = DOWNLOADS.acquire().await.expect("download semaphore stays open"); - let result = download(&url, &temp, &LIMITS).await; - cache.finish(&key, &temp, result, max_cache_bytes); + let result = download(&url, &temp, &limits, validators.as_ref()).await; + cache.finish_with(&key, &temp, result, max_cache_bytes); }); } @@ -77,22 +368,88 @@ struct Limits { const LIMITS: Limits = Limits { max_bytes: cache::MAX_PICTURE_BYTES, grace: GRACE, min_rate: cache::MIN_PICTURE_RATE }; +/// Avatars are small pictures (as myTeamSpeak's own, 4 MiB at most). +const AVATAR_LIMITS: Limits = Limits { max_bytes: 4 << 20, ..LIMITS }; /// Download the picture at `url` into `to` within `limits`, and only if it -/// is a picture (what arrived stays in `to` on failure; the cache removes it). -async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> { - let client = CLIENT.as_ref().map_err(Clone::clone)?; - let too_big = || format!("larger than {} KiB", limits.max_bytes >> 10); - let mut response = client - .get(url) - .header(reqwest::header::ACCEPT, ACCEPT) - .send() - .await - .and_then(reqwest::Response::error_for_status) - .map_err(|e| e.to_string())?; +/// is a picture (what arrived stays in `to` on failure; the cache removes +/// it). With the cached copy's `validators`, only if it changed. Each host +/// asked (a redirect's too) is asked in its [`Turn`]. +async fn download( + url: &str, + to: &Path, + limits: &Limits, + validators: Option<&Validators>, +) -> Result { + download_with(&CLIENTS, url, to, limits, validators).await +} + +async fn download_with( + clients: &Clients, + url: &str, + to: &Path, + limits: &Limits, + validators: Option<&Validators>, +) -> Result { + let mut url = Url::parse(url) + .map_err(|e| FetchError::new(format!("not a web address ({e})"), RetryHint::Permanent))?; + let user_agent = user_agent(); + let mut hops = 0; + let mut turn: Option = None; + let (mut response, proxy, sent) = loop { + if !matches!(url.scheme(), "http" | "https") { + let text = "redirected to an address not on the web"; + return Err(FetchError::new(text, RetryHint::Permanent)); + } + let host = host_and_port(&url); + if turn.as_ref().is_none_or(|turn| turn.slot.host != host) { + // Another host: the last one's turn ends before waiting. + drop(turn.take()); + turn = Some(Turn::take(host).await); + } + let (client, proxy) = clients.for_url(&url).await?; + let mut request = client + .get(url.clone()) + .header(header::ACCEPT, ACCEPT) + .header(header::USER_AGENT, &user_agent); + if let Some(validators) = validators { + if let Some(etag) = &validators.etag { + request = request.header(header::IF_NONE_MATCH, etag); + } + if let Some(date) = &validators.last_modified { + request = request.header(header::IF_MODIFIED_SINCE, date); + } + } + let sent = tokio::time::Instant::now(); + let response = match request.send().await { + Ok(response) => response, + Err(e) => { + return Err(through(request_failed(e, clients.read_timeout), proxy.as_deref())); + } + }; + match redirect(&response, &url) { + Some(_) if hops == REDIRECTS => return Err("too many redirects".into()), + Some(next) => { + hops += 1; + url = next; + } + None => break (response, proxy, sent), + } + }; + let status = response.status(); + if status == StatusCode::NOT_MODIFIED && validators.is_some() { + return Ok(Arrived::Unchanged); + } + if !status.is_success() { + let error = status_error(status, response.headers(), SystemTime::now()); + return Err(through(error, proxy.as_deref())); + } + let too_big = || FetchError::from(format!("larger than {} KiB", limits.max_bytes >> 10)); if response.content_length().is_some_and(|n| n > limits.max_bytes) { return Err(too_big()); } + let version = response.version(); + let arrived = Arrived::File(validators_of(response.headers())); if let Some(dir) = to.parent() { tokio::fs::create_dir_all(dir).await.map_err(|e| e.to_string())?; } @@ -100,7 +457,15 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> { let started = tokio::time::Instant::now(); let mut head = Vec::with_capacity(SNIFF); let mut received = 0u64; - while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? { + loop { + let chunk = match response.chunk().await { + Ok(Some(chunk)) => chunk, + Ok(None) => break, + Err(e) => { + let failed = body_failed(e, received, version, sent.elapsed()); + return Err(through(failed, proxy.as_deref())); + } + }; received += chunk.len() as u64; if received > limits.max_bytes { return Err(too_big()); @@ -109,53 +474,366 @@ async fn download(url: &str, to: &Path, limits: &Limits) -> Result<(), String> { head.extend_from_slice(&chunk[..chunk.len().min(SNIFF - head.len())]); // An error page is refused without waiting for all of it. if head.len() == SNIFF && !is_picture(&head) { - return Err("not a picture".into()); + return Err(not_a_picture(&head).into()); } } let elapsed = started.elapsed(); let expected = limits.min_rate.saturating_mul(elapsed.as_millis() as u64) / 1000; if elapsed > limits.grace && received < expected { - return Err(format!("too slow: {} KiB in {} s", received >> 10, elapsed.as_secs())); + return Err( + format!("too slow: {} KiB in {} s", received >> 10, elapsed.as_secs()).into() + ); } file.write_all(&chunk).await.map_err(|e| e.to_string())?; } file.flush().await.map_err(|e| e.to_string())?; drop(file); if !is_picture(&head) { - return Err("not a picture".into()); + return Err(not_a_picture(&head).into()); } - Ok(()) + Ok(arrived) +} + +/// Where `response` redirects to (from `url`), if it is a redirect. +fn redirect(response: &reqwest::Response, url: &Url) -> Option { + use StatusCode as S; + let status = response.status(); + let redirects = [ + S::MOVED_PERMANENTLY, + S::FOUND, + S::SEE_OTHER, + S::TEMPORARY_REDIRECT, + S::PERMANENT_REDIRECT, + ]; + if !redirects.contains(&status) { + return None; + } + let location = response.headers().get(header::LOCATION)?; + url.join(std::str::from_utf8(location.as_bytes()).ok()?).ok() +} + +/// What identifies the version of a picture, as its host sent it. +fn validators_of(headers: &HeaderMap) -> Validators { + let value = |name| { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|v| !v.is_empty() && v.len() <= 512) + .map(str::to_owned) + }; + Validators { etag: value(header::ETAG), last_modified: value(header::LAST_MODIFIED) } +} + +/// A host's refusal, with when to ask again: not soon for an address that +/// is wrong or gone, when the host says for one too busy. +fn status_error(status: StatusCode, headers: &HeaderMap, now: SystemTime) -> FetchError { + let retry = match status { + StatusCode::BAD_REQUEST | StatusCode::NOT_FOUND | StatusCode::GONE => RetryHint::Permanent, + StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => { + match retry_after(headers, now) { + Some(wait) => RetryHint::After(wait.clamp(RETRY_AFTER.0, RETRY_AFTER.1)), + // Too many: not at once again, whatever it says. + None if status == StatusCode::TOO_MANY_REQUESTS => RetryHint::After(RETRY_AFTER.0), + None => RetryHint::Default, + } + } + _ => RetryHint::Default, + }; + FetchError::new(format!("HTTP {status}"), retry) +} + +/// How long a host asks to wait (`Retry-After`: seconds, or a date). +fn retry_after(headers: &HeaderMap, now: SystemTime) -> Option { + let value = headers.get(header::RETRY_AFTER)?.to_str().ok()?.trim(); + if let Ok(seconds) = value.parse::() { + return Some(Duration::from_secs(seconds)); + } + let at = httpdate::parse_http_date(value).ok()?; + Some(at.duration_since(now).unwrap_or_default()) +} + +/// `error`, saying the request went through `proxy`. +fn through(mut error: FetchError, proxy: Option<&str>) -> FetchError { + if let Some(proxy) = proxy { + error.text = format!("{} (through the proxy {})", error.text, without_credentials(proxy)); + } + error +} + +/// Why a request got no answer: a connection not made, one that stalled, +/// or another reason (TLS, DNS, …). +fn request_failed(error: reqwest::Error, read_timeout: Duration) -> FetchError { + let error = error.without_url(); + if error.is_connect() { + if error.is_timeout() { + return format!("could not connect within {} s", CONNECT_TIMEOUT.as_secs()).into(); + } + return describe(error).into(); + } + match stall(&error) { + // HTTP/2 carries a host's downloads on one connection: others on it + // may have received data before it stopped. + Some(Stall::Http2) => { + return "the connection stalled before the answer began (HTTP/2; other downloads on \ + the same connection may have received data): the network stopped delivering data" + .into(); + } + Some(Stall::Own) => { + return "the connection stalled before the answer began: the network stopped \ + delivering data" + .into(); + } + None => {} + } + if error.is_timeout() { + // Where the kernel does not end a stalled connection (Windows, + // macOS), it ends here too. + let secs = read_timeout.as_secs(); + return format!( + "no answer within {secs} s: the host is slow, or the network stopped delivering data" + ) + .into(); + } + describe(error).into() +} + +/// Why a picture stopped arriving after `received` bytes, `elapsed` after +/// it was asked for (where a redirect led). +fn body_failed( + error: reqwest::Error, + received: u64, + version: Version, + elapsed: Duration, +) -> FetchError { + let error = error.without_url(); + if stall(&error).is_none() && !error.is_timeout() { + return describe(error).into(); + } + let amount = if received < 1024 { + format!("{received} bytes") + } else { + format!("{} KiB", received >> 10) + }; + let version = match version { + Version::HTTP_09 => "HTTP/0.9", + Version::HTTP_10 => "HTTP/1.0", + Version::HTTP_11 => "HTTP/1.1", + // What arrived is this download's: the connection carries the + // host's others too. + Version::HTTP_2 => "HTTP/2; other downloads on the same connection may have received more", + Version::HTTP_3 => "HTTP/3", + _ => "HTTP", + }; + let secs = elapsed.as_secs(); + format!( + "the connection stalled after {amount} in {secs} s ({version}): the network stopped \ + delivering data" + ) + .into() +} + +/// A connection that ended because its data stopped ([`stall`]). +#[derive(Clone, Copy, Debug, PartialEq)] +enum Stall { + /// HTTP/2's, which carries other downloads from the host too. + Http2, + /// One this download had to itself. + Own, +} + +/// Whether `error` is a connection the kernel ended because its data +/// stopped: an I/O "timed out" among its causes. HTTP/2 keeps only the +/// kind of that error: in an `h2::Error` that names no cause, or rebuilt +/// from the kind (no OS error code), where a connection of its own keeps +/// the kernel's (`ETIMEDOUT`); with another h2 than hyper's, only its +/// text tells. +fn stall(error: &(dyn std::error::Error + 'static)) -> Option { + let mut last = error; + let mut cause = Some(error); + while let Some(error) = cause { + if let Some(io) = error.downcast_ref::().and_then(h2::Error::get_io) + && io.kind() == ErrorKind::TimedOut + { + return Some(Stall::Http2); + } + if let Some(io) = error.downcast_ref::() + && io.kind() == ErrorKind::TimedOut + { + return Some(if io.raw_os_error().is_some() { Stall::Own } else { Stall::Http2 }); + } + last = error; + cause = error.source(); + } + (last.to_string() == "timed out").then_some(Stall::Http2) +} + +/// What went wrong, for the log: the whole chain of causes (a TLS, DNS or +/// timeout reason); never the address (see [`loggable`]). +fn describe(error: reqwest::Error) -> String { + let error = error.without_url(); + let mut text = if error.is_timeout() { + "timed out".to_owned() + } else if error.is_connect() { + "could not connect".to_owned() + } else { + error.to_string() + }; + let mut source = std::error::Error::source(&error); + while let Some(cause) = source { + text.push_str(": "); + text.push_str(&cause.to_string()); + source = cause.source(); + } + text +} + +/// What arrived instead of a picture, for the log. +fn not_a_picture(head: &[u8]) -> String { + let start = head.trim_ascii_start(); + let lower = + start.get(..15.min(start.len())).map(<[u8]>::to_ascii_lowercase).unwrap_or_default(); + let what = if lower.starts_with(b"= 12 && &head[4..8] == b"ftyp" { + // ISO media, told by its brand. + match &head[8..12] { + b"avif" | b"avis" | b"heic" | b"heix" | b"heim" | b"heis" | b"hevc" | b"hevx" + | b"mif1" | b"msf1" => "AVIF or HEIF, which cannot be shown", + _ => "a video (MP4, MOV), which cannot be shown", + } + } else if start.starts_with(b"{") { + "JSON" + } else { + "something else" + }; + format!("not a picture ({what})") +} + +/// The host of `url`, for the log; the scheme for one without (a server +/// file, `ts3image://`). +pub(crate) fn host_of(url: &str) -> String { + match reqwest::Url::parse(url.trim()) { + Ok(u) if matches!(u.scheme(), "http" | "https") => u.host_str().unwrap_or("?").to_owned(), + Ok(u) => u.scheme().to_owned(), + Err(_) => "?".to_owned(), + } +} + +/// `url` for the log: `scheme://host[:port]/path`, without a user and +/// password, the query or the fragment (where signed links keep their +/// secrets), cut at [`LOGGED_URL`] characters; the scheme alone for an +/// address not on the web. +pub(crate) fn loggable(url: &str) -> String { + let url = match reqwest::Url::parse(url.trim()) { + Ok(u) if matches!(u.scheme(), "http" | "https") => u, + Ok(u) => return u.scheme().to_owned(), + Err(_) => return "?".to_owned(), + }; + let port = url.port().map(|p| format!(":{p}")).unwrap_or_default(); + let mut text = + format!("{}://{}{port}{}", url.scheme(), url.host_str().unwrap_or("?"), url.path()); + if let Some((at, _)) = text.char_indices().nth(LOGGED_URL) { + text.truncate(at); + text.push('…'); + } + text +} + +/// Which host's slots a download takes: `url`'s host and port. +fn host_and_port(url: &Url) -> String { + format!("{}:{}", url.host_str().unwrap_or("?"), url.port_or_known_default().unwrap_or(0)) } /// Whether `data` is a picture the UI decodes, told by its content as the -/// UI tells it (SVG by its start, without leading blanks). +/// UI tells it (SVG by [`is_svg`]). fn is_picture(data: &[u8]) -> bool { - const STARTS: [&[u8]; 4] = [b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a"]; - let xml = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data).trim_ascii_start(); + const STARTS: [&[u8]; 6] = [ + b"\x89PNG\r\n\x1a\n", + b"\xff\xd8\xff", + b"GIF87a", + b"GIF89a", + b"BM", + // ICO. + b"\0\0\x01\0", + ]; STARTS.iter().any(|s| data.starts_with(s)) - || xml.starts_with(b"= 12 && data.starts_with(b"RIFF") && &data[8..12] == b"WEBP") + || is_svg(data) +} + +/// Whether `data` starts an SVG document: after a BOM and the prolog (the +/// XML declaration and other processing instructions, comments, blanks), +/// a DOCTYPE `svg` or an `svg` element. A page with an `svg` in it (an +/// HTML page, XHTML too) is not; nor is a start cut off before it tells. +pub fn is_svg(data: &[u8]) -> bool { + let mut rest = data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data); + loop { + rest = rest.trim_ascii_start(); + let (skipped, end) = if let Some(pi) = rest.strip_prefix(b"".as_slice()) + } else if let Some(comment) = rest.strip_prefix(b"".as_slice()) + } else if rest.get(..9).is_some_and(|s| s.eq_ignore_ascii_case(b"' | b'[')); + } else if let Some(element) = rest.strip_prefix(b"<") { + return names_svg(element); + } else { + return false; + }; + let Some(at) = skipped.windows(end.len()).position(|w| w == end) else { + return false; + }; + rest = &skipped[at + end.len()..]; + } +} + +/// Whether the element named at the start of `tag` is `svg`, with a +/// namespace prefix or without. +fn names_svg(tag: &[u8]) -> bool { + let Some(len) = tag.iter().position(|b| b.is_ascii_whitespace() || matches!(b, b'>' | b'/')) + else { + return false; + }; + let name = &tag[..len]; + name == b"svg" || name.ends_with(b":svg") } #[cfg(test)] -mod tests { +pub(crate) mod tests { use std::sync::mpsc; use tokio::io::{AsyncReadExt, AsyncWriteExt}; - use tokio::net::TcpListener; + use tokio::net::{TcpListener, TcpStream}; + use tokio::sync::mpsc as async_mpsc; use super::*; const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x01\0\0\0\x01\x08\x06\0\0\0\x1f\x15\xc4\x89\0\0\0\rIDATx\xdac\xf8\xcf\xc0\xf0\x1f\0\x05\0\x01\xff\x89\x99=\x1d\0\0\0\0IEND\xaeB`\x82"; + /// The heads of the requests a test server got. + type Requests = Arc>>; + /// An HTTP server on 127.0.0.1 with a few answers; returns its address. async fn server() -> String { + logged_server().await.0 + } + + /// [`server`], and the requests it gets. + async fn logged_server() -> (String, Requests) { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); + let requests = Requests::default(); + let log = requests.clone(); tokio::spawn(async move { loop { let Ok((mut socket, _)) = listener.accept().await else { return }; + let log = log.clone(); tokio::spawn(async move { let mut request = Vec::new(); let mut buf = [0u8; 1024]; @@ -165,11 +843,10 @@ mod tests { Ok(n) => request.extend_from_slice(&buf[..n]), } } - let path = String::from_utf8_lossy(&request) - .split_whitespace() - .nth(1) - .unwrap_or("/") - .to_owned(); + let request = String::from_utf8_lossy(&request).into_owned(); + log.lock().unwrap().push(request.clone()); + let path = request.split_whitespace().nth(1).unwrap_or("/").to_owned(); + let mut extra = String::new(); let (status, length, body): (&str, bool, Vec) = match path.as_str() { "/banner" => ("200 OK", true, PNG.to_vec()), "/svg" => { @@ -181,15 +858,73 @@ mod tests { "/big" => ("200 OK", true, [PNG, &[0; 4000]].concat()), "/big-unannounced" => ("200 OK", false, [PNG, &[0; 4000]].concat()), "/page" => ("200 OK", true, b"".to_vec()), - "/long-page" => { - ("200 OK", false, [b"", &[b' '; 4000][..]].concat()) - } + "/long-page" | "/endless-page" => ( + "200 OK", + false, + [b"".as_slice(), &vec![b' '; SNIFF]].concat(), + ), // A picture, then a byte every 100 ms. "/slow" => ("200 OK", true, [PNG, &[0; 20]].concat()), + "/bad" => ("400 Bad Request", true, b"no".to_vec()), + "/gone" => ("410 Gone", true, b"no".to_vec()), + "/busy" => { + extra = "Retry-After: 120\r\n".into(); + ("429 Too Many Requests", true, b"later".to_vec()) + } + "/busy-for-a-day" => { + let date = httpdate::fmt_http_date(SystemTime::now() + 86400 * SECOND); + extra = format!("Retry-After: {date}\r\n"); + ("503 Service Unavailable", true, b"later".to_vec()) + } + "/busy-a-moment" => { + extra = "Retry-After: 1\r\n".into(); + ("503 Service Unavailable", true, b"later".to_vec()) + } + "/down" => ("503 Service Unavailable", true, b"later".to_vec()), + // No answer at all. + "/silent" => { + tokio::time::sleep(Duration::from_secs(30)).await; + return; + } + // Headers and 16 KiB of a megabyte, then nothing (the + // network drops the rest). + "/stall" => { + ("200 OK", false, [PNG, &vec![0; (16 << 10) - PNG.len()]].concat()) + } + // Validators, and 304 to who has this version. + "/versioned" + if request.to_ascii_lowercase().contains("if-none-match: \"v1\"") => + { + ("304 Not Modified", false, Vec::new()) + } + "/versioned" => { + extra = + "ETag: \"v1\"\r\nLast-Modified: Tue, 06 Oct 2026 10:00:00 GMT\r\n" + .into(); + ("200 OK", true, PNG.to_vec()) + } + "/redirect" => { + extra = "Location: /banner\r\n".into(); + ("302 Found", true, Vec::new()) + } + "/loop" => { + extra = "Location: /loop\r\n".into(); + ("301 Moved Permanently", true, Vec::new()) + } + "/elsewhere" => { + extra = "Location: file:///etc/hostname\r\n".into(); + ("307 Temporary Redirect", true, Vec::new()) + } + p if p.starts_with("/to?") => { + extra = format!("Location: {}\r\n", &p[4..]); + ("302 Found", true, Vec::new()) + } _ => ("404 Not Found", true, b"no".to_vec()), }; - let mut head = format!("HTTP/1.1 {status}\r\nConnection: close\r\n"); - if length { + let mut head = format!("HTTP/1.1 {status}\r\nConnection: close\r\n{extra}"); + if path == "/stall" { + head += &format!("Content-Length: {}\r\n", 1 << 20); + } else if length { head += &format!("Content-Length: {}\r\n", body.len()); } head += "\r\n"; @@ -206,10 +941,61 @@ mod tests { return; } let _ = socket.write_all(&body).await; + // Never done: refused by its start or not at all. + if path == "/endless-page" { + while socket.write_all(b" ").await.is_ok() { + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + if path == "/stall" { + tokio::time::sleep(Duration::from_secs(30)).await; + } }); } }); - format!("http://{addr}") + (format!("http://{addr}"), requests) + } + + const SECOND: Duration = Duration::from_secs(1); + + /// What `f` logs at info (and above) on this thread: each line its + /// message, then its fields (` name=value`). + pub(crate) fn info_lines(f: impl FnOnce() -> T) -> (T, Vec) { + use tracing::field::{Field, Visit}; + use tracing::span; + + struct Lines(Arc>>); + #[derive(Default)] + struct Line(String, String); + impl Visit for Line { + fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { + match field.name() { + "message" => self.0 = format!("{value:?}"), + name => self.1 += &format!(" {name}={value:?}"), + } + } + } + impl tracing::Subscriber for Lines { + fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { + *metadata.level() <= tracing::Level::INFO + } + fn new_span(&self, _: &span::Attributes<'_>) -> span::Id { + span::Id::from_u64(1) + } + fn record(&self, _: &span::Id, _: &span::Record<'_>) {} + fn record_follows_from(&self, _: &span::Id, _: &span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + let mut line = Line::default(); + event.record(&mut line); + self.0.lock().unwrap().push(line.0 + &line.1); + } + fn enter(&self, _: &span::Id) {} + fn exit(&self, _: &span::Id) {} + } + let lines = Arc::new(Mutex::new(Vec::new())); + let result = tracing::subscriber::with_default(Lines(lines.clone()), f); + let lines = lines.lock().unwrap().clone(); + (result, lines) } fn temp_dir(tag: &str) -> std::path::PathBuf { @@ -224,27 +1010,218 @@ mod tests { let dir = temp_dir("download"); let to = dir.join("tmp/x.part"); let limits = Limits { max_bytes: 1000, ..LIMITS }; - download(&format!("{base}/banner"), &to, &limits).await.unwrap(); + let fresh = Arrived::File(Validators::default()); + assert_eq!(download(&format!("{base}/banner"), &to, &limits, None).await, Ok(fresh)); assert_eq!(std::fs::read(&to).unwrap(), PNG); - download(&format!("{base}/svg"), &to, &limits).await.unwrap(); + download(&format!("{base}/svg"), &to, &limits, None).await.unwrap(); for (path, error) in [ ("/big", "larger than"), ("/big-unannounced", "larger than"), ("/page", "not a picture"), ("/missing", "404"), ] { - let e = download(&format!("{base}{path}"), &to, &limits).await.unwrap_err(); - assert!(e.contains(error), "{path}: {e}"); + let e = download(&format!("{base}{path}"), &to, &limits, None).await.unwrap_err(); + assert!(e.text.contains(error), "{path}: {e}"); + } + // An error page longer than the first bytes looked at, unannounced: + // refused by them, without waiting for the rest. + for path in ["/long-page", "/endless-page"] { + let url = format!("{base}{path}"); + let fetch = download(&url, &to, &LIMITS, None); + let e = tokio::time::timeout(5 * SECOND, fetch).await.unwrap().unwrap_err(); + assert!(e.text.contains("not a picture (an HTML page)"), "{path}: {e}"); } - // An error page longer than the first bytes looked at, unannounced. - let e = download(&format!("{base}/long-page"), &to, &LIMITS).await.unwrap_err(); - assert!(e.contains("not a picture"), "{e}"); // Nothing listens there. let port = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port(); - assert!(download(&format!("http://127.0.0.1:{port}/b"), &to, &limits).await.is_err()); + let e = download(&format!("http://127.0.0.1:{port}/b"), &to, &limits, None).await; + assert!(e.unwrap_err().text.starts_with("could not connect")); std::fs::remove_dir_all(dir).unwrap(); } + /// An address wrong or gone is not tried again soon; a busy host is + /// waited for as long as it asks, within reason. + #[tokio::test] + async fn failures_tell_when_to_try_again() { + let base = server().await; + let dir = temp_dir("hints"); + let to = dir.join("x"); + let minute = RetryHint::After(60 * SECOND); + for (path, retry) in [ + ("/missing", RetryHint::Permanent), + ("/bad", RetryHint::Permanent), + ("/gone", RetryHint::Permanent), + ("/busy", RetryHint::After(120 * SECOND)), + ("/busy-for-a-day", RetryHint::After(3600 * SECOND)), + ("/busy-a-moment", minute), + ("/down", RetryHint::Default), + ("/page", RetryHint::Default), + ] { + let e = download(&format!("{base}{path}"), &to, &LIMITS, None).await.unwrap_err(); + assert_eq!(e.retry, retry, "{path}: {e}"); + } + let e = download(&format!("{base}/missing"), &to, &LIMITS, None).await.unwrap_err(); + assert_eq!(e.text, "HTTP 404 Not Found"); + let mut headers = HeaderMap::new(); + let now = SystemTime::now(); + assert_eq!(retry_after(&headers, now), None); + headers.insert( + header::RETRY_AFTER, + httpdate::fmt_http_date(now + 600 * SECOND).parse().unwrap(), + ); + assert!(retry_after(&headers, now).is_some_and(|d| d.abs_diff(600 * SECOND) <= SECOND)); + headers.insert( + header::RETRY_AFTER, + httpdate::fmt_http_date(now - 600 * SECOND).parse().unwrap(), + ); + assert_eq!(retry_after(&headers, now), Some(Duration::ZERO)); + headers.insert(header::RETRY_AFTER, "soon".parse().unwrap()); + assert_eq!(retry_after(&headers, now), None); + // Without Retry-After: too many requests are not repeated at once. + let e = status_error(StatusCode::TOO_MANY_REQUESTS, &HeaderMap::new(), now); + assert_eq!(e.retry, minute); + let _ = std::fs::remove_dir_all(dir); + } + + /// The network stops delivering mid-picture: named a stall, with what + /// arrived, not a bare "timed out". Before the answer began it may be a + /// slow host too. + #[tokio::test] + async fn a_stalled_download_is_named() { + let base = server().await; + let dir = temp_dir("stall"); + let clients = Clients::new(SECOND); + let (url, to) = (format!("{base}/stall"), dir.join("x")); + let fetch = download_with(&clients, &url, &to, &LIMITS, None); + let e = tokio::time::timeout(10 * SECOND, fetch).await.unwrap().unwrap_err(); + let rest = e.text.strip_prefix("the connection stalled after 16 KiB in "); + let (secs, rest) = rest.and_then(|r| r.split_once(' ')).expect(&e.text); + // The test's read timeout, and what a busy machine adds. + assert!((1..=5).contains(&secs.parse::().unwrap()), "{e}"); + assert_eq!(rest, "s (HTTP/1.1): the network stopped delivering data"); + assert_eq!(e.retry, RetryHint::Default); + let url = format!("{base}/silent"); + let fetch = download_with(&clients, &url, &to, &LIMITS, None); + let e = tokio::time::timeout(10 * SECOND, fetch).await.unwrap().unwrap_err(); + assert_eq!( + e.text, + "no answer within 1 s: the host is slow, or the network stopped delivering data" + ); + let _ = std::fs::remove_dir_all(dir); + } + + /// A plain I/O error. + #[derive(Debug)] + struct Cause(&'static str, Option>); + + impl std::fmt::Display for Cause { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.0) + } + } + + impl std::error::Error for Cause { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1.as_deref().map(|e| e as _) + } + } + + /// A stream that fails its reads with "timed out" once told, as a + /// socket does when the kernel gives up on its connection. + struct Stalling { + inner: tokio::io::DuplexStream, + stalled: Arc, + } + + impl tokio::io::AsyncRead for Stalling { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + if self.stalled.load(std::sync::atomic::Ordering::SeqCst) { + return std::task::Poll::Ready(Err(ErrorKind::TimedOut.into())); + } + Pin::new(&mut self.inner).poll_read(cx, buf) + } + } + + impl tokio::io::AsyncWrite for Stalling { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + Pin::new(&mut self.inner).poll_write(cx, buf) + } + + fn poll_flush( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } + } + + /// HTTP/2 ended by the kernel's timeout mid-body: its `h2::Error` names + /// no cause and keeps only the kind, yet it is a stall. So is any chain + /// that ends in that text (another h2 version), and an I/O timeout. + #[tokio::test] + async fn stalls_are_told_by_their_causes() { + use std::sync::atomic::{AtomicBool, Ordering}; + + let (client_io, server_io) = tokio::io::duplex(1 << 16); + let stalled = Arc::new(AtomicBool::new(false)); + let client_io = Stalling { inner: client_io, stalled: stalled.clone() }; + let (streams, mut stream) = async_mpsc::unbounded_channel(); + tokio::spawn(async move { + let mut connection = h2::server::handshake(server_io).await.unwrap(); + while let Some(Ok((_, mut respond))) = connection.accept().await { + let mut body = respond.send_response(http::Response::new(()), false).unwrap(); + body.send_data(bytes::Bytes::from_static(&[0; 100]), false).unwrap(); + let _ = streams.send(body); + } + }); + let (send, connection) = h2::client::handshake(client_io).await.unwrap(); + tokio::spawn(connection); + let mut send = send.ready().await.unwrap(); + let request = http::Request::get("https://h.test/b.png").body(()).unwrap(); + let (response, _) = send.send_request(request, true).unwrap(); + let mut body = response.await.unwrap().into_body(); + assert_eq!(body.data().await.unwrap().unwrap().len(), 100); + // The network stops: the next read fails. + stalled.store(true, Ordering::SeqCst); + let mut more = stream.recv().await.unwrap(); + more.send_data(bytes::Bytes::from_static(&[0; 100]), false).unwrap(); + let error = + tokio::time::timeout(5 * SECOND, body.data()).await.unwrap().unwrap().unwrap_err(); + assert_eq!(error.to_string(), "timed out"); + assert!(std::error::Error::source(&error).is_none()); + let body = Cause("error reading a body from connection", Some(Box::new(error))); + assert_eq!(stall(&body), Some(Stall::Http2)); + // Before the answer, hyper rebuilds HTTP/2's error from its kind. + let rebuilt = std::io::Error::from(ErrorKind::TimedOut); + let request = Cause("client error (SendRequest)", Some(Box::new(rebuilt))); + assert_eq!(stall(&request), Some(Stall::Http2)); + // Another h2 than hyper's: told by the text. + let text = Cause("body", Some(Box::new(Cause("timed out", None)))); + assert_eq!(stall(&text), Some(Stall::Http2)); + // A connection of its own keeps the kernel's error. + let os = std::io::Error::from_raw_os_error(110); + if os.kind() == ErrorKind::TimedOut { + let request = Cause("client error (SendRequest)", Some(Box::new(os))); + assert_eq!(stall(&request), Some(Stall::Own)); + } + assert_eq!(stall(&Cause("connection reset", None)), None); + assert_eq!(stall(&Cause("tls", Some(Box::new(Cause("operation timed out", None))))), None); + } + #[tokio::test(flavor = "multi_thread")] async fn fetch_into_the_cache() { let base = server().await; @@ -263,21 +1240,209 @@ mod tests { // Not on the web: refused at once, nothing cached. let (tx, rx) = mpsc::channel(); fetch(cache.clone(), "file:///etc/hostname", false, 0, waiter(&tx)); - assert!(rx.recv().unwrap().unwrap_err().contains("http")); + assert!(rx.recv().unwrap().unwrap_err().text.contains("http")); // A failed download is reported and leaves nothing behind. fetch(cache.clone(), &format!("{base}/page"), false, 0, waiter(&tx)); let failed = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap(); - assert_eq!(failed, Err("not a picture".into())); + assert_eq!(failed, Err("not a picture (an HTML page)".into())); + // So does one larger than asked for (a chat picture). + let (tx, rx) = mpsc::channel(); + fetch_chat_picture(cache.clone(), &format!("{base}/big"), 0, 1000, waiter(&tx)); + let failed = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap(); + assert!(failed.unwrap_err().text.contains("larger")); assert_eq!(cache.size(), PNG.len() as u64); std::fs::remove_dir_all(dir).unwrap(); } + /// Fetched again, a cached picture is asked for with its validators and + /// kept as it is when its host says it did not change. + #[tokio::test(flavor = "multi_thread")] + async fn a_cached_picture_is_downloaded_again_only_if_it_changed() { + let (base, requests) = logged_server().await; + let dir = temp_dir("revalidate"); + let cache = Cache::new(&dir); + let url = format!("{base}/versioned"); + let key = cache::picture_key(&url).unwrap(); + let get = |fresh| { + let (tx, rx) = mpsc::channel(); + fetch(cache.clone(), &url, fresh, 0, Box::new(move |r| tx.send(r).unwrap())); + tokio::task::spawn_blocking(move || rx.recv().unwrap()) + }; + let path = get(false).await.unwrap().unwrap(); + assert_eq!(cache.validators(&key).unwrap().etag.as_deref(), Some("\"v1\"")); + std::fs::write(&path, PNG).unwrap(); + assert_eq!(get(true).await.unwrap(), Ok(path.clone())); + assert_eq!(std::fs::read(&path).unwrap(), PNG); + let requests = requests.lock().unwrap().clone(); + assert_eq!(requests.len(), 2); + let first = requests[0].to_ascii_lowercase(); + let again = requests[1].to_ascii_lowercase(); + assert!(!first.contains("if-none-match"), "{first}"); + assert!(again.contains("if-none-match: \"v1\""), "{again}"); + assert!(again.contains("if-modified-since: tue, 06 oct 2026 10:00:00 gmt"), "{again}"); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// Redirects are followed (each hop asked as the first), not forever, + /// and only on the web; the app tells who it is and how to reach its + /// makers. + #[tokio::test] + async fn redirects_and_who_asks() { + let (base, requests) = logged_server().await; + let dir = temp_dir("redirects"); + let to = dir.join("x"); + download(&format!("{base}/redirect"), &to, &LIMITS, None).await.unwrap(); + assert_eq!(std::fs::read(&to).unwrap(), PNG); + let e = download(&format!("{base}/loop"), &to, &LIMITS, None).await.unwrap_err(); + assert_eq!(e.text, "too many redirects"); + let e = download(&format!("{base}/elsewhere"), &to, &LIMITS, None).await.unwrap_err(); + assert_eq!(e.retry, RetryHint::Permanent, "{e}"); + let requests = requests.lock().unwrap().clone(); + assert_eq!(requests.iter().filter(|r| r.starts_with("GET /loop ")).count(), REDIRECTS + 1); + let user_agent = format!("user-agent: {}\r\n", user_agent().to_ascii_lowercase()); + for request in &requests { + assert!(request.to_ascii_lowercase().contains(&user_agent), "{request}"); + } + let _ = std::fs::remove_dir_all(dir); + } + + /// A forward HTTP proxy on 127.0.0.1: relays each request, tells the + /// request lines it got. + async fn http_proxy() -> (u16, async_mpsc::UnboundedReceiver) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let (lines, received) = async_mpsc::unbounded_channel(); + tokio::spawn(async move { + while let Ok((mut client, _)) = listener.accept().await { + let lines = lines.clone(); + tokio::spawn(async move { + let mut head = Vec::new(); + let mut byte = [0u8]; + while !head.ends_with(b"\r\n\r\n") { + client.read_exact(&mut byte).await.unwrap(); + head.push(byte[0]); + } + let head = String::from_utf8(head).unwrap(); + let (line, rest) = head.split_once("\r\n").unwrap(); + lines.send(line.to_owned()).unwrap(); + // GET http://host:port/path HTTP/1.1, to the host as + // GET /path HTTP/1.1. + let target = line.split(' ').nth(1).unwrap(); + let url = Url::parse(target).unwrap(); + let address = format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()); + let mut server = TcpStream::connect(address).await.unwrap(); + let line = format!("GET {} HTTP/1.1\r\n", url.path()); + server.write_all(line.as_bytes()).await.unwrap(); + server.write_all(rest.as_bytes()).await.unwrap(); + let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await; + }); + } + }); + (port, received) + } + + /// A SOCKS5 proxy on 127.0.0.1 without authentication: relays each + /// connection, tells where to. + async fn socks5_proxy() -> (u16, async_mpsc::UnboundedReceiver) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let (targets, received) = async_mpsc::unbounded_channel(); + tokio::spawn(async move { + while let Ok((mut client, _)) = listener.accept().await { + let targets = targets.clone(); + tokio::spawn(async move { + let mut greeting = [0u8; 2]; + client.read_exact(&mut greeting).await.unwrap(); + let mut methods = vec![0u8; usize::from(greeting[1])]; + client.read_exact(&mut methods).await.unwrap(); + client.write_all(&[5, 0]).await.unwrap(); + let mut request = [0u8; 4]; + client.read_exact(&mut request).await.unwrap(); + let host = match request[3] { + 1 => { + let mut ip = [0u8; 4]; + client.read_exact(&mut ip).await.unwrap(); + std::net::Ipv4Addr::from(ip).to_string() + } + 3 => { + let mut len = [0u8]; + client.read_exact(&mut len).await.unwrap(); + let mut name = vec![0u8; usize::from(len[0])]; + client.read_exact(&mut name).await.unwrap(); + String::from_utf8(name).unwrap() + } + other => panic!("address type {other}"), + }; + let mut port = [0u8; 2]; + client.read_exact(&mut port).await.unwrap(); + let target = format!("{host}:{}", u16::from_be_bytes(port)); + targets.send(target.clone()).unwrap(); + let mut server = TcpStream::connect(target).await.unwrap(); + client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap(); + let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await; + }); + } + }); + (port, received) + } + + /// The proxy the desktop names for each address: asked per hop, only + /// with the scheme, host and port, and pictures go through it (HTTP or + /// SOCKS); where it names none, they go as without it. + #[tokio::test] + async fn pictures_go_through_the_proxy_named_for_each_hop() { + let base = server().await; + let other = server().await; + let (http_port, mut http_lines) = http_proxy().await; + let (socks_port, mut socks_targets) = socks5_proxy().await; + let clients = Clients::new(READ_TIMEOUT); + let (asked, mut origins) = async_mpsc::unbounded_channel(); + let proxied = format!("{other}/"); + clients.set_resolver(Arc::new(move |origin: String| { + asked.send(origin.clone()).unwrap(); + let answer = + (origin == proxied).then(|| format!("http://user:secret@127.0.0.1:{http_port}")); + Box::pin(async move { answer }) + })); + let dir = temp_dir("proxy"); + let to = dir.join("x"); + // Direct to `base`, redirected to `other` through the HTTP proxy. + let url = format!("{base}/to?{other}/banner"); + download_with(&clients, &url, &to, &LIMITS, None).await.unwrap(); + assert_eq!(std::fs::read(&to).unwrap(), PNG); + assert_eq!(origins.recv().await.unwrap(), format!("{base}/")); + assert_eq!(origins.recv().await.unwrap(), format!("{other}/")); + assert_eq!(http_lines.recv().await.unwrap(), format!("GET {other}/banner HTTP/1.1")); + assert!(http_lines.try_recv().is_err(), "only the second hop went through it"); + // Its failures say so, without the password. + let e = download_with(&clients, &format!("{other}/gone"), &to, &LIMITS, None).await; + let e = e.unwrap_err(); + assert!( + e.text.ends_with(&format!("(through the proxy http://127.0.0.1:{http_port})")), + "{e}" + ); + assert!(!e.text.contains("secret")); + // SOCKS, the host resolved by the proxy. + let socks_clients = Clients::new(READ_TIMEOUT); + let socks = format!("socks5h://127.0.0.1:{socks_port}"); + socks_clients.set_resolver(Arc::new(move |_| { + let answer = socks.clone(); + Box::pin(async move { Some(answer) }) + })); + let banner = format!("{}/banner", base.replace("127.0.0.1", "localhost")); + download_with(&socks_clients, &banner, &to, &LIMITS, None).await.unwrap(); + assert_eq!(std::fs::read(&to).unwrap(), PNG); + let port = base.rsplit(':').next().unwrap(); + assert_eq!(socks_targets.recv().await.unwrap(), format!("localhost:{port}")); + let _ = std::fs::remove_dir_all(dir); + } + #[tokio::test] async fn banners_above_the_old_limits_are_downloaded() { let base = server().await; let dir = temp_dir("large-banner"); let path = dir.join("large"); - download(&format!("{base}/large-banner"), &path, &LIMITS).await.unwrap(); + download(&format!("{base}/large-banner"), &path, &LIMITS, None).await.unwrap(); assert!(std::fs::metadata(&path).unwrap().len() > 16 << 20); std::fs::remove_dir_all(dir).unwrap(); } @@ -289,23 +1454,22 @@ mod tests { let to = dir.join("slow"); // Slow, but within its grace: it arrives. let patient = Limits { grace: Duration::from_secs(60), ..LIMITS }; - download(&format!("{base}/slow"), &to, &patient).await.unwrap(); + download(&format!("{base}/slow"), &to, &patient, None).await.unwrap(); let strict = Limits { grace: Duration::from_millis(150), min_rate: 1 << 20, ..LIMITS }; - let e = download(&format!("{base}/slow"), &to, &strict).await.unwrap_err(); - assert!(e.contains("too slow"), "{e}"); + let e = download(&format!("{base}/slow"), &to, &strict, None).await.unwrap_err(); + assert!(e.text.contains("too slow"), "{e}"); std::fs::remove_dir_all(dir).unwrap(); } - #[tokio::test] - async fn distinct_banners_download_concurrently_and_duplicates_share_a_request() { - use std::sync::Arc; - use tokio::sync::{Semaphore, mpsc as async_mpsc}; + /// A server on 127.0.0.1 that holds every answer until released; tells + /// each request as it arrives. + async fn gated_server() -> (String, async_mpsc::UnboundedReceiver<()>, Arc) { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); - let (requests, mut received) = async_mpsc::unbounded_channel(); + let (requests, received) = async_mpsc::unbounded_channel(); let release = Arc::new(Semaphore::new(0)); let gate = release.clone(); - let server = tokio::spawn(async move { + tokio::spawn(async move { while let Ok((mut socket, _)) = listener.accept().await { let (requests, gate) = (requests.clone(), gate.clone()); tokio::spawn(async move { @@ -328,6 +1492,12 @@ mod tests { }); } }); + (base, received, release) + } + + #[tokio::test] + async fn distinct_banners_download_concurrently_and_duplicates_share_a_request() { + let (base, mut received, release) = gated_server().await; let dir = temp_dir("parallel"); let cache = Cache::new(&dir); let (completed, mut results) = async_mpsc::unbounded_channel(); @@ -346,22 +1516,124 @@ mod tests { // All three requests arrive before any response is released: no // slow banner can serialize the other downloads. for _ in 0..3 { - tokio::time::timeout(Duration::from_secs(5), received.recv()).await.unwrap().unwrap(); + tokio::time::timeout(5 * SECOND, received.recv()).await.unwrap().unwrap(); } release.add_permits(3); for _ in 0..4 { - let path = tokio::time::timeout(Duration::from_secs(5), results.recv()) - .await - .unwrap() - .unwrap() - .unwrap(); + let path = + tokio::time::timeout(5 * SECOND, results.recv()).await.unwrap().unwrap().unwrap(); assert_eq!(std::fs::read(path).unwrap(), PNG); } assert!(received.try_recv().is_err(), "duplicate URL opened another connection"); - server.abort(); std::fs::remove_dir_all(dir).unwrap(); } + /// A host whose answers do not come holds [`PER_HOST`] downloads at + /// most, those redirected to it too; the others wait for a slot of + /// their host. + #[tokio::test] + async fn a_host_runs_a_few_downloads_at_once() { + let (base, mut received, release) = gated_server().await; + // Redirected there from two hosts, fewer from each than a host's + // slots. + let redirectors = [server().await, server().await]; + let dir = temp_dir("per-host"); + let cache = Cache::new(&dir); + let (completed, mut results) = async_mpsc::unbounded_channel(); + for n in 0..PER_HOST + 2 { + let completed = completed.clone(); + let waiter: Waiter = Box::new(move |r| completed.send(r).unwrap()); + let url = format!("{}/to?{base}/{n}", redirectors[n % 2]); + fetch(cache.clone(), &url, false, 0, waiter); + } + for _ in 0..PER_HOST { + tokio::time::timeout(5 * SECOND, received.recv()).await.unwrap().unwrap(); + } + let more = tokio::time::timeout(Duration::from_millis(300), received.recv()).await; + assert!(more.is_err(), "more than {PER_HOST} downloads from one host at once"); + // Another host is not held up. + let banner = format!("{}/banner", server().await); + let (tx, rx) = mpsc::channel(); + fetch(cache.clone(), &banner, false, 0, Box::new(move |r| tx.send(r).unwrap())); + tokio::task::spawn_blocking(move || rx.recv_timeout(5 * SECOND).unwrap().unwrap()) + .await + .unwrap(); + release.add_permits(PER_HOST + 2); + for _ in 0..PER_HOST + 2 { + tokio::time::timeout(5 * SECOND, results.recv()).await.unwrap().unwrap().unwrap(); + } + // The hosts' slots go with their last download. + let hosts = [&base, &redirectors[0], &redirectors[1]] + .map(|url| host_and_port(&Url::parse(url).unwrap())); + let left = || hosts.iter().any(|host| HOSTS.lock().unwrap().contains_key(host)); + for _ in 0..100 { + if !left() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(!left(), "slots left behind"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn addresses_for_the_log() { + assert_eq!( + loggable( + " https://u:p@upload.wikimedia.org:443/wikipedia/commons/thumb/a/a9/Golod.jpg/250px-Golod.jpg?sig=s#f " + ), + "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Golod.jpg/250px-Golod.jpg" + ); + // Escaped as it is sent. + assert_eq!( + loggable("https://h.test/Голод 1.png"), + "https://h.test/%D0%93%D0%BE%D0%BB%D0%BE%D0%B4%201.png" + ); + assert_eq!(loggable("http://127.0.0.1:8080/b.png?x"), "http://127.0.0.1:8080/b.png"); + assert_eq!(loggable("http://[::1]:81/b"), "http://[::1]:81/b"); + let long = format!("https://h.test/{}", "a".repeat(1000)); + let logged = loggable(&long); + assert_eq!(logged.chars().count(), LOGGED_URL + 1); + assert!(logged.starts_with("https://h.test/aaa") && logged.ends_with("a…")); + assert_eq!(loggable("ts3image://banner.png?channel=1"), "ts3image"); + assert_eq!(loggable("not an address"), "?"); + assert_eq!(without_credentials("socks5h://u:p@127.0.0.1:2080"), "socks5h://127.0.0.1:2080"); + assert_eq!( + origin_of(&Url::parse("https://u:p@h.test/a?b").unwrap()), + "https://h.test:443/" + ); + assert_eq!(host_and_port(&Url::parse("http://H.test/x").unwrap()), "h.test:80"); + // The app's version, as the UI sets it. + let link = "(+https://github.com/Faumaray/Voelin)"; + assert_eq!(user_agent_of("9.9.9-test"), format!("Voelin/9.9.9-test {link}")); + assert_eq!(user_agent_of(""), format!("Voelin/{} {link}", env!("CARGO_PKG_VERSION"))); + } + + /// Which proxy pictures go through is told once for each, and when it + /// changes for a host; never with its password. + #[test] + fn the_proxy_pictures_go_through_is_told_when_it_changes() { + let clients = Clients::new(READ_TIMEOUT); + let proxy = Some("http://u:secret@127.0.0.1:2080"); + let ((), lines) = info_lines(|| { + clients.note_route("https://a.test:443/", None); + clients.note_route("https://b.test:443/", proxy); + clients.note_route("https://c.test:443/", proxy); + clients.note_route("https://b.test:443/", proxy); + clients.note_route("https://b.test:443/", None); + clients.note_route("https://a.test:443/", Some("socks5h://127.0.0.1:1080")); + }); + assert_eq!( + lines, + [ + "pictures go through the desktop's proxy proxy=http://127.0.0.1:2080", + "pictures from this host go without the desktop's proxy now origin=https://b.test:443/", + "pictures from this host go through the desktop's proxy now origin=https://a.test:443/ \ + proxy=socks5h://127.0.0.1:1080", + ] + ); + } + #[test] fn pictures_by_content() { assert!(is_picture(PNG)); @@ -374,5 +1646,40 @@ mod tests { assert!(!is_picture(b"")); assert!(!is_picture(b"RIFF\x24\0\0\0WAVEfmt ")); assert!(!is_picture(b"")); + // What browsers show too: BMP, ICO, SVG after a comment or DOCTYPE. + assert!(is_picture(b"BM\x36\0\0\0")); + assert!(is_picture(b"\0\0\x01\0\x01\0")); + assert!(is_picture(b"\n")); + assert!(is_picture(b"")); + assert!(!is_picture(b"")); + assert!(is_picture(b"")); + assert!(is_picture( + b"" + )); + assert!(is_picture(b" ]>")); + // Pages with an SVG in them are pages. + assert!(!is_picture( + b"\">" + )); + assert!(!is_picture(b"")); + assert!(!is_picture(b"")); + assert!(!is_picture(b"")); + // Cut off before it tells. + assert!(!is_picture(b""; + assert_eq!(picture("test:svg-prolog", svg).size().width, 8); + assert!(decode(b"").is_none()); + // A page with an SVG in it is a page (told so by the engine). + assert!(decode(b"").is_none()); + } + + #[test] + fn rasters_beyond_the_pixel_cap_are_refused_before_pixels_are_read() { + // Only the header: its size is all that is read. + let mut bytes = Vec::new(); + let mut encoder = png::Encoder::new(&mut bytes, 20_000, 20_000); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + std::mem::forget(encoder.write_header().unwrap()); + assert!(decode(&bytes).is_none()); + } + + #[test] + fn large_rasters_are_scaled_down() { use std::io::Write; - for (width, height) in [(6000, 6000), (16_385, 1), (1, 16_385)] { + for (width, height) in [(5000, 5000), (16_385, 1), (1, 16_385)] { let mut bytes = Vec::new(); let mut encoder = png::Encoder::new(&mut bytes, width, height); encoder.set_color(png::ColorType::Rgba); @@ -279,19 +367,13 @@ mod tests { } stream.finish().unwrap(); writer.finish().unwrap(); - // A valid solid picture fits the download cap but not the - // decoded budget. Generate it a row at a time, without ever - // allocating the large pixel buffer this test guards against. + // Generated a row at a time. assert!(bytes.len() < 4 << 20); - assert_eq!( - image::ImageReader::new(Cursor::new(&bytes)) - .with_guessed_format() - .unwrap() - .into_dimensions() - .unwrap(), - (width, height) - ); - assert!(decode(&bytes).is_none()); + let (image, cost) = decode(&bytes).unwrap(); + let size = image.size(); + assert!(size.width <= MAX_SIDE && size.height <= MAX_SIDE, "{size:?}"); + assert_eq!(size.width.max(size.height), MAX_SIDE); + assert_eq!(cost, size.width as usize * size.height as usize * 4); } } @@ -328,16 +410,23 @@ mod tests { std::fs::write(&path, bytes).unwrap(); assert_eq!(file(&path).size().width, width, "{name}"); } - // A file that changed is decoded again once forgotten. + // A file that arrives again unchanged is not decoded again. let path = dir.join("287478770"); + let decoded = || CACHE.with(|c| c.borrow().len()); + let before = decoded(); + std::fs::write(&path, &png).unwrap(); + reloaded(&path); + assert_eq!(decoded(), before, "kept"); + // One that changed is, once it arrived. let mut wider = Vec::new(); let mut encoder = png::Encoder::new(&mut wider, 5, 2); encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); encoder.write_header().unwrap().write_image_data(&[90; 40]).unwrap(); std::fs::write(&path, wider).unwrap(); - assert_eq!(file(&path).size().width, 3, "kept until forgotten"); - forget(&path); + assert_eq!(file(&path).size().width, 3, "kept until it arrived"); + reloaded(&path); + assert_eq!(decoded(), before - 1); assert_eq!(file(&path).size().width, 5); // A file that is no picture is remembered as such until forgotten, // not read again on every refresh. @@ -346,7 +435,7 @@ mod tests { assert_eq!(file(&junk).size().width, 0); std::fs::write(&junk, &png).unwrap(); assert_eq!(file(&junk).size().width, 0, "remembered"); - forget(&junk); + reloaded(&junk); assert_eq!(file(&junk).size().width, 3); std::fs::remove_dir_all(dir).unwrap(); } @@ -356,6 +445,6 @@ mod tests { let image = emoji("1f600"); assert!(image.size().width > 0); assert_eq!(emoji("nope").size().width, 0); - assert!(usage_text().contains("of 64 MB")); + assert!(usage_text().contains("of 256 MB")); } } diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs index 0bb05c1..af7593c 100644 --- a/crates/voelin-ui/src/inbox.rs +++ b/crates/voelin-ui/src/inbox.rs @@ -1,7 +1,8 @@ //! Requests from the platform around the window: on Android a tapped -//! notification or something shared to the app ("Share to Voelin"). They -//! can come from any thread and before the window runs; [`request`] keeps -//! them until the window takes them on its thread. +//! notification or something shared to the app ("Share to Voelin"), and a +//! TeamSpeak link to open. They can come from any thread and before the +//! window runs; [`request`] keeps them until the window takes them on its +//! thread. use std::path::PathBuf; use std::sync::{Mutex, PoisonError}; @@ -21,6 +22,9 @@ pub enum Request { /// should not post into a chat), the files are uploaded to the current /// channel and linked there, as the composer's attach button does. Share { text: Option, files: Vec }, + /// Open a TeamSpeak link (`ts3server://`, `teamspeak://`, `tmspk.gg`): + /// the server dialog filled in from it, or a move in voice. + OpenLink(String), } static PENDING: Mutex> = Mutex::new(Vec::new()); @@ -52,6 +56,9 @@ pub(crate) fn take() { nav.invoke_show(Page::Server); with_app(|app| app.share(&nav, text, files)); } + Request::OpenLink(url) => { + with_app(|app| app.open_link(&url)); + } } } } @@ -67,8 +74,9 @@ impl App { _ => view.state.own_channel, } .map(|c| { - let name = view.presence.channels.get(&c).map(|c| c.name.as_str()); - (c, name.map_or_else(|| "the channel".to_owned(), |n| format!("#{n}"))) + let name = + view.presence.channels.get(&c).map(|c| crate::vm::tree::channel_title(c).0); + (c, name.map_or_else(|| "the channel".to_owned(), str::to_owned)) }); Some((id, tab.title.clone(), channel)) }); diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index 0e8f5b8..3671c57 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -13,10 +13,12 @@ mod hotkey; mod identities; mod images; mod inbox; +mod links; mod members; mod messages; #[cfg(not(target_os = "android"))] mod myts; +mod popout; mod previews; mod servers; mod settings; diff --git a/crates/voelin-ui/src/links.rs b/crates/voelin-ui/src/links.rs new file mode 100644 index 0000000..2445e78 --- /dev/null +++ b/crates/voelin-ui/src/links.rs @@ -0,0 +1,70 @@ +//! TeamSpeak links opened in the app (`ts3server://`, `teamspeak://` and +//! `tmspk.gg`), from a message or the platform. + +use slint::ComponentHandle; +use voelin_core::VoiceState; +use voelin_model::{Link, ServerLink}; + +use crate::app::{App, Nav}; +use crate::vm; + +impl App { + /// Open a TeamSpeak link. In voice on its server: show it and move into + /// the link's channel (a locked one asks for its password if the link + /// has none or a wrong one). Otherwise the server dialog, filled in from + /// the link (the saved server's when there is one): nothing connects + /// before its Connect. + pub(crate) fn open_link(&mut self, url: &str) { + let link = match Link::parse(url) { + Some(Link::Server(link)) => link, + Some(Link::Invite(_)) => { + self.set_status( + "TeamSpeak invite codes (tmspk.gg/…) can't be opened yet; ask for the server address", + ); + return; + } + None => { + self.set_status("Not a TeamSpeak server link"); + return; + } + }; + let in_voice = |id: i64| { + self.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected) + }; + match vm::servers::link_server(&self.bookmarks, &link.address(), self.current, in_voice) { + Some((id, true)) => self.move_by_link(id, &link), + saved => self.open_link_form(saved.map(|(id, _)| id), &link), + } + } + + /// In voice on the link's server: show it, and move into its channel. + fn move_by_link(&mut self, session: i64, link: &ServerLink) { + self.show_server(session); + let Some(path) = &link.channel else { return }; + let Some(view) = self.sessions.get_mut(&session) else { return }; + let Some(channel) = vm::servers::channel_by_path(&view.presence, path) else { + let server = self.bookmark(session).map(|b| b.name.clone()).unwrap_or_default(); + self.set_status(format!("{server} has no channel \u{201c}{path}\u{201d}")); + return; + }; + if view.state.own_channel == Some(channel) { + return; + } + // As if typed into the password dialog: a wrong one asks again. + if let Some(password) = &link.channel_password { + view.channel_passwords.insert(channel, password.clone()); + } + self.join_channel(session, channel); + } + + /// The server dialog, filled in from the link over the saved server's + /// form, or a new server's. + fn open_link_form(&mut self, saved: Option, link: &ServerLink) { + let form = self.bookmark_form(saved.unwrap_or(-1)); + let form = vm::servers::link_form(link, form, &self.default_nickname()); + let Some(ui) = self.ui.upgrade() else { return }; + let nav = ui.global::