diff --git a/CHANGELOG.md b/CHANGELOG.md index 3af4ecf..de82d06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,7 +27,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows 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). + 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/…`) @@ -42,6 +44,32 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows 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. ### Changed @@ -101,6 +129,31 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - 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. +- 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 @@ -131,6 +184,10 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows - 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. ## [0.0.1-alpha] - 2026-10-04 diff --git a/Cargo.lock b/Cargo.lock index 4303409..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]] @@ -9693,9 +9695,13 @@ version = "0.1.0" dependencies = [ "anyhow", "base64 0.22.1", + "bytes", "dirs", "futures", + "h2", "hickory-resolver", + "http", + "httpdate", "md5", "reqwest", "rusqlite", @@ -9827,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", @@ -9863,6 +9871,7 @@ dependencies = [ "tracing", "windows 0.62.2", "x11rb", + "zbus", ] [[package]] @@ -9873,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 0554dca..fbeaf37 100644 --- a/crates/proto/UPSTREAM.md +++ b/crates/proto/UPSTREAM.md @@ -129,7 +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. **Privilege key when connecting** (`tsclientlib/src/lib.rs`, "Voelin patch"). +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 4f8911e..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. 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-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/book.rs b/crates/voelin-core/src/book.rs index 0e7e9d2..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, @@ -117,7 +117,12 @@ pub(crate) fn presence_from_book( needed_talk_power: c.needed_talk_power.unwrap_or(0), is_default: c.is_default.unwrap_or(false), icon: c.icon.map_or(0, |i| i.0), - banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()), + banner_gfx_url: c + .banner_gfx_url + .as_deref() + .map(str::trim) + .filter(|u| !u.is_empty()) + .map(str::to_owned), // A number the book keeps as text. banner_mode: c .banner_mode @@ -149,11 +154,15 @@ pub(crate) fn presence_from_book( server_groups, country: Some(c.country_code.clone()).filter(|c| !c.is_empty()), avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()), + myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url), description: Some(c.description.clone()).filter(|d| !d.is_empty()), talk_power: c.talk_power, talker: c.talk_power_granted, channel_group: Some(c.channel_group.0), - badges: parse_badges(&c.badges), + badges: shown_badges( + &c.badges, + c.signed_badges.as_deref().unwrap_or_default(), + ), icon: c.icon.0, recording: c.is_recording, priority_speaker: c.is_priority_speaker, @@ -179,10 +188,8 @@ mod tests { InMessage::new(&packet.header(), text.as_bytes()).unwrap() } - /// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them: - /// in the channel list, when a channel is created and when it is edited. - #[test] - fn channel_banners() { + /// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`. + fn ts6_book() -> data::Connection { let InMessage::InitServer(init) = message(concat!( "initserver virtualserver_name=Test virtualserver_welcomemessage ", "virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ", @@ -202,20 +209,29 @@ mod tests { )) else { panic!("not an initserver"); }; - let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init); - let channel = |cid: u64, order: u64, name: &str, banner: &str| { - format!( - "cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \ - channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \ - channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \ - channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \ - channel_codec_is_unencrypted=1 channel_delete_delay=0 \ - channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \ - channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \ - channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \ - channel_storage_quota=4294967295" - ) - }; + data::Connection::new(EccKeyPrivP256::create().to_pub(), &init) + } + + /// A `channellist` entry as TeamSpeak 6 sends it. + fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String { + format!( + "cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \ + channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \ + channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \ + channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \ + channel_codec_is_unencrypted=1 channel_delete_delay=0 \ + channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \ + channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \ + channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \ + channel_storage_quota=4294967295" + ) + } + + /// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them: + /// in the channel list, when a channel is created and when it is edited. + #[test] + fn channel_banners() { + let mut book = ts6_book(); let list = format!( "channellist {}|{}", channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"), @@ -269,4 +285,50 @@ mod tests { assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust); assert_eq!(p.server.priority_speaker_dimm_db, -18); } + + /// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it: + /// when the client enters and when it changes. + #[test] + fn myts_avatars() { + let mut book = ts6_book(); + book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", "")))) + .unwrap(); + let enter = |clid: u16, avatar: &str| { + format!( + "notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \ + client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \ + client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \ + client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \ + client_output_hardware=1 client_meta_data client_is_recording=0 \ + client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \ + client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \ + client_talk_request=0 client_talk_request_msg client_is_talker=0 \ + client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \ + client_needed_serverquery_view_power=75 client_is_channel_commander=0 \ + client_country=RU client_badges client_myteamspeak_id=m{clid} \ + client_integrations{avatar}" + ) + }; + for text in [ + enter( + 5, + r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png", + ), + // A TeamSpeak 3 server, or a client without one. + enter(6, ""), + enter(7, " client_myteamspeak_avatar"), + ] { + book.handle_command(&message(&text)).unwrap(); + } + let p = presence_from_book(&book, None, |_| false); + let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone(); + assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png")); + assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None)); + book.handle_command(&message( + r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png", + )) + .unwrap(); + let p = presence_from_book(&book, None, |_| false); + assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png")); + } } 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 b31ed96..8a15086 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -96,6 +96,10 @@ use voelin_stream::{ EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo, }; pub use voice::VoiceOptions; +/// Banners are downloaded and shown by the same rule. +pub use web::is_svg; +/// Pictures from the web go through the desktop's proxy (set at startup). +pub use web::set_proxy_resolver; pub type SessionId = u64; @@ -108,6 +112,11 @@ pub const POKE_MESSAGE_MAX: usize = 100; pub enum Command { /// Main account proof for every current and future voice connection. SetMytsIdentity(Option>), + /// 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, @@ -115,10 +124,14 @@ pub enum Command { DisconnectVoice { session: SessionId, }, - /// Invisible presence and relay chat through a `tsgw` gateway. + /// Invisible presence and relay chat through a `tsgw` gateway: the first + /// of `urls` (best first, [`discover::gateways`]) that logs in, tried in + /// turn again whenever it is lost. Sent again with the same `urls` and + /// identity while it runs, it is not started over; while still + /// connecting, it tries again at once (at most every 5 s). ObserveGateway { session: SessionId, - url: String, + urls: Vec, identity: Box, }, /// Invisible presence and relay chat with own ServerQuery credentials. @@ -671,9 +684,10 @@ pub enum Event { request: RequestId, result: Result<(), String>, }, - /// A client's avatar is in the cache: `path`, its MD5 `hash` - /// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears - /// with an avatar and when it changes. + /// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a + /// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address + /// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]). + /// Comes when the client appears with an avatar and when it changes. AvatarReady { session: SessionId, client_uid: String, @@ -849,6 +863,7 @@ async fn run( contacts.load().await; let mut sessions: HashMap = HashMap::new(); let (myts_identity, _) = watch::channel(None); + let (myts_data, _) = watch::channel(None); let mut current = shared.current(); // Pruning: at start, then hourly (and when the setting changes). let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600)); @@ -906,6 +921,16 @@ async fn run( }); continue; } + Command::SetMytsData(data) => { + myts_data.send_if_modified(|current| { + if *current == data { + return false; + } + *current = data; + true + }); + continue; + } Command::SetAudioSettings(new) => { settings = (*new).clone(); for s in sessions.values() { @@ -982,6 +1007,7 @@ async fn run( settings.clone(), engine.clone(), myts_identity.subscribe(), + myts_data.subscribe(), ); if let Some(profiles) = &srtp_profiles { s.send(Command::SetSrtpProfiles(profiles.clone())); @@ -1061,6 +1087,7 @@ fn command_session(command: &Command) -> SessionId { | Command::SetOfflineMessageRead { session, .. } | Command::CloseSession { session } => *session, Command::SetMytsIdentity(_) + | Command::SetMytsData(_) | Command::SetAudioSettings(_) | Command::SetSrtpProfiles(_) | Command::TestMicrophone { .. } diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index ba2d164..348fae5 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -15,7 +15,7 @@ use std::time::Duration; use tokio::time::Instant; use tokio::sync::{broadcast, mpsc, watch}; -use tracing::{debug, warn}; +use tracing::{debug, info, warn}; use tsclientlib::ClientId; use voelin_audio::AudioSettings; use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature}; @@ -23,7 +23,7 @@ use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails, use voelin_stream::ClientState; use crate::audio::{self, AudioEvent, AudioHandle, AudioIn}; -use crate::cache::{self, Fetch, SharedCache, Waiter}; +use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter}; use crate::contacts::{Contacts, Relation}; use crate::files::{self, DownloadTo, Report, RequestId, Sink, TransferId, TransferState}; use crate::gateway::{ @@ -87,10 +87,12 @@ impl SessionHandle { audio_settings: AudioSettings, shared: Shared, myts_identity: watch::Receiver>>, + 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,6 +342,13 @@ 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, badges) reported or being fetched, by @@ -231,6 +358,9 @@ struct Session { /// fetched, by address, with the size they may have /// ([`Command::FetchPicture`]). chat_pictures: HashMap, + /// Banner addresses that cannot be fetched at all (another scheme), + /// logged once. + unfetchable: HashSet, image_epoch: u64, images_enabled: bool, image_retries: HashMap, @@ -257,19 +387,24 @@ 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(), @@ -290,6 +425,7 @@ impl Session { gateway: None, gateway_presence: None, gateway_client: None, + gateway_observed: None, query: None, query_presence: None, audio: None, @@ -398,6 +534,7 @@ impl Session { } let link = VoiceLink { myts_identity: self.myts_identity.clone(), + myts_data: self.myts_data.clone(), session: self.id, events: self.events.clone(), settings: self.settings.clone(), @@ -414,13 +551,32 @@ impl Session { let _ = tx.send(VoiceCmd::Disconnect); } } - Command::ObserveGateway { url, identity, .. } => { + Command::ObserveGateway { urls, identity, .. } => { + // Asked again for the same (the server selected again): not + // started over; while still connecting, it tries again now + // (not every time: a struggling gateway is not hammered). + if let (Some((_, tx)), Some(observed)) = (&self.gateway, &mut self.gateway_observed) + && observed.same(&urls, &identity) + { + if self.state.observe == ObserveState::Connecting && observed.nudge() { + let _ = tx.send(GatewayCmd::RetryNow); + } + return; + } self.stop_observing(); + if urls.is_empty() { + return; + } let generation = self.next_generation(); - self.known_server(format!("gateway:{url}")); + // Each is published for this server (history before its + // unique id is known). + for url in &urls { + self.known_server(format!("gateway:{url}")); + } let (cmd_tx, cmd_rx) = mpsc::unbounded_channel(); let (ev_tx, ev_rx) = mpsc::unbounded_channel(); - tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx)); + self.gateway_observed = Some(gateway::Observed::new(&urls, &identity)); + tokio::spawn(gateway::run(urls, *identity, cmd_rx, ev_tx)); self.forward(ev_rx, move |e| SourceEvent::Gateway(generation, e)); self.gateway = Some((generation, cmd_tx)); self.state.observe = ObserveState::Connecting; @@ -676,9 +832,13 @@ impl Session { .voice_presence .as_ref() .and_then(|p| p.client_by_uid(&client_uid)) - .and_then(|c| c.avatar.clone()); - if let Some(hash) = hash { + .and_then(|c| c.avatar.clone()) + .filter(|hash| self.server_avatars_failed.get(&client_uid) != Some(hash)); + let myts = self.shown_client(&client_uid).and_then(|c| c.myts_avatar.clone()); + if let Some(hash) = hash.filter(|_| self.voice.is_some()) { self.fetch_avatar(&client_uid, &hash, true); + } else if let Some(url) = myts { + self.fetch_myts_avatar(&client_uid, &url, true); } } Command::FetchPicture { url, max_bytes, .. } => { @@ -687,7 +847,7 @@ impl Session { && !self.chat_pictures.contains_key(&url) { self.chat_pictures.insert(url.clone(), max_bytes); - self.fetch_picture(&url, false); + self.fetch_chat_picture(&url); } } Command::ListOfflineMessages { request, .. } => { @@ -718,6 +878,7 @@ impl Session { } // Engine-wide. Command::SetMytsIdentity(_) + | Command::SetMytsData(_) | Command::CloseSession { .. } | Command::TestMicrophone { .. } | Command::SetSetting { .. } @@ -840,9 +1001,12 @@ impl Session { self.image_epoch += 1; self.image_retries.clear(); self.avatars.clear(); + self.myts_avatars.clear(); + self.server_avatars_failed.clear(); self.icons.clear(); self.pictures.clear(); self.chat_pictures.clear(); + self.unfetchable.clear(); self.contact_audio.clear(); self.priority_audio = Default::default(); self.stream_friends.clear(); @@ -880,7 +1044,7 @@ impl Session { } fn image_waiter(&self, request: ImageRequest, requested: bool) -> Waiter { - let epoch = if requested { + let epoch = if requested && voice_bound(&request) { self.voice.as_ref().map_or(0, |(generation, _)| *generation) } else { self.image_epoch @@ -898,6 +1062,45 @@ impl Session { self.fetch_image(key, files::avatar_path(uid).map(|path| (0, path)), false, waiter); } + /// The myTeamSpeak avatars of the presence shown (any source) where the + /// server's avatar is not shown: none set, no voice connection to + /// download it over, or its download gave up. As the official client: + /// the server's avatar first. + fn fetch_myts_avatars(&mut self, p: &Presence) { + if !self.settings.current().get(&CACHE_FETCH_IMAGES) { + return; + } + let mut wanted = HashMap::with_capacity(self.myts_avatars.len()); + for c in p.clients.values() { + let (Some(uid), Some(url)) = (&c.uid, &c.myts_avatar) else { continue }; + let server_avatar = c.avatar.is_some() + && self.voice.is_some() + && self.server_avatars_failed.get(uid) != c.avatar.as_ref(); + if server_avatar { + continue; + } + if self.myts_avatars.get(uid) != Some(url) { + self.fetch_myts_avatar(uid, url, false); + } + wanted.insert(uid.clone(), url.clone()); + } + self.myts_avatars = wanted; + } + + fn fetch_myts_avatar(&self, uid: &str, url: &str, requested: bool) { + let request = ImageRequest::MytsAvatar { uid: uid.into(), url: url.into() }; + let waiter = self.image_waiter(request, requested); + web::fetch_avatar(self.cache.current(), url, max_cache_bytes(&self.settings), waiter); + } + + /// The client shown (any presence) with this unique id. + fn shown_client(&self, uid: &str) -> Option<&voelin_model::ClientInfo> { + [&self.voice_presence, &self.gateway_presence, &self.query_presence] + .into_iter() + .find_map(|p| p.as_ref()) + .and_then(|p| p.client_by_uid(uid)) + } + fn fetch_icon(&self, icon: u32) { let waiter = self.image_waiter(ImageRequest::Icon(icon), false); self.fetch_image(cache::icon_key(icon), Some((0, files::icon_path(icon))), false, waiter); @@ -908,19 +1111,10 @@ impl Session { ImageRequest::Avatar { uid, hash } => { self.voice.is_some() && self.avatars.get(uid) == Some(hash) } + ImageRequest::MytsAvatar { uid, url } => self.myts_avatars.get(uid) == Some(url), ImageRequest::Icon(id) => self.voice.is_some() && self.icons.contains(id), - ImageRequest::Picture(url) => { - self.pictures.contains(url) || self.chat_pictures.contains_key(url) - } - } - } - - /// How large the picture at `url` may be: a chat picture as large as - /// it was asked for, unless it is also a banner or badge. - fn picture_limit(&self, url: &str) -> u64 { - match self.chat_pictures.get(url) { - Some(max) if !self.pictures.contains(url) => (*max).min(cache::MAX_PICTURE_BYTES), - _ => cache::MAX_PICTURE_BYTES, + ImageRequest::Picture(url) => self.pictures.contains(url), + ImageRequest::ChatPicture(url) => self.chat_pictures.contains_key(url), } } @@ -929,16 +1123,28 @@ impl Session { requested: bool, epoch: u64, request: ImageRequest, - result: Result, + 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 @@ -949,13 +1155,24 @@ impl Session { match result { Ok(path) => { self.image_retries.remove(&request); + // A server avatar given up on came after all (asked for + // again): it is shown again in place of the myTeamSpeak one. + if let ImageRequest::Avatar { uid, hash } = &request + && self.server_avatars_failed.get(uid) == Some(hash) + { + self.server_avatars_failed.remove(uid); + if let Some(presence) = self.voice_presence.clone() { + self.fetch_myts_avatars(&presence); + } + } if !requested && !self.settings.current().get(&CACHE_FETCH_IMAGES) { return; } // A chat picture already in the cache may be larger than // asked for now. - if let ImageRequest::Picture(url) = &request - && std::fs::metadata(&path).is_ok_and(|m| m.len() > self.picture_limit(url)) + if let ImageRequest::ChatPicture(url) = &request + && let Some(max) = self.chat_pictures.get(url) + && std::fs::metadata(&path).is_ok_and(|m| m.len() > *max) { return; } @@ -964,23 +1181,49 @@ impl Session { ImageRequest::Avatar { uid: client_uid, hash } => { Event::AvatarReady { session, client_uid, hash, path } } + // The address in place of a hash: it changes with the + // picture. + ImageRequest::MytsAvatar { uid: client_uid, url } => { + Event::AvatarReady { session, client_uid, hash: url, path } + } ImageRequest::Icon(icon) => Event::IconReady { session, icon, path }, - ImageRequest::Picture(url) => Event::PictureReady { session, url, path }, + ImageRequest::Picture(url) | ImageRequest::ChatPicture(url) => { + Event::PictureReady { session, url, path } + } }); } Err(error) => { - debug!(?request, %error, "image download failed"); - let retry = self - .image_retries - .entry(request) - .or_insert(ImageRetry { failures: 0, due: None }); - retry.failures = retry.failures.saturating_add(1); - retry.due = match retry.failures { - 1..=3 => { - Some(Instant::now() + Duration::from_secs(1 << (2 * (retry.failures - 1)))) + let avatar_of = match &request { + ImageRequest::Avatar { uid, hash } => Some((uid.clone(), hash.clone())), + _ => None, + }; + // The host banner is asked for again at its reload interval too. + let reload_s = match (&request, &self.banner_reload) { + (ImageRequest::Picture(url), Some((reloaded, every_s, _))) + if url == reloaded => + { + Some((*every_s).max(web::MIN_RELOAD.as_secs())) } _ => None, }; + let retry = self.image_retries.entry(request.clone()).or_default(); + retry.failures = retry.failures.saturating_add(1); + let delay = retry_delay(&request, retry.failures, error.retry, retry.gone); + retry.due = delay.map(|delay| Instant::now() + delay); + retry.busy = matches!(error.retry, RetryHint::After(_)); + let newly_gone = error.retry == RetryHint::Permanent && !retry.gone; + retry.gone |= newly_gone; + log_image_failure(&request, retry.failures, delay, &error, newly_gone, reload_s); + // The server's avatar gave up (its files unreachable): the + // myTeamSpeak one, if the client has one. + if let (None, Some((uid, hash))) = (retry.due, avatar_of) + && self.server_avatars_failed.get(&uid) != Some(&hash) + { + self.server_avatars_failed.insert(uid, hash); + if let Some(presence) = self.voice_presence.clone() { + self.fetch_myts_avatars(&presence); + } + } } } } @@ -991,6 +1234,8 @@ impl Session { self.images_enabled = enabled; self.image_epoch += 1; self.avatars.clear(); + self.myts_avatars.clear(); + self.server_avatars_failed.clear(); self.icons.clear(); self.pictures.clear(); self.chat_pictures.clear(); @@ -1029,8 +1274,10 @@ impl Session { for request in ready { match request { ImageRequest::Avatar { uid, hash } => self.fetch_avatar(&uid, &hash, false), + ImageRequest::MytsAvatar { uid, url } => self.fetch_myts_avatar(&uid, &url, false), ImageRequest::Icon(icon) => self.fetch_icon(icon), ImageRequest::Picture(url) => self.fetch_picture(&url, true), + ImageRequest::ChatPicture(url) => self.fetch_chat_picture(&url), } } } @@ -1075,17 +1322,25 @@ impl Session { if !enabled { return; } + let all = std::iter::once(&p.server.banner_gfx_url) + .chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref())) + .filter(|u| !u.is_empty()); + let mut urls = HashSet::new(); + for url in all { + if self.can_fetch_picture(url) { + urls.insert(url.clone()); + } else if files::server_image(url).is_none() && self.unfetchable.insert(url.clone()) { + let scheme = url.split(':').next().unwrap_or_default(); + info!(%scheme, "banner not downloaded: only http, https and ts3image addresses"); + } + } // The badges shown, from TeamSpeak's server. let badge_urls = p .clients .values() .flat_map(|c| c.badges.iter().take(badges::SHOWN)) .filter_map(|guid| badges::icon_url(guid)); - let urls: HashSet = std::iter::once(p.server.banner_gfx_url.clone()) - .chain(p.channels.values().filter_map(|c| c.banner_gfx_url.clone())) - .chain(badge_urls) - .filter(|u| self.can_fetch_picture(u)) - .collect(); + urls.extend(badge_urls); self.pictures.retain(|url| urls.contains(url)); for url in &urls { if self.pictures.insert(url.clone()) { @@ -1094,6 +1349,13 @@ impl Session { } } + /// Whether the host of the picture at `url` asked to wait + /// (`Retry-After`) and the wait is not over. + fn picture_host_busy(&self, url: &str) -> bool { + let retry = self.image_retries.get(&ImageRequest::Picture(url.into())); + retry.is_some_and(|r| r.busy && r.due.is_some_and(|due| due > Instant::now())) + } + /// Get the picture at `url` into the cache (again with `fresh`): from /// the web, or from the server's files through the voice connection. fn fetch_picture(&self, url: &str, fresh: bool) { @@ -1103,11 +1365,19 @@ impl Session { let key = cache::server_picture_key(server, url); self.fetch_image(key, Some(file), fresh, waiter); } else { - let (max_cache, max) = (max_cache_bytes(&self.settings), self.picture_limit(url)); - web::fetch(self.cache.current(), url, fresh, max_cache, max, waiter); + web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter); } } + /// Get the picture a chat message shows at `url` into the cache, if it + /// is no larger than it was asked for ([`Command::FetchPicture`]). + fn fetch_chat_picture(&self, url: &str) { + let Some(&max_bytes) = self.chat_pictures.get(url) else { return }; + let waiter = self.image_waiter(ImageRequest::ChatPicture(url.into()), false); + let max_cache = max_cache_bytes(&self.settings); + web::fetch_chat_picture(self.cache.current(), url, max_cache, max_bytes, waiter); + } + /// Get `key` from the cache, downloading `file` (channel and path) once /// (again with `fresh`). fn fetch_image(&self, key: String, file: Option<(u64, String)>, fresh: bool, waiter: Waiter) { @@ -1531,6 +1801,7 @@ impl Session { if let Some((_, tx)) = self.gateway.take() { let _ = tx.send(GatewayCmd::Stop); } + self.gateway_observed = None; if let Some((_, tx)) = self.query.take() { let _ = tx.send(QueryCmd::Stop); } @@ -1643,6 +1914,7 @@ impl Session { if let Some((url, ..)) = &self.banner_reload && *url == address && self.settings.current().get(&CACHE_FETCH_IMAGES) + && !self.picture_host_busy(url) { self.fetch_picture(url, true); } @@ -1661,6 +1933,13 @@ impl Session { } self.learn_server_uid(server_uid, Source::Voice); self.emit_state(); + // The server knows our identity now: a gateway that could not + // log us in before (on a server we never joined) tries at once. + if self.state.observe == ObserveState::Connecting + && let Some((_, tx)) = &self.gateway + { + let _ = tx.send(GatewayCmd::RetryNow); + } let capabilities = flavor.capabilities(); if capabilities.streams && let Some((generation, voice)) = &self.voice @@ -1773,7 +2052,7 @@ impl Session { fn gateway_event(&mut self, e: GatewayEvent) { match e { - GatewayEvent::Connected(client) => { + GatewayEvent::Connected(client, url) => { self.state.observe = ObserveState::Observing; let info = client.info().clone(); self.gateway_client = Some(client.clone()); @@ -1783,6 +2062,7 @@ impl Session { self.learn_server_uid(info.server_uid.clone(), Source::Gateway); self.emit_state(); self.gateway_update(GatewayUpdate::Connected { + url, gateway_id: info.gateway_id, server_uid: info.server_uid, server_name: info.server_name, @@ -1809,6 +2089,7 @@ impl Session { } GatewayEvent::Disconnected(reason) => { self.gateway = None; + self.gateway_observed = None; self.gateway_gone(reason.clone()); self.gateway_presence = None; self.state.observe = ObserveState::Off; @@ -1981,6 +2262,7 @@ impl Session { self.emit_state(); } self.fetch_pictures(&presence); + self.fetch_myts_avatars(&presence); let presence = Arc::new(presence); self.contacts.presence(self.id, presence.clone()); self.emit(Event::Presence { session: self.id, presence }); @@ -2009,7 +2291,17 @@ mod banner_tests { // No myTeamSpeak account; its source stays open, as the engine's does // (a closed one ends voice connections). let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); - (Session::new(1, events, frames, AudioSettings::default(), shared, myts_identity), receiver) + let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe(); + let session = Session::new( + 1, + events, + frames, + AudioSettings::default(), + shared, + myts_identity, + myts_data, + ); + (session, receiver) } #[tokio::test] @@ -2185,6 +2477,143 @@ mod banner_tests { let _ = std::fs::remove_dir_all(cache.dir()); } + #[test] + fn banners_keep_trying_avatars_and_icons_give_up() { + let banner = ImageRequest::Picture("https://example.com/b.png".into()); + let delay = |f, hint, gone| retry_delay(&banner, f, hint, gone).map(|d| d.as_secs()); + let delays: Vec<_> = + (1..=8).map(|f| delay(f, RetryHint::Default, false).unwrap()).collect(); + assert_eq!(delays, [1, 4, 16, 60, 300, 900, 900, 900]); + // An address wrong or gone: after 15 minutes, then every hour. + assert_eq!(delay(1, RetryHint::Permanent, false), Some(900)); + assert_eq!(delay(2, RetryHint::Permanent, true), Some(3600)); + // A busy host: when it says. + assert_eq!(delay(1, RetryHint::After(Duration::from_secs(120)), false), Some(120)); + let icon = ImageRequest::Icon(1234); + let delays: Vec<_> = (1..=4) + .map(|f| retry_delay(&icon, f, RetryHint::Default, false).map(|d| d.as_secs())) + .collect(); + assert_eq!(delays, [Some(1), Some(4), Some(16), None]); + // So does a chat picture, not shown as a banner. + let chat = ImageRequest::ChatPicture("https://example.com/b.png".into()); + assert_eq!(retry_delay(&chat, 3, RetryHint::Default, false), Some(Duration::from_secs(16))); + assert_eq!(retry_delay(&chat, 4, RetryHint::Permanent, false), None); + } + + /// A banner whose address is wrong or gone is tried again after 15 + /// minutes, then every hour, until the connection is made again; a + /// busy host's banner waits as long as it asks, and so do its reloads. + #[tokio::test] + async fn banners_wait_as_their_hosts_say() { + let (mut session, _events) = session("hints"); + let url = "https://example.com/gone.png"; + let request = ImageRequest::Picture(url.into()); + let wait = |session: &Session, request: &ImageRequest| { + let due = session.image_retries[request].due.unwrap(); + due.saturating_duration_since(Instant::now()).as_secs_f64().round() as u64 + }; + let gone = || Err(FetchError::new("HTTP 404 Not Found", RetryHint::Permanent)); + session.pictures.insert(url.into()); + session.image_finished(false, session.image_epoch, request.clone(), gone()); + assert_eq!(wait(&session, &request), 900); + assert!(session.image_retries[&request].gone); + session.image_finished(false, session.image_epoch, request.clone(), gone()); + assert_eq!(wait(&session, &request), 3600); + // Something else in between: the usual schedule. + let failed = Err("timed out".into()); + session.image_finished(false, session.image_epoch, request.clone(), failed); + assert_eq!(wait(&session, &request), 16); + // Connected again: from the start. + session.forget_images(); + session.pictures.insert(url.into()); + session.image_finished(false, session.image_epoch, request.clone(), gone()); + assert_eq!(wait(&session, &request), 900); + + // The host banner of a busy host: its reloads wait too. + let banner = "https://example.com/busy.png"; + let request = ImageRequest::Picture(banner.into()); + session.pictures.insert(banner.into()); + let timer = tokio::spawn(async {}).abort_handle(); + session.banner_reload = Some((banner.into(), 60, timer)); + let busy = FetchError::new("HTTP 429", RetryHint::After(Duration::from_secs(600))); + session.image_finished(false, session.image_epoch, request.clone(), Err(busy)); + assert_eq!(wait(&session, &request), 600); + let cache = session.cache.current(); + let key = cache::picture_key(banner).unwrap(); + // Downloaded here, so a fetch by the session waits for this one. + let reload = |session: &mut Session| { + let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(|_| {})) else { + panic!("own download"); + }; + session.source_event(SourceEvent::ReloadBanner(banner.into())); + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(&temp, b"picture").unwrap(); + cache.finish(&key, &temp, Ok(()), 0); + session.sources_rx.as_mut().unwrap().try_recv().is_ok() + }; + assert!(!reload(&mut session), "reloaded while its host is busy"); + session.image_retries.get_mut(&request).unwrap().due = Some(Instant::now()); + assert!(reload(&mut session), "not reloaded once the wait was over"); + std::fs::remove_dir_all(cache.dir()).unwrap(); + } + + /// What a failed download of `request` logs at info. + fn failure_lines( + session: &mut Session, + request: &ImageRequest, + result: Result, + ) -> 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"); @@ -2200,7 +2629,8 @@ mod banner_tests { ); let retry = &session.image_retries[&request]; assert_eq!(retry.failures, failure); - assert_eq!(retry.due.is_some(), failure <= 3); + // A banner is tried again while it is shown. + assert!(retry.due.is_some()); } assert!(events.try_recv().is_err()); // Disabling fetch invalidates pending retries and completions. @@ -2317,6 +2747,82 @@ mod banner_tests { std::fs::remove_dir_all(cache.dir()).unwrap(); } + /// myTeamSpeak avatars (TeamSpeak 6) come from the web where the + /// server's avatar is not shown: none set, no voice connection to get it + /// over (observing), or its download gave up. + #[tokio::test] + async fn myts_avatars_where_the_servers_is_not_shown() { + let (mut session, mut events) = session("myts-avatar"); + let cache = session.cache.current(); + let client = |id, uid: &str, avatar: Option<&str>, myts: &str| voelin_model::ClientInfo { + id, + uid: Some(uid.into()), + avatar: avatar.map(Into::into), + myts_avatar: Some(myts.into()), + ..Default::default() + }; + let (a, b) = ("https://a.example.test/a.png", "https://a.example.test/b.png"); + let hash = "0123456789abcdef0123456789abcdef"; + let mut presence = Presence::default(); + presence.clients.insert(1, client(1, "A=", None, a)); + presence.clients.insert(2, client(2, "B=", Some(hash), b)); + // Owned here, so nothing goes to the network. + let temps: Vec<_> = [a, b] + .iter() + .map(|url| { + let key = cache::picture_key(url).unwrap(); + let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else { + panic!("first download"); + }; + (key, temp) + }) + .collect(); + // Observing: both, even the one with a server avatar. + session.gateway_presence = Some(presence.clone()); + session.publish_presence(); + assert_eq!(session.myts_avatars.len(), 2); + for (key, temp) in &temps { + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(temp, b"\x89PNG\r\n\x1a\npicture").unwrap(); + cache.finish(key, temp, Ok(()), 0); + let done = session.sources_rx.as_mut().unwrap().recv().await.unwrap(); + session.source_event(done); + } + let mut ready = Vec::new(); + while let Ok(event) = events.try_recv() { + if let Event::AvatarReady { client_uid, hash, .. } = event { + ready.push((client_uid, hash)); + } + } + ready.sort(); + assert_eq!(ready, [("A=".to_owned(), a.to_owned()), ("B=".to_owned(), b.to_owned())]); + // With voice the server's avatar is shown where there is one. + let (tx, _rx) = mpsc::unbounded_channel(); + session.voice = Some((1, tx)); + session.voice_presence = Some(presence.clone()); + session.publish_presence(); + assert_eq!(session.myts_avatars.keys().collect::>(), ["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"); @@ -2463,4 +2969,26 @@ mod banner_tests { assert_eq!(sent(), [(vec![], -30.0)]); session.stop_all(); } + + #[tokio::test] + async fn voice_connected_wakes_a_gateway_still_connecting() { + let (mut session, _events) = session("gateway-wake"); + let (tx, mut rx) = mpsc::unbounded_channel(); + session.gateway = Some((session.next_generation(), tx)); + let connected = || VoiceEvent::Connected { + name: "test".into(), + flavor: voelin_model::ServerFlavor::Unknown(String::new()), + own_client: 1, + server_uid: "server=".into(), + own_uid: None, + }; + session.state.observe = ObserveState::Connecting; + session.voice_event(connected()); + assert!(matches!(rx.try_recv(), Ok(GatewayCmd::RetryNow))); + assert!(rx.try_recv().is_err()); + // Logged in already: nothing to hurry. + session.state.observe = ObserveState::Observing; + session.voice_event(connected()); + assert!(rx.try_recv().is_err()); + } } diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 980b736..10996bb 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1121,8 +1121,8 @@ 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, banners and badges of servers we are on, diff --git a/crates/voelin-core/src/voice.rs b/crates/voelin-core/src/voice.rs index 00534de..898355a 100644 --- a/crates/voelin-core/src/voice.rs +++ b/crates/voelin-core/src/voice.rs @@ -76,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, @@ -231,8 +233,35 @@ fn now_ms() -> i64 { .unwrap_or_default() } +/// What `client_user_tag` is to be set to, if anything: on servers that +/// know it (`user_tags`), the tag `wanted` where `shown` is another (or +/// none), or `again` after a new account proof; empty (cleared) where one +/// is shown that is no longer wanted. +fn user_tag_update( + wanted: Option<&tsclientlib::UserTag>, + shown: Option<&tsclientlib::UserTag>, + user_tags: bool, + again: bool, + now_ms: i64, +) -> Option { + 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), @@ -242,6 +271,16 @@ enum Input { /// A command waiting for the server's answer. enum Pending { MytsIdentity(Instant), + /// `updatemytsdata`: whether it showed the avatar and the badges (else + /// it cleared them), and the ids of the badges shown; what the server + /// published is only logged. + MytsData { + avatar: Option, + badges: Option, + badge_ids: Vec, + }, + /// `clientupdate client_user_tag`: the value (empty: cleared); only logged. + UserTag(String), Stream(Request), FileList { request: RequestId, @@ -300,17 +339,21 @@ impl Job { } } -/// How long a picture of `size` bytes may take to arrive: half a minute, -/// plus its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on -/// slow links while a stalled transfer still ends. +/// How long a picture of `size` bytes may take to arrive: a minute, plus +/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow +/// links while a stalled transfer still ends. fn image_download_time(size: u64) -> Duration { - Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE) + Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE) } +/// How long the server may take to start an image transfer (a busy server +/// answers the requests of a large channel tree in turn). +const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30); + /// Bound background image handshakes without imposing a deadline on user transfers. fn expire_image_jobs(jobs: &mut HashMap, now: Instant) { jobs.retain(|_, job| { - if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= Duration::from_secs(15)) { + if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) { job.report()(TransferState::Failed("image transfer negotiation timed out".into())); false } else { @@ -350,6 +393,12 @@ struct Voice { pending: HashMap, 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( @@ -382,6 +431,7 @@ async fn run_inner( builder = builder.default_token(token.clone()); } let mut identity = link.myts_identity.clone(); + let mut data = link.myts_data.clone(); // A changed account invalidates an in-flight handshake. Drop that connection // and take a fresh snapshot before publishing any connected state. let mut con = timeout(Duration::from_secs(30), async { @@ -449,8 +499,14 @@ async fn run_inner( pending: HashMap::new(), jobs: HashMap::new(), transfers: HashMap::new(), + myts_data_due: false, + myts_shown: tsclientlib::MytsData::default(), }; voice.publish_state()?; + // The account's avatar, badges and User Tag, for everyone on the + // server (as the official client, once connected). + data.borrow_and_update(); + voice.send_myts_data(true); let mut tick = tokio::time::interval(Duration::from_millis(250)); let result = loop { @@ -461,7 +517,9 @@ async fn run_inner( }) { break Err(anyhow::anyhow!("myTeamSpeak account update timed out")); } - let input = next_input(&mut voice.con.events(), commands, &mut tick, &mut identity).await; + let input = + next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data) + .await; match input { Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")), Input::MytsIdentityChanged => { @@ -472,6 +530,15 @@ async fn run_inner( } Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")), } + // After the proof, what is shown of the account (a sign-in): + // its change, if any, is in this one. All of it again: the + // server checks it for the myTS ID it holds when it comes. + data.borrow_and_update(); + voice.send_myts_data(true); + } + Input::MytsDataChanged => { + data.borrow_and_update(); + voice.send_myts_data(false); } Input::Item(None) => break Err(anyhow::anyhow!("connection closed")), Input::Item(Some(Err(e))) => break Err(e.into()), @@ -504,6 +571,7 @@ async fn next_input( commands: &mut mpsc::UnboundedReceiver, tick: &mut tokio::time::Interval, identity: &mut watch::Receiver>>, + data: &mut watch::Receiver>>, ) -> Input { tokio::select! { biased; @@ -512,6 +580,11 @@ async fn next_input( } else { Input::AccountSourceClosed }, + changed = data.changed() => if changed.is_ok() { + Input::MytsDataChanged + } else { + Input::AccountSourceClosed + }, input = async { // Keep account changes first without starving network or timers when // the audio command queue remains ready. @@ -578,6 +651,10 @@ impl Voice { self.message(target, invoker, message); } } + // Connected again after a reconnect. + if self.myts_data_due { + self.send_myts_data(true); + } self.publish_state()?; } StreamItem::Audio(packet) => { @@ -660,6 +737,9 @@ impl Voice { } StreamItem::DisconnectedTemporarily(reason) => { warn!(?reason, "voice connection interrupted, reconnecting"); + // A new client on the server: it shows nothing of the account. + self.myts_data_due = true; + self.myts_shown = tsclientlib::MytsData::default(); } _ => {} } @@ -825,6 +905,30 @@ impl Voice { } } Pending::Quiet | Pending::MytsIdentity(_) => {} + Pending::MytsData { avatar, badges, badge_ids } => match result { + Ok(()) => self.myts_published(avatar, badges, &badge_ids), + Err(TsError::ParameterInvalid) => warn!( + "the server refused the account's myTeamSpeak certificate (error 1538): it \ + is expired, revoked or not a myTeamSpeak signing certificate, or the \ + server could not load myTeamSpeak's revocation list" + ), + Err(e) => warn!(error = %e, "the server refused the account's avatar or badges"), + }, + Pending::UserTag(value) => match result { + Ok(()) => { + let own = self.con.get_state().ok().and_then(|state| { + state.clients.get(&state.own_client).and_then(|c| c.user_tag.clone()) + }); + if value.is_empty() { + info!("the server no longer shows a User Tag for the account"); + } else if own.as_deref() == Some(value.as_str()) { + info!("the server shows the account's User Tag"); + } else { + warn!("the server took the account's User Tag but shows another value"); + } + } + Err(e) => warn!(error = %e, "the server refused the account's User Tag"), + }, Pending::Report(what) => { if let Err(e) = result { let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}"))); @@ -833,6 +937,129 @@ impl Voice { } } + /// What is to be shown of the account on this connection: what the UI + /// gave, when it is for the myTS ID this connection presents; nothing + /// without one (signed out). + fn myts_wanted(&self) -> tsclientlib::MytsData { + let identity = self.link.myts_identity.borrow(); + let data = self.link.myts_data.borrow(); + match (identity.as_deref(), data.as_deref()) { + (Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(), + _ => tsclientlib::MytsData::default(), + } + } + + /// Whether the server knows the User Tag (TeamSpeak 6: it names + /// `client_user_tag` for our client, protocol 8 on). + fn has_user_tags(&self) -> bool { + self.con.get_state().is_ok_and(|state| { + state.server.protocol_version >= 8 + || state.clients.get(&state.own_client).is_some_and(|c| c.user_tag.is_some()) + }) + } + + /// Show the server the account's avatar, badges and User Tag where it + /// shows something else (`updatemytsdata`, `clientupdate`), or clear + /// them; `again`: all of it, after a new account proof. While + /// reconnecting, once connected again. + fn send_myts_data(&mut self, again: bool) { + self.myts_data_due = false; + if self.con.get_state().is_err() { + self.myts_data_due = true; + return; + } + let mut wanted = self.myts_wanted(); + let user_tags = self.has_user_tags(); + if !user_tags { + wanted.user_tag = None; + } + for update in wanted.updates(&self.myts_shown, again) { + let shows = |part: &Option>| 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); @@ -1195,10 +1422,10 @@ mod image_download_tests { }, ); } - expire_image_jobs(&mut jobs, started + Duration::from_secs(14)); + expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1)); assert_eq!(jobs.len(), 2); assert!(reports.lock().unwrap().is_empty()); - expire_image_jobs(&mut jobs, started + Duration::from_secs(15)); + expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION); assert_eq!(jobs.len(), 1); assert!(jobs.contains_key(&FiletransferHandle(2))); assert!( @@ -1210,10 +1437,10 @@ mod image_download_tests { #[test] fn large_pictures_get_time_to_arrive() { - assert_eq!(image_download_time(0), Duration::from_secs(30)); - assert_eq!(image_download_time(100 << 10), Duration::from_secs(33)); + assert_eq!(image_download_time(0), Duration::from_secs(60)); + assert_eq!(image_download_time(100 << 10), Duration::from_secs(72)); // The largest picture, at the slowest rate allowed. - assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048)); + assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384)); } } @@ -1224,6 +1451,7 @@ mod account_tests { #[tokio::test(start_paused = true)] async fn account_priority_preserves_ready_network_and_timer_progress() { let (account, mut identity) = watch::channel(None); + let (account_data, mut data) = watch::channel(None); let (commands, mut receiver) = mpsc::unbounded_channel(); for _ in 0..512 { commands.send(VoiceCmd::SetInputMuted(false)).unwrap(); @@ -1234,14 +1462,22 @@ mod account_tests { let mut tick = tokio::time::interval(Duration::from_millis(1)); account.send_replace(None); assert!(matches!( - next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await, + next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await, Input::MytsIdentityChanged )); identity.borrow_and_update(); + // What is shown of the account changes too, ahead of the rest. + account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default()))); + assert!(matches!( + next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await, + Input::MytsDataChanged + )); + data.borrow_and_update(); let (mut network, mut timers, mut audio) = (0, 0, 0); for _ in 0..512 { tokio::time::advance(Duration::from_millis(1)).await; - match next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await { + match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await + { Input::Item(_) => network += 1, Input::Tick => timers += 1, Input::Cmd(_) => audio += 1, @@ -1251,6 +1487,130 @@ mod account_tests { assert!(network > 0 && timers > 0 && audio > 0); } + fn account_data(myts_id: &[u8]) -> tsclientlib::MytsData { + let signed = |data: &[u8]| tsclientlib::Signed { certificate: vec![1], data: data.into() }; + tsclientlib::MytsData { + myts_id: myts_id.to_vec(), + avatar: signed(b"avatar"), + badges: signed(b"badges"), + badge_ids: vec!["b1".into()], + user_tag: Some(tsclientlib::UserTag { + tag: "a@myteamspeak.com".into(), + token: vec![2], + }), + } + } + + /// The User Tag is set where it is not shown yet, or after a new account + /// proof, and cleared where it is no longer wanted: on TeamSpeak 6 + /// servers only. + #[test] + fn the_user_tag_is_set_where_it_changed() { + let tag = |tag: &str| tsclientlib::UserTag { tag: tag.into(), token: vec![2] }; + let (a, b) = (tag("a@myteamspeak.com"), tag("b@myteamspeak.com")); + let update = + |wanted, shown, user_tags, again| user_tag_update(wanted, shown, user_tags, again, 5); + let set = Some(a.value(5)); + assert!(set.as_deref().unwrap().starts_with(r#"{"myts_token":"Ag==","tag":"a@"#)); + assert_eq!(update(Some(&a), None, true, false), set); + assert_eq!(update(Some(&a), Some(&a), true, false), None, "unchanged"); + assert_eq!(update(Some(&a), Some(&a), true, true), set, "after a new account proof"); + assert_eq!(update(Some(&a), Some(&b), true, false), set, "another tag"); + assert_eq!(update(None, Some(&a), true, false).as_deref(), Some(""), "cleared"); + assert_eq!(update(None, Some(&a), true, true).as_deref(), Some("")); + assert_eq!(update(None, None, true, true), None, "nothing to clear"); + // Not a TeamSpeak 6 server: nothing, set or cleared. + assert_eq!(update(Some(&a), None, false, true), None); + assert_eq!(update(None, Some(&a), false, false), None); + } + + /// The server publishes the ids of the badges that verified. + #[test] + fn badges_the_server_dropped_are_named() { + let sent: Vec = ["b1", "b2", "b3"].map(String::from).to_vec(); + assert!(badges_dropped(&sent, "b1,b2,b3").is_empty()); + assert!(badges_dropped(&sent, "b3,b1,b2").is_empty()); + assert_eq!(badges_dropped(&sent, "b1,b3"), ["b2"]); + assert_eq!(badges_dropped(&sent, ""), ["b1", "b2", "b3"]); + assert!(badges_dropped(&[], "b1").is_empty()); + } + + /// A voice source that never connects (a silent UDP peer) presenting + /// the account with myTS ID `[1; 33]`, told to show `data`. + fn unconnected(server: &tokio::net::UdpSocket, data: tsclientlib::MytsData) -> Voice { + // Scalar one and the standard compressed Edwards base point. + let mut private = [0; 32]; + private[0] = 1; + let mut public = [0x66; 32]; + public[0] = 0x58; + let identity = + tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(); + let (events, _) = broadcast::channel(8); + let link = VoiceLink { + session: 1, + events, + settings: SharedSettings::new(crate::settings::Settings::default()), + myts_identity: watch::channel(Some(Arc::new(identity))).1, + myts_data: watch::channel(Some(Arc::new(data))).1, + }; + Voice { + con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(), + link, + events: mpsc::unbounded_channel().0, + server_uid: String::new(), + talking: HashMap::new(), + pending: HashMap::new(), + jobs: HashMap::new(), + transfers: HashMap::new(), + myts_data_due: false, + myts_shown: tsclientlib::MytsData::default(), + } + } + + /// A reconnect (tsclientlib's own) leaves the server without the + /// account's avatar: it goes again once connected, not before. + #[tokio::test] + async fn account_data_waits_for_the_connection() { + let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let mut voice = unconnected(&server, account_data(&[1; 33])); + voice.send_myts_data(true); + assert!(voice.myts_data_due && voice.pending.is_empty()); + assert_eq!(voice.myts_shown, tsclientlib::MytsData::default(), "nothing shown yet"); + voice.myts_data_due = false; + voice.myts_shown = account_data(&[1; 33]); + let reconnecting = tsclientlib::TemporaryDisconnectReason::Timeout("test"); + voice.item(StreamItem::DisconnectedTemporarily(reconnecting)).unwrap(); + assert!(voice.myts_data_due); + assert_eq!( + voice.myts_shown, + tsclientlib::MytsData::default(), + "a new client shows nothing" + ); + // Not connected yet: still due. + let _ = voice.item(StreamItem::BookEvents(Vec::new())); + assert!(voice.myts_data_due && voice.pending.is_empty()); + timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap(); + } + + /// Only what is signed for the myTS ID the connection presents is shown. + #[tokio::test] + async fn account_data_is_for_the_presented_myts_id() { + let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let voice = unconnected(&server, account_data(&[1; 33])); + assert_eq!(voice.myts_wanted(), account_data(&[1; 33])); + let other = unconnected(&server, account_data(&[2; 33])); + assert_eq!(other.myts_wanted(), tsclientlib::MytsData::default()); + let mut signed_out = unconnected(&server, account_data(&[1; 33])); + signed_out.link.myts_identity = watch::channel(None).1; + assert_eq!(signed_out.myts_wanted(), tsclientlib::MytsData::default()); + for voice in [voice, other, signed_out] { + timeout(Duration::from_millis(100), shutdown_connection(voice.con)) + .await + .unwrap() + .unwrap(); + } + } + #[tokio::test] async fn shutdown_never_polls_a_connecting_connection() { let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); @@ -1276,6 +1636,7 @@ mod account_tests { events, settings: SharedSettings::new(crate::settings::Settings::default()), myts_identity: identity, + myts_data: watch::channel(None).1, }; let (_commands, commands) = mpsc::unbounded_channel(); let (events, mut received) = mpsc::unbounded_channel(); diff --git a/crates/voelin-core/src/web.rs b/crates/voelin-core/src/web.rs index e2ef9a4..a806ab3 100644 --- a/crates/voelin-core/src/web.rs +++ b/crates/voelin-core/src/web.rs @@ -1,67 +1,347 @@ //! Pictures from the web: the host banner and TeamSpeak 6 channel banners, -//! which servers give as `http(s)` addresses on any host, and the pictures -//! of the clients' badges on TeamSpeak's server -//! ([`voelin_model::badges::icon_url`]). +//! 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; `max_bytes`: -/// the picture's size at most (up to [`cache::MAX_PICTURE_BYTES`]). -pub(crate) fn fetch( +/// 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, - max_bytes: u64, + limits: Limits, waiter: Waiter, ) { let Some(key) = cache::picture_key(url) else { @@ -69,12 +349,12 @@ pub(crate) fn fetch( return; }; let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return }; - let url = url.to_owned(); - let limits = Limits { max_bytes: max_bytes.min(LIMITS.max_bytes), ..LIMITS }; + // 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); }); } @@ -88,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())?; } @@ -111,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()); @@ -120,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]; @@ -176,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" => { @@ -192,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"; @@ -217,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 { @@ -235,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; @@ -267,34 +1233,216 @@ mod tests { Box::new(move |r| tx.send(r).unwrap()) }; let url = format!("{base}/banner"); - let max = cache::MAX_PICTURE_BYTES; - fetch(cache.clone(), &url, false, 0, max, waiter(&tx)); + fetch(cache.clone(), &url, false, 0, waiter(&tx)); let path = tokio::task::spawn_blocking(move || rx.recv().unwrap()).await.unwrap().unwrap(); assert_eq!(path, dir.join(cache::picture_key(&url).unwrap())); assert_eq!(std::fs::read(&path).unwrap(), PNG); // Not on the web: refused at once, nothing cached. let (tx, rx) = mpsc::channel(); - fetch(cache.clone(), "file:///etc/hostname", false, 0, max, waiter(&tx)); - assert!(rx.recv().unwrap().unwrap_err().contains("http")); + fetch(cache.clone(), "file:///etc/hostname", false, 0, waiter(&tx)); + 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, max, waiter(&tx)); + 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(cache.clone(), &format!("{base}/big"), false, 0, 1000, waiter(&tx)); + 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().contains("larger")); + 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(); } @@ -306,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 { @@ -345,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(); @@ -355,7 +1508,6 @@ mod tests { &format!("{base}/{path}"), false, 0, - cache::MAX_PICTURE_BYTES, Box::new(move |r| { completed.send(r).unwrap(); }), @@ -364,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)); @@ -392,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/main.rs b/crates/voelin-ui/src/main.rs index 3259200..ad7545e 100644 --- a/crates/voelin-ui/src/main.rs +++ b/crates/voelin-ui/src/main.rs @@ -40,6 +40,12 @@ fn main() -> Result<()> { ), Err(error) => tracing::warn!(%error, "no log file this time"), } + // Banners go through the proxy the desktop's settings name (GNOME, KDE), + // as a browser's requests do; Windows and macOS settings are read anyway. + #[cfg(all(unix, not(any(target_os = "macos", target_os = "android"))))] + voelin_core::set_proxy_resolver( + |url| async move { voelin_platform::proxy::proxy_for(&url).await }, + ); let options = voelin_ui::RunOptions { setting_overrides: setting_overrides(std::env::args().skip(1)), ..Default::default() diff --git a/crates/voelin-ui/src/messages.rs b/crates/voelin-ui/src/messages.rs index e8674e8..5a3ceef 100644 --- a/crates/voelin-ui/src/messages.rs +++ b/crates/voelin-ui/src/messages.rs @@ -82,12 +82,9 @@ impl App { } self.social.dm.bookmark_of.clear(); for b in &self.bookmarks { - for alias in [ - Some(format!("voice:{}", b.address)), - b.gateway_url.as_ref().map(|u| format!("gateway:{u}")), - ] - .into_iter() - .flatten() + let gateways = b.gateways().into_iter().chain(b.gateway_url.clone()); + for alias in std::iter::once(format!("voice:{}", b.address)) + .chain(gateways.map(|url| format!("gateway:{url}"))) { if let Ok(Some(uid)) = self.store.server_alias(&alias) { self.social.dm.bookmark_of.insert(uid, b.id); diff --git a/crates/voelin-ui/src/myts.rs b/crates/voelin-ui/src/myts.rs index af7739d..81e1e48 100644 --- a/crates/voelin-ui/src/myts.rs +++ b/crates/voelin-ui/src/myts.rs @@ -1,12 +1,16 @@ //! Desktop account state. Only the UI thread mutates state or persists credentials. use serde::{Deserialize, Serialize}; use slint::{ComponentHandle, ModelRc, SharedString, VecModel}; +use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; -use voelin_myts::{Client, Login, Profile, ServerIdentity, SessionToken}; +use std::time::Duration; +use voelin_myts::{ + Client, Login, OwnAvatar, Presentation, Profile, ServerIdentity, SessionToken, SignedBadge, +}; use voelin_store::Secrets; -use crate::app::{App, Bridge, MytsForm, later}; +use crate::app::{App, Bridge, MytsBadge, MytsForm, later}; // One keyring item makes session replacement atomic: a failed write cannot // combine a new session with another account's renewal material. @@ -50,6 +54,85 @@ struct SavedProfile { /// The account's avatar picture, in the account directory. const AVATAR_FILE: &str = "avatar"; +/// What servers are shown of the account ([`SavedPresentation`]), in the +/// account directory: public data, so not in the keyring (whose items are +/// small on some systems). +const PRESENTATION_FILE: &str = "presentation.json"; +/// The badges chosen to show on servers, per account (`{account: [badge +/// id]}`), in the account directory: kept across sign-outs. +const BADGES_FILE: &str = "badges.json"; +/// Servers are shown at most this many badges, as the official client +/// shows them. +const MAX_SHOWN_BADGES: usize = 3; +/// A User Tag's token is asked for again when it holds for less than this. +const USER_TAG_MARGIN: i64 = 3 * 86_400; +/// While signed in, what servers are shown is asked for again this often +/// (certificates and tokens expire; the avatar may change elsewhere). +const PRESENTATION_REFRESH: Duration = Duration::from_secs(86_400); + +/// [`PRESENTATION_FILE`]: whose it is, and what myTeamSpeak handed out for +/// it, as it came (public data: certificates, signatures, links, ids). +#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +struct SavedPresentation { + uuid: String, + /// What the last password sign-in brought ([`Presentation`]). + certificate: Vec, + avatar: Vec, + /// What myTeamSpeak's avatar service hands out for the account's myTS + /// ID ([`OwnAvatar`]): no password needed. + #[serde(default)] + service_certificate: Vec, + #[serde(default)] + service_avatar: Vec, + /// The account's badges as signed for its myTS ID (`SignedUserBadge`s). + #[serde(default)] + badges: Vec>, + /// The primary User Tag, and the token that proves it. + #[serde(default)] + user_tag: String, + #[serde(default)] + user_tag_token: Vec, +} + +/// What asking myTeamSpeak again learned; `None`: nothing (an empty or +/// failed answer), and what was known stays. +#[derive(Default)] +struct Fetched { + avatar: Option, + badges: Option>, + user_tag: Option, + /// Checked for the tag before it is taken. + user_tag_token: Option>, +} + +impl SavedPresentation { + fn merge(&mut self, fetched: Fetched) { + if let Some(own) = fetched.avatar { + self.service_certificate = own.certificate; + self.service_avatar = own.avatar; + } + if let Some(badges) = fetched.badges { + self.badges = badges.iter().map(|b| b.raw().to_vec()).collect(); + } + if let Some(tag) = fetched.user_tag { + self.user_tag = tag; + } + if let Some(token) = fetched.user_tag_token { + self.user_tag_token = token; + } + } + + fn signed_badges(&self) -> Vec { + self.badges.iter().filter_map(|raw| SignedBadge::parse(raw)).collect() + } +} + +/// Now, Unix seconds. +fn unix_now() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) +} /// A date (Unix seconds) as the profile shows it; empty when not known. fn date(seconds: i64) -> String { @@ -97,6 +180,11 @@ pub(crate) struct Account { /// The avatar, decoded. avatar: slint::Image, saved: Option, + /// What servers can be shown of the account: from a password sign-in, + /// and from myTeamSpeak with the session alone. + presentation: Option, + /// The ids of the badges chosen to show on servers, in order. + shown_badges: Vec, signed_in: bool, busy: bool, /// The saved session is being checked (not a password sign-in). @@ -121,6 +209,223 @@ impl Account { self.dir.as_ref().map(|dir| dir.join(AVATAR_FILE)) } + fn presentation_path(&self) -> Option { + self.dir.as_ref().map(|dir| dir.join(PRESENTATION_FILE)) + } + + fn badges_path(&self) -> Option { + self.dir.as_ref().map(|dir| dir.join(BADGES_FILE)) + } + + /// The kept presentation and badge choice, if they are the saved + /// account's. + fn load_presentation(&mut self) { + let uuid = self.saved.as_ref().map(|s| s.uuid.clone()).unwrap_or_default(); + self.presentation = self + .presentation_path() + .and_then(|path| std::fs::read(path).ok()) + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|kept| !uuid.is_empty() && kept.uuid == uuid); + self.load_badge_choice(&uuid); + } + + fn save_presentation(&self) { + let (Some(path), Some(kept)) = (self.presentation_path(), self.presentation.as_ref()) + else { + return; + }; + let written = serde_json::to_vec(kept).map_err(std::io::Error::other).and_then(|json| { + path.parent().map_or(Ok(()), std::fs::create_dir_all)?; + std::fs::write(&path, json) + }); + if let Err(error) = written { + tracing::warn!(%error, "could not keep what servers are shown of the account"); + } + } + + /// The kept presentation if it is `uuid`'s, else a new one. + fn presentation_for(&mut self, uuid: &str) -> &mut SavedPresentation { + if self.presentation.as_ref().is_none_or(|kept| kept.uuid != uuid) { + self.presentation = + Some(SavedPresentation { uuid: uuid.to_owned(), ..Default::default() }); + } + self.presentation.as_mut().expect("just set") + } + + /// A sign-in's presentation, kept for the next start. + fn set_presentation(&mut self, uuid: &str, presentation: Presentation) { + let kept = self.presentation_for(uuid); + kept.certificate = presentation.certificate; + kept.avatar = presentation.avatar; + self.save_presentation(); + } + + /// What asking myTeamSpeak again learned for the account `uuid`; what + /// it did not learn stays as known. + fn take_fetched(&mut self, uuid: &str, fetched: Fetched) { + self.presentation_for(uuid).merge(fetched); + self.save_presentation(); + } + + fn forget_presentation(&mut self) { + self.presentation = None; + self.shown_badges.clear(); + if let Some(path) = self.presentation_path() { + let _ = std::fs::remove_file(path); + } + } + + fn badge_choices(&self) -> HashMap> { + self.badges_path() + .and_then(|path| std::fs::read(path).ok()) + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or_default() + } + + fn load_badge_choice(&mut self, uuid: &str) { + self.shown_badges = self.badge_choices().remove(uuid).unwrap_or_default(); + } + + /// Show the badge at `index` (of the signed badges) on servers, or not: + /// at most [`MAX_SHOWN_BADGES`], in the order chosen, kept per account. + /// The choice kept is then what the list shows: a chosen badge + /// myTeamSpeak no longer lists is dropped from it. + fn choose_badge(&mut self, index: usize, on: bool) -> bool { + let Some(account) = self.saved.as_ref().map(|s| s.uuid.clone()) else { return false }; + let badges = self.presentation.as_ref().map(SavedPresentation::signed_badges); + let Some(badge) = badges.unwrap_or_default().into_iter().nth(index) else { + return false; + }; + let mut chosen: Vec = self.chosen_badges().into_iter().map(|b| b.uuid).collect(); + let shown = chosen.contains(&badge.uuid); + if on == shown || (on && chosen.len() >= MAX_SHOWN_BADGES) { + return false; + } + if on { + chosen.push(badge.uuid); + } else { + chosen.retain(|uuid| *uuid != badge.uuid); + } + self.shown_badges = chosen; + if let Some(path) = self.badges_path() { + let mut choices = self.badge_choices(); + choices.insert(account, self.shown_badges.clone()); + let written = + serde_json::to_vec(&choices).map_err(std::io::Error::other).and_then(|json| { + path.parent().map_or(Ok(()), std::fs::create_dir_all)?; + std::fs::write(&path, json) + }); + if let Err(error) = written { + tracing::warn!(%error, "could not keep which badges servers are shown"); + } + } + true + } + + /// The chosen badges myTeamSpeak lists, in the order chosen, as it + /// signed them: one it no longer lists takes no place (and no place of + /// the [`MAX_SHOWN_BADGES`]). + fn chosen_badges(&self) -> Vec { + let signed = self.presentation.as_ref().map(SavedPresentation::signed_badges); + let signed = signed.unwrap_or_default(); + self.shown_badges + .iter() + .filter_map(|uuid| signed.iter().find(|b| b.uuid == *uuid).cloned()) + .take(MAX_SHOWN_BADGES) + .collect() + } + + /// What voice servers are shown of the signed-in account at `now` + /// (Unix seconds), checked as a TeamSpeak 6 server and its viewers check + /// it: the newest avatar a certificate at hand verifies, the chosen + /// badges if one certificate verifies them all, the User Tag if its + /// token holds. Each with the certificate that verifies it, since the + /// server shows nothing of what it cannot verify. + fn myts_data(&self, now: i64) -> Option { + self.myts_data_from(&voelin_myts::ROOT_KEY, now) + } + + /// [`Self::myts_data`] with certificates from `root` (tests). + fn myts_data_from(&self, root: &[u8; 32], now: i64) -> Option { + let identity = self.identity()?; + let kept = self.presentation.as_ref()?; + let id = identity.id_bytes(); + // The certificates at hand, and where they came from (for the log). + let sources = ["the sign-in's", "the avatar service's", "the myTS ID's"]; + let certificates = [ + kept.certificate.as_slice(), + kept.service_certificate.as_slice(), + identity.public_signature_certificate(), + ]; + let avatars = [kept.avatar.as_slice(), kept.service_avatar.as_slice()]; + let mut data = tsclientlib::MytsData { myts_id: id.to_vec(), ..Default::default() }; + match voelin_myts::choose_avatar_from(root, &avatars, &certificates, id, now) { + // The newest avatar has no pictures: the account has none now. + Some((avatar, _)) if !voelin_myts::avatar_has_pictures(avatars[avatar]) => { + tracing::info!("servers are shown no avatar: the account has none") + } + Some((avatar, certificate)) => { + tracing::info!( + avatar = ["from the sign-in", "from the avatar service"][avatar], + certificate = sources[certificate], + "servers are shown the account's avatar" + ); + data.avatar = tsclientlib::Signed { + certificate: certificates[certificate].to_vec(), + data: avatars[avatar].to_vec(), + }; + } + None if avatars.iter().all(|a| a.is_empty()) => { + tracing::info!("servers are shown no avatar: myTeamSpeak has not handed one out") + } + None => tracing::info!( + "servers are shown no avatar: no certificate at hand verifies it (expired, or \ + another key)" + ), + } + let badges = self.chosen_badges(); + let badges: Vec<&SignedBadge> = badges.iter().collect(); + if !badges.is_empty() { + match voelin_myts::choose_badges_certificate_from(root, &badges, &certificates, id, now) + { + Some(certificate) => { + data.badge_ids = badges.iter().map(|b| b.uuid.clone()).collect(); + tracing::info!( + badges = ?data.badge_ids, + certificate = sources[certificate], + "servers are shown the chosen badges" + ); + data.badges = tsclientlib::Signed { + certificate: certificates[certificate].to_vec(), + data: voelin_myts::badge_list(badges), + }; + } + None => tracing::info!( + "servers are shown no badges: no certificate at hand verifies all the chosen \ + ones" + ), + } + } + if !kept.user_tag.is_empty() { + if kept.user_tag_token.is_empty() { + tracing::info!("servers are shown no User Tag: myTeamSpeak has not sent its token"); + } else { + let token = &kept.user_tag_token; + match voelin_myts::check_user_tag_from(root, token, &kept.user_tag, id, now) { + Ok(_) => { + tracing::info!(tag = %kept.user_tag, "servers are shown the account's User Tag"); + data.user_tag = Some(tsclientlib::UserTag { + tag: kept.user_tag.clone(), + token: kept.user_tag_token.clone(), + }); + } + Err(error) => tracing::info!(%error, "servers are shown no User Tag"), + } + } + } + Some(data) + } + /// The kept picture, shown while the session is checked. fn load_avatar(&mut self) { let bytes = self.avatar_path().and_then(|path| std::fs::read(path).ok()); @@ -163,6 +468,7 @@ impl Account { if self.saved.is_some() { self.load_avatar(); } + self.load_presentation(); self.can_forget = false; self.status = 0; self.persistence_status = 0; @@ -202,6 +508,12 @@ impl Account { if same_account { self.saved.take().unwrap().profile } else { SavedProfile::default() }; if !same_account { self.forget_avatar(); + self.forget_presentation(); + self.load_badge_choice(&login.uuid); + } + // A sign-in without it keeps the same account's known one. + if !login.presentation.is_empty() { + self.set_presentation(&login.uuid, login.presentation); } profile.update(&login.profile); let saved = Saved { @@ -258,6 +570,21 @@ impl Account { items.into_iter().map(SharedString::from).collect::>(), )) }; + let signed = self.presentation.as_ref().map(SavedPresentation::signed_badges); + let chosen: Vec = self.chosen_badges().into_iter().map(|b| b.uuid).collect(); + let full = chosen.len() >= MAX_SHOWN_BADGES; + let badge_choice = signed + .unwrap_or_default() + .into_iter() + .map(|badge| { + let place = chosen.iter().position(|uuid| *uuid == badge.uuid); + MytsBadge { + name: badge.name.into(), + shown: place.map_or(0, |place| place as i32 + 1), + can_change: place.is_some() || !full, + } + }) + .collect::>(); MytsForm { available: true, prompt: self.prompt, @@ -270,6 +597,13 @@ impl Account { member_since: date(profile.registered).into(), last_login: date(profile.last_login).into(), badges: strings(profile.badges), + badge_choice: ModelRc::new(VecModel::from(badge_choice)), + user_tag: self + .presentation + .as_ref() + .map(|p| p.user_tag.as_str()) + .unwrap_or_default() + .into(), devices: strings(profile.devices), email: self.saved.as_ref().map(|s| s.email.as_str()).unwrap_or_default().into(), username: self.saved.as_ref().map(|s| s.username.as_str()).unwrap_or_default().into(), @@ -327,6 +661,7 @@ impl Account { self.persistence_status = if cleared { 0 } else { 8 }; self.can_forget = !cleared; self.forget_avatar(); + self.forget_presentation(); cleared } } @@ -381,6 +716,150 @@ impl App { self.engine.send(voelin_core::Command::SetMytsIdentity( self.myts.identity().cloned().map(Arc::new), )); + // What servers are shown of it, after the proof. + self.publish_myts_data(); + } + + /// What servers are shown of the account (avatar, badges, User Tag): + /// only what changed goes to them. + fn publish_myts_data(&self) { + let data = self.myts.myts_data(unix_now()); + if data.is_none() && self.myts.identity().is_some() { + tracing::info!( + "servers are shown nothing of the account but its myTS ID until myTeamSpeak \ + answers" + ); + } + self.engine.send(voelin_core::Command::SetMytsData(data.map(Arc::new))); + } + + /// Ask myTeamSpeak, with the session alone, for what servers are shown + /// of the account: its avatar and a certificate (the avatar service's + /// answer for its own myTS ID), its signed badges, its User Tag and the + /// token that proves it. After a password sign-in, a checked saved + /// session, and then daily. An empty or failed answer changes nothing. + fn refresh_myts_presentation(&self) { + let Some(saved) = self.myts.saved.as_ref().filter(|_| self.myts.signed_in) else { + return; + }; + let (Some(identity), Ok(token)) = + (self.myts.identity(), SessionToken::new(saved.session.clone())) + else { + return; + }; + if saved.uuid.is_empty() { + return; + } + let uuid = saved.uuid.clone(); + let id = identity.id_bytes().to_vec(); + let kept_token = self + .myts + .presentation + .as_ref() + .filter(|kept| kept.uuid == uuid) + .map(|kept| kept.user_tag_token.clone()) + .unwrap_or_default(); + let generation = self.myts.generation; + self.runtime.spawn(async move { + let client = match Client::new() { + Ok(client) => client, + Err(error) => return tracing::debug!(%error, "no account client"), + }; + let (avatar, badges, tag) = tokio::join!( + client.own_avatar(&token, &id), + client.signed_badges(&token), + client.user_tag(&token) + ); + let mut fetched = Fetched::default(); + match avatar { + Ok(Some(own)) => { + tracing::info!( + "myTeamSpeak's avatar service sent the account's avatar and certificate" + ); + fetched.avatar = Some(own); + } + Ok(None) => tracing::info!( + "myTeamSpeak's avatar service sent nothing for the account; what was known \ + is kept" + ), + Err(error) => { + tracing::info!(%error, "the account's avatar for servers was not fetched") + } + } + match badges { + Ok(Some(badges)) => { + tracing::info!( + count = badges.len(), + "myTeamSpeak sent the account's signed badges" + ); + fetched.badges = Some(badges); + } + Ok(None) => { + tracing::info!("myTeamSpeak sent no badge list; what was known is kept") + } + Err(error) => { + tracing::info!(%error, "the account's signed badges were not fetched") + } + } + match tag { + Ok(Some(tag)) => { + tracing::info!(%tag, "the account's primary User Tag"); + // The token proves all the account's tags; asked for again + // when it would not prove this one in a few days. + let at = unix_now() + USER_TAG_MARGIN; + if voelin_myts::check_user_tag(&kept_token, &tag, &id, at).is_err() { + match client.user_tag_token(&token).await { + Ok(token) => { + match voelin_myts::check_user_tag(&token, &tag, &id, unix_now()) { + Ok(until) => { + tracing::info!( + valid_until = until, + "myTeamSpeak sent the token for the User Tag" + ); + fetched.user_tag_token = Some(token); + } + Err(error) => tracing::info!( + %error, + "myTeamSpeak sent a token for the User Tag that viewers would not accept" + ), + } + } + Err(error) => { + tracing::info!(%error, "the User Tag's token was not fetched") + } + } + } + fetched.user_tag = Some(tag); + } + Ok(None) => tracing::info!("myTeamSpeak names no User Tag for the account"), + Err(error) => tracing::info!(%error, "the account's User Tag was not fetched"), + } + later(move |app| { + if app.myts.generation != generation || !app.myts.signed_in { + return; + } + if app.myts.saved.as_ref().is_some_and(|s| s.uuid == uuid) { + app.myts.take_fetched(&uuid, fetched); + app.publish_myts_data(); + app.refresh_myts(); + } + }); + tokio::time::sleep(PRESENTATION_REFRESH).await; + later(move |app| { + if app.myts.generation == generation { + app.refresh_myts_presentation(); + } + }); + }); + } + + /// Show a badge on servers, or not (Settings → My Account). + pub(crate) fn myts_badge(&mut self, index: i32, on: bool) { + let changed = usize::try_from(index).is_ok_and(|index| self.myts.choose_badge(index, on)); + if changed { + self.publish_myts_data(); + } + self.refresh_myts(); } pub(crate) fn refresh_myts(&self) { @@ -498,6 +977,7 @@ impl App { Ok(()) => { app.myts.restored(); app.refresh_myts_profile(); + app.refresh_myts_presentation(); } Err(error) => { app.myts.otp_required = @@ -556,6 +1036,7 @@ impl App { app.store_settings(); } app.refresh_myts_profile(); + app.refresh_myts_presentation(); } Err(error) => { app.myts.otp_required = @@ -642,15 +1123,288 @@ mod tests { otp_token: format!("{name}-otp"), device_id: format!("{name}-device"), }), + presentation: Presentation { + certificate: format!("{name}-cert").into_bytes(), + avatar: format!("{name}-avatar").into_bytes(), + }, } } + /// What servers are shown of the account is kept for it, told once its + /// session is valid again, and never shown for another account. + #[test] + fn what_servers_are_shown_is_kept_per_account() { + let dir = std::env::temp_dir().join(format!("voelin-presentation-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let secrets = MemorySecrets::default(); + let mut account = Account::new(dir.clone()); + account.accept(&secrets, login("Alice"), "alice@example.test".into()); + assert_eq!(account.presentation.as_ref().unwrap().certificate, b"Alice-cert"); + let data = account.myts_data(NOW).unwrap(); + assert_eq!(data.myts_id, [1; 33]); + // Nothing a server would verify: nothing shown. + assert!(data.avatar.is_empty() && data.badges.is_empty() && data.user_tag.is_none()); + let mut restarted = Account::new(dir.clone()); + restarted.load(&secrets); + assert!(restarted.myts_data(NOW).is_none(), "not before the session is checked"); + assert!(restarted.presentation == account.presentation); + restarted.restored(); + assert!(restarted.myts_data(NOW).is_some()); + restarted.forget(&secrets); + assert!(!dir.join(PRESENTATION_FILE).exists()); + let mut bob = login("Bob"); + bob.presentation = Presentation::default(); + restarted.accept(&secrets, bob, "bob@example.test".into()); + assert!(restarted.presentation.is_none()); + // What myTeamSpeak hands out with the session alone is Bob's. + restarted.take_fetched("Bob-uuid", fetched_tag("bob@myteamspeak.com")); + let mut again = Account::new(dir.clone()); + again.load(&secrets); + assert_eq!(again.presentation.as_ref().unwrap().uuid, "Bob-uuid"); + assert_eq!(again.form().user_tag, "bob@myteamspeak.com"); + let _ = std::fs::remove_dir_all(dir); + } + + use voelin_myts::testing::NOW; + + fn fetched_tag(tag: &str) -> Fetched { + Fetched { user_tag: Some(tag.into()), ..Default::default() } + } + + /// A `SignedUserBadge` as myTeamSpeak sends it (protobuf by hand). + fn signed_badge(uuid: &str, name: &str) -> Vec { + let mut badge = vec![0x0a, uuid.len() as u8]; + badge.extend_from_slice(uuid.as_bytes()); + badge.extend_from_slice(&[0x1a, name.len() as u8]); + badge.extend_from_slice(name.as_bytes()); + let mut signed = vec![0x0a, badge.len() as u8]; + signed.extend_from_slice(&badge); + signed.extend_from_slice(&[0x12, 64]); + signed.extend_from_slice(&[7; 64]); + signed + } + + /// An empty or failed answer changes nothing; an answer replaces only + /// what it is about. + #[test] + fn what_myteamspeak_did_not_tell_stays() { + let mut kept = SavedPresentation { + uuid: "a".into(), + certificate: b"login".to_vec(), + avatar: b"login avatar".to_vec(), + service_certificate: b"service".to_vec(), + service_avatar: b"service avatar".to_vec(), + badges: vec![signed_badge("b1", "One")], + user_tag: "alex@myteamspeak.com".into(), + user_tag_token: b"token".to_vec(), + }; + let before = kept.clone(); + kept.merge(Fetched::default()); + assert!(kept == before); + kept.merge(Fetched { + avatar: Some(OwnAvatar { certificate: b"new".to_vec(), avatar: b"newer".to_vec() }), + ..Default::default() + }); + assert_eq!( + (kept.service_certificate.as_slice(), kept.service_avatar.as_slice()), + (&b"new"[..], &b"newer"[..]) + ); + assert_eq!(kept.certificate, b"login", "the sign-in's stays"); + assert_eq!(kept.badges, before.badges); + // A list is the list, even an empty one. + kept.merge(Fetched { badges: Some(Vec::new()), ..Default::default() }); + assert!(kept.badges.is_empty()); + kept.merge(fetched_tag("alex@tschat-1.teamspeak.com")); + assert_eq!(kept.user_tag, "alex@tschat-1.teamspeak.com"); + assert_eq!(kept.user_tag_token, b"token", "the token proves all the tags"); + kept.merge(Fetched { user_tag_token: Some(b"fresh".to_vec()), ..Default::default() }); + assert_eq!(kept.user_tag_token, b"fresh"); + } + + /// Up to three badges, in the order chosen, kept per account (across + /// sign-outs); none chosen at first. + #[test] + fn badges_shown_on_servers_are_chosen_per_account() { + let dir = std::env::temp_dir().join(format!("voelin-badges-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let secrets = MemorySecrets::default(); + let mut account = Account::new(dir.clone()); + account.accept(&secrets, login("Alice"), "alice@example.test".into()); + let badges = ["One", "Two", "Three", "Four"] + .iter() + .enumerate() + .map(|(i, name)| SignedBadge::parse(&signed_badge(&format!("b{i}"), name)).unwrap()) + .collect(); + account.take_fetched("Alice-uuid", Fetched { badges: Some(badges), ..Default::default() }); + assert!(account.shown_badges.is_empty(), "none chosen at first"); + assert!(account.chosen_badges().is_empty()); + for index in [2, 0, 3] { + assert!(account.choose_badge(index, true)); + } + assert!(!account.choose_badge(1, true), "three at most"); + assert!(!account.choose_badge(0, true), "already shown"); + assert!(!account.choose_badge(9, true)); + let names = |account: &Account| { + account.chosen_badges().into_iter().map(|b| b.name).collect::>() + }; + assert_eq!(names(&account), ["Three", "One", "Four"]); + let form = account.form(); + let choice: Vec<_> = form.badge_choice.iter().map(|b| (b.shown, b.can_change)).collect(); + assert_eq!(choice, [(2, true), (0, false), (1, true), (3, true)]); + assert!(account.choose_badge(0, false)); + assert!(account.choose_badge(1, true)); + assert_eq!(names(&account), ["Three", "Four", "Two"]); + // Kept for the account, also after signing out and in again. + account.forget(&secrets); + assert!(account.shown_badges.is_empty()); + account.accept(&secrets, login("Bob"), "bob@example.test".into()); + assert!(account.shown_badges.is_empty(), "Bob chose none"); + account.forget(&secrets); + account.accept(&secrets, login("Alice"), "alice@example.test".into()); + assert_eq!(account.shown_badges, ["b2", "b3", "b1"]); + let _ = std::fs::remove_dir_all(dir); + } + + /// A chosen badge myTeamSpeak no longer lists takes no place: the others + /// move up, another can be chosen, and the choice kept is then what the + /// list shows. + #[test] + fn a_badge_no_longer_listed_takes_no_place() { + let secrets = MemorySecrets::default(); + let mut account = Account::default(); + account.accept(&secrets, login("Alice"), "alice@example.test".into()); + let listed = |names: &[&str]| Fetched { + badges: Some( + names.iter().map(|n| SignedBadge::parse(&signed_badge(n, n)).unwrap()).collect(), + ), + ..Default::default() + }; + account.take_fetched("Alice-uuid", listed(&["b0", "b1", "b2", "b3"])); + for index in [0, 1, 2] { + assert!(account.choose_badge(index, true)); + } + // b1 is gone. + account.take_fetched("Alice-uuid", listed(&["b0", "b2", "b3"])); + let names = |account: &Account| { + account.chosen_badges().into_iter().map(|b| b.name).collect::>() + }; + assert_eq!(names(&account), ["b0", "b2"]); + let choice = |account: &Account| { + account.form().badge_choice.iter().map(|b| (b.shown, b.can_change)).collect::>() + }; + assert_eq!(choice(&account), [(1, true), (2, true), (0, true)]); + assert!(account.choose_badge(2, true), "a place is free"); + assert_eq!(account.shown_badges, ["b0", "b2", "b3"]); + assert_eq!(choice(&account), [(1, true), (2, true), (3, true)]); + // Back again, b1 is not chosen: the choice is what the list showed. + account.take_fetched("Alice-uuid", listed(&["b0", "b1", "b2", "b3"])); + assert_eq!(names(&account), ["b0", "b2", "b3"]); + // A choice kept from before (badges.json) with more than three listed: + // three are shown. + account.shown_badges = ["b3", "b1", "b0", "b2"].map(String::from).to_vec(); + assert_eq!(names(&account), ["b3", "b1", "b0"]); + assert_eq!(choice(&account)[2], (0, false)); + } + + /// Servers are shown what verifies, each part with the certificate that + /// verifies it: here the avatar service's newer avatar with its own + /// certificate, the chosen badges with the sign-in's, the User Tag with + /// its token. (Certificates from a synthetic root: TeamSpeak's verifies + /// none of it.) + #[test] + fn servers_are_shown_what_verifies_with_its_certificate() { + use voelin_myts::testing::Chain; + let secrets = MemorySecrets::default(); + let mut account = Account::default(); + account.accept(&secrets, login("Alice"), "alice@example.test".into()); + let id = [1; 33]; + let sign_in = Chain::signing(1); + // Valid for an hour only. + let service = Chain::new(2, 6, NOW - 3600, NOW + 3600); + let chat = Chain::new(3, 4, NOW - 3600, NOW + 86_400); + let root = sign_in.root; + let uuids = [ + "a2a2a2a2-0000-4000-8000-000000000001", + "a2a2a2a2-0000-4000-8000-000000000002", + "a2a2a2a2-0000-4000-8000-000000000003", + ]; + let badges: Vec = uuids + .iter() + .zip(["One", "Two", "Three"]) + .map(|(uuid, name)| SignedBadge::parse(&sign_in.badge(&id, uuid, name)).unwrap()) + .collect(); + account.set_presentation( + "Alice-uuid", + Presentation { + certificate: sign_in.certificate.clone(), + avatar: sign_in.avatar(&id, 100), + }, + ); + let tag = "alice@myteamspeak.com"; + let token = chat.user_tag_token(&["alice@tschat-1.teamspeak.com", tag], &id); + account.take_fetched( + "Alice-uuid", + Fetched { + avatar: Some(OwnAvatar { + certificate: service.certificate.clone(), + avatar: service.avatar(&id, 200), + }), + badges: Some(badges), + user_tag: Some(tag.into()), + user_tag_token: Some(token.clone()), + }, + ); + assert!(account.choose_badge(2, true) && account.choose_badge(0, true)); + let data = account.myts_data_from(&root, NOW).unwrap(); + assert_eq!(data.myts_id, id); + assert!( + data.avatar + == tsclientlib::Signed { + certificate: service.certificate.clone(), + data: service.avatar(&id, 200), + } + ); + assert_eq!(data.badges.certificate, sign_in.certificate); + let chosen = account.chosen_badges(); + assert_eq!(data.badges.data, voelin_myts::badge_list(&chosen)); + assert_eq!(data.badge_ids, [uuids[2], uuids[0]]); + assert!(data.user_tag == Some(tsclientlib::UserTag { tag: tag.into(), token })); + // The avatar and the badges with two certificates: two commands. + assert_eq!(data.updates(&tsclientlib::MytsData::default(), false).len(), 2); + // Two hours on, the avatar service's certificate has expired: the + // sign-in's avatar, with the sign-in's certificate, and one command. + let later = account.myts_data_from(&root, NOW + 7200).unwrap(); + assert!( + later.avatar + == tsclientlib::Signed { + certificate: sign_in.certificate.clone(), + data: sign_in.avatar(&id, 100), + } + ); + assert_eq!(later.updates(&tsclientlib::MytsData::default(), false).len(), 1); + // A day on, the User Tag's token no longer holds. + assert!(account.myts_data_from(&root, NOW + 86_400).unwrap().user_tag.is_none()); + // For another myTS ID, nothing verifies. + account.saved.as_mut().unwrap().identity = Some(server_identity_for(2)); + let other = account.myts_data_from(&root, NOW).unwrap(); + assert!(other.avatar.is_empty() && other.badges.is_empty() && other.user_tag.is_none()); + // TeamSpeak's root verifies none of it. + account.saved.as_mut().unwrap().identity = Some(server_identity()); + let data = account.myts_data(NOW).unwrap(); + assert!(data.avatar.is_empty() && data.badges.is_empty() && data.user_tag.is_none()); + } + fn server_identity() -> ServerIdentity { + server_identity_for(1) + } + + /// An identity with the myTS ID `[id; 33]`. + fn server_identity_for(id: u8) -> ServerIdentity { let mut private = [0; 32]; private[0] = 1; let mut public = [0x66; 32]; public[0] = 0x58; // Compressed Ed25519 basepoint for scalar one. - ServerIdentity::new(vec![1; 33], 1, public, private, vec![2; 65]).unwrap() + ServerIdentity::new(vec![id; 33], 1, public, private, vec![2; 65]).unwrap() } #[test] diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index a5119e2..77782cb 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -1,8 +1,10 @@ //! Servers: bookmarks, connecting and observing, the rail, the sidebar's //! server card and the channel tree. +use std::time::Instant; + use slint::ComponentHandle; -use tracing::{info, warn}; +use tracing::{debug, info, warn}; use voelin_core::identity::LaunchImport; use voelin_core::{Command, JoinFailure, ObserveState, Source, VoiceOptions, VoiceState}; use voelin_model::ChannelId; @@ -51,6 +53,7 @@ fn bookmark_from_form( if old.is_some_and(|old| old.address != bookmark.address) { bookmark.cached_server_icon = None; bookmark.gateway_url = None; + bookmark.gateway_urls.clear(); bookmark.query = None; } bookmark.name = match form.name.trim() { @@ -82,6 +85,21 @@ fn apply_server_icon( bookmark.cached_server_icon != before } +/// Whether observing goes on as it is when discovery changed the gateways +/// kept from `previous` to `found`: the same ones (an older version kept +/// only the one in use), or logged in through `in_use`, still published. +/// What was found is kept for the next start, without a new login now. +fn observing_stays( + previous: &[String], + found: &[String], + in_use: Option<&str>, + observe: ObserveState, +) -> bool { + found == previous + || (observe == ObserveState::Observing + && in_use.is_some_and(|url| found.iter().any(|u| u == url))) +} + impl App { pub(crate) fn connect_voice(&mut self) { let channel = @@ -146,10 +164,10 @@ impl App { } /// Look up the gateway of a server ([`voelin_core::discover`]), once a - /// run: one found is kept as if typed, and takes the place of a stored - /// one that is no longer what the server publishes (a gateway that - /// moved, or one typed into an older version, which showed the field). - /// Nothing found keeps what is stored. + /// run: every one the server publishes is kept, best first, and tried in + /// turn; they take the place of a stored one that is no longer published + /// (a gateway that moved, or one typed into an older version, which + /// showed the field). Nothing found keeps what is stored. pub(crate) fn discover_gateway(&mut self, id: i64) { if self.demo_ui || !self.gateways_looked_up.insert(id) { return; @@ -157,31 +175,47 @@ impl App { let Some(b) = self.bookmark(id) else { return }; let address = b.address.clone(); self.engine.runtime().spawn(async move { - if let Some(url) = voelin_core::discover::gateway(&address).await { - later(move |app| app.gateway_found(id, &address, url)); + let started = Instant::now(); + let urls = voelin_core::discover::gateways(&address).await; + let elapsed_ms = started.elapsed().as_millis() as u64; + if urls.is_empty() { + info!(server = %address, elapsed_ms, "no gateway published"); + } else { + later(move |app| app.gateway_found(id, &address, urls, elapsed_ms)); } }); } - /// A gateway was found for the server at `address`; it is kept unless - /// the server changed meanwhile, and the server is observed through it - /// if it is the one shown. Users never hear of it (logged only). - fn gateway_found(&mut self, id: i64, address: &str, url: String) { + /// Gateways were found for the server at `address` (best first); they + /// are kept unless the server changed meanwhile, and the server is + /// observed through them if it is the one shown. Users never hear of + /// them (logged only). + fn gateway_found(&mut self, id: i64, address: &str, urls: Vec, elapsed_ms: u64) { let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id && b.address == address) else { return; }; - if b.gateway_url.as_deref() == Some(url.as_str()) { + let previous = b.gateways(); + let in_use = b.gateway_url.clone(); + if !b.set_gateways(urls) { + debug!(server = %b.address, urls = ?b.gateway_urls, elapsed_ms, "gateway found, as kept"); return; } - let previous = b.gateway_url.replace(url.clone()); if let Err(e) = self.store.update_bookmark(b) { warn!(%e, "could not keep the gateway found"); return; } - info!(server = %b.address, %url, ?previous, "gateway found"); + let observe = self.sessions.get(&id).map(|v| v.state.observe).unwrap_or_default(); + let kept = observing_stays(&previous, &b.gateways(), in_use.as_deref(), observe); + info!(server = %b.address, urls = ?b.gateway_urls, ?previous, kept, elapsed_ms, "gateway found"); self.refresh_toolbar(); - // Observed through the old one: through this one now. - if previous.is_some() { + if kept { + if self.current == Some(id) && observe == ObserveState::Off { + self.observe(id); + } + return; + } + // Observed through the old ones: through these now. + if !previous.is_empty() { self.engine.send(Command::StopObserving { session: id as u64 }); if let Some(view) = self.sessions.get_mut(&id) { view.state.observe = ObserveState::Off; @@ -192,6 +226,19 @@ impl App { } } + /// The gateway logged in at `url`: it is the one in use from now on. + pub(crate) fn gateway_in_use(&mut self, id: i64, url: &str) { + let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id) else { return }; + if !b.gateway_in_use(url) { + return; + } + if let Err(e) = self.store.update_bookmark(b) { + warn!(%e, "could not keep the gateway in use"); + return; + } + info!(server = %b.address, %url, "gateway in use"); + } + /// The server told its name: a server still named by its address takes /// it, so the address is all a user has to type. pub(crate) fn adopt_server_name(&mut self, id: i64, name: &str) { @@ -212,22 +259,38 @@ impl App { /// Observe the server invisibly, unless it is already: through its /// gateway, else its own query login. Without either the gateway is /// looked up first, and observing starts when it is found - /// (`gateway_found`). + /// (`gateway_found`). Asked while still connecting, the engine tries + /// the gateway again sooner. pub(crate) fn observe(&mut self, id: i64) { let Some(b) = self.bookmark(id).cloned() else { return }; if self.demo_ui { return; } let session = b.id as u64; - let observing = - self.sessions.get(&b.id).is_some_and(|v| v.state.observe != ObserveState::Off); - if observing { - return; + let state = self.sessions.get(&b.id).map(|v| v.state.observe).unwrap_or_default(); + let urls = b.gateways(); + match state { + ObserveState::Observing => return, + // The engine decides: the same gateways are not started over, + // at most tried again now. + ObserveState::Connecting => { + if !urls.is_empty() { + debug!(server = %b.address, "still connecting to the gateway: try now"); + self.engine.send(Command::ObserveGateway { + session, + urls, + identity: Box::new(self.identity_for(Some(b.id))), + }); + } + return; + } + ObserveState::Off => {} } - if let Some(url) = &b.gateway_url { + if !urls.is_empty() { + info!(server = %b.address, ?urls, "observing through the gateway"); self.engine.send(Command::ObserveGateway { session, - url: url.clone(), + urls, identity: Box::new(self.identity_for(Some(b.id))), }); // Still the one the server publishes? @@ -753,6 +816,7 @@ mod tests { identity: Some(2), default_channel: Some("Lobby/Sub".into()), gateway_url: Some("ws://gw.example.test:7788/v1".into()), + gateway_urls: vec!["ws://gw.example.test:7788/v1".into()], query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }), client_version: Some("linux".into()), cached_server_icon: Some(voelin_store::CachedServerIcon { @@ -781,6 +845,7 @@ mod tests { assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into()))); assert_eq!(b.client_version.as_deref(), Some("linux")); assert_eq!((b.gateway_url, b.query), (None, None)); + assert!(b.gateway_urls.is_empty()); } #[test] @@ -811,4 +876,23 @@ mod tests { "You now use your TeamSpeak identity \u{201c}Main\u{201d}; your previous one is kept" ); } + + #[test] + fn a_gateway_found_again_is_not_logged_in_again() { + let (tls, plain) = ("wss://gw.example.test/v1", "ws://ts.example.test:7788/v1"); + let urls = |list: &[&str]| list.iter().map(|u| u.to_string()).collect::>(); + let stays = |previous: &[&str], found: &[&str], observe| { + observing_stays(&urls(previous), &urls(found), Some(plain), observe) + }; + // The same ones (an older version kept only the one in use). + assert!(stays(&[plain], &[plain], ObserveState::Connecting)); + assert!(stays(&[plain], &[plain], ObserveState::Observing)); + // Logged in through one still published. + assert!(stays(&[plain], &[tls, plain], ObserveState::Observing)); + // Not logged in yet: through the new ones. + assert!(!stays(&[plain], &[tls, plain], ObserveState::Connecting)); + // The one in use is no longer published. + assert!(!stays(&[plain], &[tls], ObserveState::Observing)); + assert!(!observing_stays(&[], &urls(&[tls]), None, ObserveState::Off)); + } } diff --git a/crates/voelin-ui/src/settings.rs b/crates/voelin-ui/src/settings.rs index 97e423a..2d10f98 100644 --- a/crates/voelin-ui/src/settings.rs +++ b/crates/voelin-ui/src/settings.rs @@ -87,8 +87,8 @@ pub static UI_NARROW_BREAKPOINT: Key = Key::new( pub static UI_IMAGE_CACHE_MB: Key = Key::new( "ui.image_cache_mb", Kind::UInt { min: 0 }, - "Memory in MB for decoded images (avatars, icons, emoji); 0 keeps none.", - || 64, + "Memory in MB for decoded images (avatars, icons, banners, emoji); 0 keeps none.", + || 256, ); /// `ui.members_width`: how wide the members and streams panel is, in diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index cca1d36..cb35b3d 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -841,6 +841,15 @@ export struct AdvancedForm { crash-dir: string, } +// A badge of the account, as servers can be shown it: its place among the +// shown ones (1 to 3; 0: not shown), and whether that can change now (at +// most three are shown). +export struct MytsBadge { + name: string, + shown: int, + can-change: bool, +} + // Who we are (My Account page). export struct MytsForm { prompt: bool, @@ -862,6 +871,9 @@ export struct MytsForm { member-since: string, last-login: string, badges: [string], + // The badges signed for servers, to choose from; the primary User Tag. + badge-choice: [MytsBadge], + user-tag: string, devices: [string], status: int, persistence-status: int, @@ -1255,6 +1267,8 @@ export global Bridge { callback myts-dismiss(); callback myts-retry(); callback myts-portal(int); + // Show the badge at this index (of `myts.badge-choice`) on servers, or not. + callback myts-badge(int, bool); callback myts-login(string, string, string); callback myts-logout(); in property <[IdentityItem]> identities; diff --git a/crates/voelin-ui/ui/screens/account.slint b/crates/voelin-ui/ui/screens/account.slint index b5ccb56..c19ecbb 100644 --- a/crates/voelin-ui/ui/screens/account.slint +++ b/crates/voelin-ui/ui/screens/account.slint @@ -5,7 +5,7 @@ import { Theme } from "../theme.slint"; import { Icons } from "../icons.slint"; import { Bridge } from "../bridge.slint"; import { Nav } from "../nav.slint"; -import { Icon, Spinner, Button, ButtonKind, IconButton, TextField, Field, Card, Divider, Banner, Avatar, Status, Chip, ScrollView } from "../components/index.slint"; +import { Icon, Spinner, Button, ButtonKind, IconButton, TextField, Field, Card, Divider, Banner, Avatar, Status, Chip, ScrollView, Toggle } from "../components/index.slint"; component Note inherits Text { // Keep wrapped account copy in the card’s layout bounds. @@ -257,7 +257,42 @@ component ProfileDetails inherits VerticalLayout { label: @tr("Previous sign-in"); value: Bridge.myts.last-login; } - if Bridge.myts.badges.length > 0: VerticalLayout { + // The badges signed for servers: up to three are shown there. + if Bridge.myts.badge-choice.length > 0: VerticalLayout { + spacing: Theme.space-2; + Text { + text: @tr("Badges"); + color: Theme.text-secondary; + font-size: Theme.font-sm; + font-weight: Theme.weight-medium; + } + Note { text: @tr("Choose up to three badges to show on servers, in the order you pick them."); } + for badge[i] in Bridge.myts.badge-choice: HorizontalLayout { + spacing: Theme.space-3; + Icon { + source: Icons.star; + size: Theme.icon-sm; + tint: badge.shown > 0 ? Theme.gold : Theme.text-muted; + y: (parent.height - self.height) / 2; + } + Text { + text: badge.shown > 0 ? @tr("{} · place {} on servers", badge.name, badge.shown) : badge.name; + color: Theme.text; + font-size: Theme.font-sm; + overflow: elide; + vertical-alignment: center; + horizontal-stretch: 1; + } + Toggle { + checked: badge.shown > 0; + enabled: badge.can-change; + label: @tr("Show {} on servers", badge.name); + y: (parent.height - self.height) / 2; + toggled(on) => { Bridge.myts-badge(i, on); } + } + } + } + if Bridge.myts.badge-choice.length == 0 && Bridge.myts.badges.length > 0: VerticalLayout { spacing: Theme.space-2; Text { text: @tr("Badges"); @@ -322,6 +357,15 @@ component AccountProfile inherits VerticalLayout { icon: Icons.id-card; } } + if Bridge.myts.user-tag != "": Field { + label: @tr("User Tag"); + TextField { + text: Bridge.myts.user-tag; + read-only: true; + label: @tr("User Tag"); + icon: Icons.at-sign; + } + } if Bridge.myts.myts-id != "": Field { label: @tr("myTS ID"); TextField { diff --git a/docs/gateway-admin.md b/docs/gateway-admin.md index 42ff8c2..e1ade7f 100644 --- a/docs/gateway-admin.md +++ b/docs/gateway-admin.md @@ -76,9 +76,30 @@ Every login, post and settings change is written to the audit table. `permoverview`, `banlist`, `clientmove`, `sendtextmessage`, `servergroupsbyclientid` and `channelgroupclientlist`, e.g. a dedicated login in the Server Admin group. -3. Put the gateway's IP into `query_ip_allowlist.txt` and set - `query.allowlisted = true`. Otherwise the server's flood protection - (10 commands / 3 s) applies and bans the gateway under load. +3. Put the address the server sees for the gateway into the server's + `query_ip_allowlist.txt` and set `query.allowlisted = true`. The server's + flood protection counts the query commands of each address, all of + tsgw's connections together and the SSH login included: it refuses the + 10th command within 3 seconds and asks to wait, and two more commands + during the wait get the address banned for 600 seconds. tsgw logs the + address when it starts ("the TeamSpeak server sees the gateway's queries + coming from this address"): + - tsgw on the server's machine: `127.0.0.1`, which the file lists by + default. + - tsgw in a Docker container with bridge networking: the container's + or the bridge's address (e.g. `172.17.0.2`), not `127.0.0.1`. Add + that address, or run the container with `--network host`. + + The server reads the file again within seconds, without a restart; that + also lifts a 600 s ban. Do not set `allowlisted = true` without the + entry in the file: tsgw then sends at full speed until the server + refuses a command, and an older tsgw got the address banned that way. + Now it stops at the first refusal and logs "the server limits this + address although it was taken to be on its query allowlist". Without + the allowlist tsgw stays under the limit itself (9 commands per 3 s + over all its connections) and, after a refusal (other query tools on + the same address count too), sends nothing on any connection for at + least 3 s, so logins are slower when many happen at once. 4. Each relayed channel is one more query connection. Keep `relay.max_channel_relays` below the server's per-IP connection limit. Relays count toward a channel's max clients unless their group has @@ -102,9 +123,16 @@ registered domain, the most specific name first; for `ts.example.org` that is `ts.example.org`, then `example.org`. It looks once per run when the server is selected or connects with voice, and again when its address changes: what is published takes the place of what was found before (a -lookup that finds nothing keeps it). A gateway that cannot be reached is -tried again by itself (after 2, 5, 15, 30, then every 60 seconds); users -see nothing of it, the log file has the URL and the error. +lookup that finds nothing keeps it). Every gateway found is kept and +tried in turn, best first, each for up to 20 seconds; the first that logs +in is used, and the log file names those it passed over (URL and error). +Only when all of them fail does it wait (1, 2, 5, 10, 20, then every 30 +seconds, give or take 30 %; at once when voice connects) and start over; +users see nothing of it. Only a refused login ends it (bad signature, +security level too low, banned, not allowed); a gateway that cannot do the +login yet (for example an identity the server has not seen) is tried again. +Once connected, the client pings the gateway every 30 seconds and connects +again after 60 seconds without an answer. **DNS records** (preferred). An SRV record names the gateway's host and port, the service name says whether it speaks TLS: @@ -115,9 +143,17 @@ port, the service name says whether it speaks TLS: | `_tsgw._tcp. SRV ` | `ws://:/v1` (plain, e.g. tsgw itself on 7788) | | `_tsgws._tcp. TXT "path=/"` (optional, same for `_tsgw`) | another path than `/v1`, e.g. behind a reverse proxy | -At the same name TLS wins; among several records of one name the lowest -priority. A target of `.` means "no gateway here" and the search goes on at -the parent domain. Examples (zone of `example.org`): +Which gateways: those of the most specific name that publishes a record, +and only those (a parent domain's records are another server's gateway +when the host publishes its own). At that name `_tsgws` before `_tsgw`, +among several records of one kind the lowest priority first, then tsgw's +own answer at that name (below), but only when a plain record is published +there, so a server that publishes only TLS is never reached without it. A +TLS proxy that fails (no rule for the host, no certificate) thus falls +back to the plain gateway published next to it. With no record at any +name, tsgw's own answer at the most specific name that gives one. A target +of `.` means "no gateway here" and the search goes on at the parent +domain. Examples (zone of `example.org`): ```dns ; Behind a TLS proxy at gw.example.org that forwards /tsgw/v1 to tsgw: @@ -135,6 +171,18 @@ itself speaks plain WebSocket, so its own port (7788) is published as `_tsgw`; a `_tsgws` record there makes Voelin start TLS with it, which fails. Publish `_tsgws` only for a port with TLS in front. +Behind [Zoraxy](https://zoraxy.aroz.org/): add an HTTP proxy rule for the +gateway's host (`gw.example.org`) with one upstream, tsgw's plain address +(`:7788`), "Proxy Target require TLS Connection" off, +WebSockets on, and a certificate for the host (ACME). If the rule also +has an uptime monitor, point it at `/health` (tsgw's `/` answers 404). +Check from outside: `curl https://gw.example.org/health` prints `ok` (or +what is missing while tsgw is not logged in to the TeamSpeak server, see +[Logs](#logs)); Zoraxy's own `404 page not found` there means no rule +matched the host or the request went to another upstream. Then set `listen.public_url = +"wss://gw.example.org/v1"` in tsgw.toml, so its own answer points at the +proxy. + One domain with several servers and several gateways: publish one record per server host (`_tsgws._tcp.ts1.example.org`, `_tsgws._tcp.ts2.example.org`); a record at the domain itself applies to every host below it that has none @@ -193,11 +241,74 @@ the unit to `/etc/systemd/system/`. ```sh docker load -i tsgw-image.tar.gz # or: docker build -f crates/voelin-gateway/Dockerfile -t tsgw . -docker run -v $PWD/tsgw.toml:/etc/tsgw/tsgw.toml -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw +docker run -d --name tsgw --init --restart unless-stopped \ + -v $PWD/tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \ + -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw +docker logs -f tsgw ``` +The volume keeps the database (`/var/lib/tsgw/tsgw.db`: login tokens, +history, settings changed at runtime) when the container is replaced. +`--init` passes `docker stop` on to tsgw and cleans up after it; +`--restart unless-stopped` brings it back after a crash or a reboot. With +bridge networking (the default) see step 3 of [Setup](#setup) about the +address the TeamSpeak server sees. + **From source:** `cargo run --release -p voelin-gateway -- --config tsgw.toml`. +## Logs + +tsgw logs to standard output: `journalctl -u tsgw -f` under systemd, +`docker logs -f tsgw` in a container (colours only on a terminal; `NO_COLOR` +turns them off there too). At the default level it logs: + +- at start: the version and settings in use (whether a query password is + set, never the password itself), the query login and how long it took, + the address the TeamSpeak server sees for the gateway (with a hint when + `query.allowlisted` is off), "listening" with the URL apps are given; +- each app connection: its address, `X-Forwarded-For` and `User-Agent`, + then logins (unique id, nickname, signature or token, how long it took), + refused logins with the reason, requests slower than 1 s and the close + (reason, how long it was open). Every line of a connection carries its + number and address (`ws{id=12 peer=…}`); +- ServerQuery: failed commands (by name), each wait the server's flood + protection asks for, relays opened and closed, the watcher connecting + and losing its connection (with the attempt and the next wait), the + lookup connection lost and restored. + +More detail with `log.level` (`TSGW_LOG_LEVEL`; without it `RUST_LOG`): + +| Setting | Shows | +|---|---| +| `TSGW_LOG_LEVEL=debug` | also every request and its time, ServerQuery connections opening and closing | +| `TSGW_LOG_LEVEL=info,voelin_query=trace` | every query command sent and answered, with its time and the connection it went over (`lookup`, `observer`, `relay `) | +| `TSGW_LOG_LEVEL=warn` | only problems | + +Libraries that log every packet (`russh`, `hyper`, `h2`, `tower`, +`tungstenite`) stay at warnings unless the setting names them +(`debug,russh=debug`). Under systemd put the variable into +`/etc/tsgw/tsgw.env`, in a container pass `-e TSGW_LOG_LEVEL=…`. + +`log.file` (`TSGW_LOG_FILE`) writes the log to a file as well. tsgw appends +to it, also across restarts; at 20 MB it moves to `tsgw.1.log` (older ones +one further along, 5 files in all) and a new one starts. A relative path is +relative to the working directory, `/var/lib/tsgw` under systemd and in the +container (`TSGW_LOG_FILE=logs/tsgw.log` with the volume above). The systemd +unit can also write `/var/log/tsgw`. If the file cannot be opened, tsgw +says so and logs to standard output only. + +While the TeamSpeak server cannot be reached (not started yet, restarting), +tsgw listens anyway and logs in as soon as it can, waiting 1, 2, 3, 5, 10, +then 30 seconds between attempts (longer if the server's flood protection +asks for it). Apps that connect meanwhile wait up to 10 seconds, then are +told to try again. A query connection the server drops is opened again the +same way, and relays that someone still reads or that are pinned come back. +Opening a query connection (connecting, logging in, selecting the server) +gives up after 10 seconds, so a server that does not answer holds up +nothing for long. `/health` answers +`ok` while the gateway is logged in and watching the server, otherwise 503 +and what is missing (`starting: …`, `query: down, observer: up`). + ## Visibility Query clients are not hidden by the server; official clients hide them from @@ -213,7 +324,8 @@ query clients sees that it came from a query session. - **Bootstrap** keys are needed before the database opens: `gateway_id`, `server.voice_port`, `query.*` (transport, address, login, password, - `allowlisted`), `listen.bind`, `listen.public_url` and `history.path`. + `allowlisted`), `listen.bind`, `listen.public_url`, `history.path` and + `log.level`, `log.file` ([Logs](#logs)). They come from the file, the environment or the command line and apply at start; changing them needs a restart. - Everything else (history, relays, features, permission rules, quotas, diff --git a/docs/research/myteamspeak.md b/docs/research/myteamspeak.md index 22bc286..7d5f0d3 100644 --- a/docs/research/myteamspeak.md +++ b/docs/research/myteamspeak.md @@ -108,6 +108,86 @@ file names and description are used until then. What is kept goes into the same secret-store bundle as the session (`profile`), never the token into a URL. +### Presenting the account's avatar, and other clients' avatars (TeamSpeak 6) + +Voice servers show the account's avatar (and the blurred banner behind it +in the client-info view) and badges from what the client sends once +connected, not from `clientinit` (the official 6.0.0-beta4.1 client never +sets `client_myteamspeak_avatar` or `client_signed_badges` itself): + + updatemytsdata myts_certificate= [myts_signed_badge=] [myts_avatar=] + +built at 0x1f38520: `myts_certificate` is the inner `MyTSUserCertificate.cert` +bytes, `myts_avatar` a serialized `AvatarData` (its `AvatarInfo`, a timestamp +and myTeamSpeak's signature), `myts_signed_badge` a `UserBadgesSignedList` +of the badges the user chose (at most three, in the chosen order; none +until chosen). The values are the raw bytes with TeamSpeak's escaping only +(`\a` and `\b` included), no base64. The official client sends it once +connected, after a sign-in (after `updatemytsid`), after an avatar upload +and after a badge change. + +What the TeamSpeak 6 server (6.0.0-beta13.1) does with it: it parses the +certificate as a TeamSpeak license chain, requires the leaf to be valid now, +of block type 6 (`MYTSID_SIGN`; types 4 to 7 carry nothing after the 42-byte +header), the chain to lead to TeamSpeak's root and the key not to be on +myTeamSpeak's revocation list, and takes the leaf's derived Ed25519 key. It +verifies the avatar's signature over `SerializeAsString(AvatarInfo) || +myTS ID (33 bytes) || timestamp (u64, big-endian)` and each badge's over +`uuid (16 bytes) || sign_timestamp (u64, big-endian) || myTS ID`, the myTS +ID being the one it holds for the client at that moment. What does not +verify is silently emptied (`client_myteamspeak_avatar` / +`client_signed_badges` become empty, answer `error id=0`); only an unusable +certificate with a non-empty value is refused, with 1538 (also when the +server could not load the revocation list). The server echoes both +properties for the client before its answer. A bare parameter clears it +without a certificate; an absent one is left alone. `updatemytsid` does +not check them again, so they are sent again after it. + +Voelin does the same checks locally (`tsproto::myts::Certificate`, +`voelin_myts::choose_avatar`, `choose_badges_certificate`) to choose, for +the avatar and for the chosen badges, a certificate that verifies them, +from those at hand: the last password sign-in's (`LoginSession` fields 10 +and 11, the avatar as it came), the one myTeamSpeak's avatar service hands +out with the avatar, and the myTS ID's `pubSignCert` when its leaf is of +type 6. Since a server verifies with the one certificate of each command, +the avatar and the badges go in separate commands when they need different +certificates (one command, certificate, badges, avatar, when one verifies +both). A badge id must be in the 36-character form with hyphens: the server +reads it with Boost's `uuid` parser, which throws on anything else, so such +a badge is never sent. After sending, Voelin logs whether the server shows +them, or why not, and names the badges it dropped (`client_signed_badges` +lists the ids that verified). Each connection sends only what changed, all +of it again after `updatemytsid` or a reconnect, and clears with bare +parameters what it showed and should no longer show: on a sign-out or an +account change, `updatemytsdata myts_certificate myts_signed_badge +myts_avatar` (or only the parts it showed; both answer 0). + +Without a password: `requestContactsAvatar` at `/user` with the account's own +raw myTS ID (`RequestContactsAvatarInfoRequest{session, id: +[AvatarRequestID{key: Any(…AvatarRequestID.MYTSKey{id})}]}`) answers the +account's `AvatarData` as it came, whose `optional` field holds +`OptionalAvatarDataContactInfo{mytsid, user_cert}`; `user_cert` is checked +by the official client with the same function as the login certificate. An +unknown session gets an empty answer, like an account without an avatar, so +an empty answer means "nothing learned" and never clears what is kept. +`getSignedBadges(Session)` at `/user` answers `UserBadgesSignedResponse{list, +error_code}` (109 for an unknown session); each `SignedUserBadge` is kept as +it came. Voelin asks both after a password sign-in, after a checked saved +session and then daily, and keeps the answers in +`/account/presentation.json` (public data); the chosen badges are kept +per account in `/account/badges.json`, across sign-outs. A chosen +badge myTeamSpeak no longer lists takes none of the three places, and is +dropped from the choice the next time the user changes it. + +Other clients' avatars arrive as `client_myteamspeak_avatar`, plain text +`,;,…` with myTeamSpeak's `AvatarState` numbers +(`request_avatar_with_ts_server_client_property`, 0x1ae2840): an entry +that is not `,` (an empty one from a trailing `;` too) spoils +the whole value; the online picture is shown, else away, do not disturb, +offline; the server's own avatar (`client_flag_avatar`) wins when it loads. +Voelin downloads it (HTTPS, 4 MiB) where the server's is not shown: none +set, no voice connection (observing), or its download gave up. + `requestAvatarSignedUrl` is not a download call: it signs *upload* links. In the TS6 6.0.0-beta4.1 Linux client, `Account_Manager_Impl:: request_avatar_signed_urls`'s reply goes only to `upload_avatar`, whose @@ -127,6 +207,37 @@ session deletion; storage or remote errors are reported. A late completion cannot sign a canceled operation back in. Server identities and bookmark nicknames remain independent of the primary app profile. +### The User Tag (TeamSpeak 6) + +`client_user_tag` is the account's primary TeamSpeak chat identifier +(`name@myteamspeak.com`): the entry with `primary` set in +`getActiveIdentifierList` at `/tschat` (Voelin falls back to +`getAccountData`'s active identifiers). The token that proves it comes from +`requestSignedAllowedIdentifierList` at `/tschat`; both take +`AuthenticatedUser{session}` only (no chat account, `matrix_id` never set) +and answer an `ErrorHandling` whose `return_code` must be 1 (5: the session +expired). The token is a `MatrixIdentifierToken{signature, sign_certificate, +timestamp, tags}`, kept as it came. Viewers (the official client's +`verifyIdentifierToken`) parse `sign_certificate` as a license chain from +TeamSpeak's root, require its leaf to be valid now (any block type), verify +the Ed25519 signature over `SerializeAsString(tags) || timestamp (u64, +big-endian) || myTS ID` with the myTS ID the client shows the server +(`client_myteamspeak_id`), and require the tag to be one of the tags. They +verify once per change of the property, and only if they have a TeamSpeak +chat connection themselves. The value is compact JSON in this key order: + + {"myts_token":"","tag":"","updated":} + +sent as `clientupdate client_user_tag=` (TeamSpeak escaping, so `/` +goes as `\/`), once connected and after every `updatemytsid`, on servers +that know the property (protocol 8, TeamSpeak 6; on protocol 7 the official +client mirrors the JSON into `client_meta_data`, which Voelin leaves to its +own identification). A bare `clientupdate client_user_tag` clears it, on +sign-out or account change. The server stores and relays the value without +checks (about 8 KB at most). Voelin checks the token itself before using it, +asks for a new one when it would not hold three days later, and shows the +tag in Settings → My Account. + ### Authenticated account identity on voice servers The account UUID is a profile identifier, not the authenticated `myTS ID`. diff --git a/docs/ui.md b/docs/ui.md index 2a13c25..7e966f0 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -223,8 +223,10 @@ back. The signed-in username/email and the account's avatar become the primary app profile in the desktop user card and mobile You page; they do not replace server identities or bookmark nicknames. Settings → My Account shows the profile from the account service (avatar, name, email, -description, member since, previous sign-in, badges, signed-in devices, the -account and myTS ids) or the sign-in form, supports retry/OTP/sign-out, and +description, member since, previous sign-in, badges with a toggle each to +show up to three of them on servers, in the order picked, signed-in +devices, the User Tag, the account and myTS ids) or the sign-in form, +supports retry/OTP/sign-out, and opens official browser flows for registration, activation, recovery and account management. Account and renewal material live only in the keyring; passwords and one-time codes are cleared after submission. Expired sessions @@ -404,7 +406,7 @@ live when they change (settings page, `--set`, another window): | `ui.theme` | dark / light / system | dark | colours | | `ui.font_scale` | number above 0 | 1.0 | every type size | | `ui.narrow_breakpoint` | pixels | 800 | below this width the phone layout | -| `ui.image_cache_mb` | megabytes | 64 | decoded images kept in memory (0: none) | +| `ui.image_cache_mb` | megabytes | 256 | decoded images kept in memory (0: none) | | `ui.members_width` | pixels | 280 | width of the members panel (dragging its edge sets it) | | `ui.image_preview_kb` | kilobytes | 8192 | pictures linked in chat (files and `[img]`) up to this size show as pictures (0: never) | | `notify.mentions`, `notify.private_messages`, `notify.pokes`, `notify.event_reminders`, `notify.friends_online` | off / app / desktop | desktop (friends: app) | what the bell and the desktop say about each kind | @@ -606,7 +608,9 @@ profile requires account setup before the server list, so no fresh-profile network capture was obtained. These observations do not establish that every server or client version lacks a pre-login mechanism. -Badges arrive as GUIDs (`client_badges`). Their names and descriptions come +Badges arrive as GUIDs (`client_badges`; on TeamSpeak 6 also +`client_signed_badges`, the myTeamSpeak badges the server verified, which +come first: `voelin_model::shown_badges`). Their names and descriptions come from a table in `voelin-model` (`badges::info`, tsclientlib's list and the newer entries of TeamSpeak's own, `https://badges-content.teamspeak.com/list`, as of October 2026); newer badges show as "Badge". Their pictures are SVGs @@ -627,28 +631,38 @@ server's own files, linked as `ts3image://` (TeamSpeak 5 and 6: `ts3image://?channel=…&path=…`), come through the voice connection's file transfer, so they need voice and the server's file permissions. Their cache entry is named by the server too, as the same address names another -file elsewhere. Up to eight distinct web banners download concurrently; -duplicate URLs share a request. A picture may be up to 64 MiB, avatars and -icons too, and goes to disk as it arrives. Web downloads have a 10-second -connection timeout and fail after 20 seconds without data or when, after -their first 30 seconds, they average less than 32 KiB/s; there is no -fixed overall deadline, so large banners on slow hosts still arrive. Failed -avatars, icons and banners receive up to three automatic retries after -1, 4 and 16 seconds, -without waiting for a presence update. Avatar/icon/banner file-transfer -negotiation expires after 15 seconds, and the download after 30 seconds -plus its size at 32 KiB/s. User file transfers retain their existing -timing. Replaced images and closed sessions discard -obsolete results. A host banner's reload interval is at least 60 seconds; -failed refreshes preserve the previous cached picture. Closing the session -stops its reload timer. `PictureReady` invalidates the decoded image before -refreshing the visible models, including when the URL and cache path stay -the same. +file elsewhere. Up to 16 web downloads run at once, at most 6 per host (a +redirect's target counts); duplicate URLs share a request. Pictures on the +web go through the desktop's proxy (the portal's, on Linux) or the +system's, SOCKS too. A picture may be up to 128 MiB (avatars and icons +too; myTeamSpeak avatars 4 MiB, a chat's `[img]` up to +`ui.image_preview_kb`), and goes to disk as it arrives. Web downloads +connect within 20 seconds, and fail after 60 seconds without data or when, +after their first 120 seconds, they average less than 8 KiB/s; there is +no fixed overall deadline, so large banners on slow hosts still arrive. +Failed banners and badges are tried again after 1, 4, 16, 60, 300 and 900 +seconds, then every 15 minutes while they are shown; one whose address is +wrong or gone (HTTP 400, 404, 410) after 15 minutes, then hourly; one whose +host asks to wait (429, 503) when it says (1 minute to 1 hour). Asked for +again, a cached picture is downloaded only if its host says it changed +(ETag, Last-Modified). Avatars, icons and chat pictures receive up to three +automatic retries after 1, 4 and 16 seconds. Retries do not wait for a +presence update. Avatar/icon/banner file-transfer negotiation expires +after 30 seconds, and the download after 60 seconds plus its size at +8 KiB/s. User file transfers retain their existing timing. Replaced images +and closed sessions discard obsolete results. A host banner's reload +interval is at least 60 seconds; failed refreshes preserve the previous +cached picture. Closing the session stops its reload timer. +`PictureReady` (and `AvatarReady`, `IconReady`) has a file that changed +decoded again before the visible models refresh, also when the URL and +cache path stay the same. -PNG, JPEG, GIF, WebP and SVG are decoded by content, since cached files have -no extension. Raster pictures larger than 16,384 pixels on either axis or -64 MiB of decoded RGBA are refused before pixel allocation on the UI -thread. SVG uses Slint's vector loader and the existing vector-cache cost. +PNG, JPEG, GIF, WebP, BMP, ICO and SVG (also after a comment or DOCTYPE) +are decoded by content, since cached files have no extension. Raster +pictures whose decoded RGBA would exceed 128 MiB are refused before pixel +allocation on the UI thread; those larger than 4096 pixels on a side are +scaled down (an animation to its first frame). SVG uses Slint's vector +loader and the existing vector-cache cost. Avatars and server, channel, client and group icons use the same image cache. The focused checks are the `voelin-core`, `voelin-model`, `voelin-observer`, diff --git a/packaging/linux/tsgw.service b/packaging/linux/tsgw.service index bc795e6..948d575 100644 --- a/packaging/linux/tsgw.service +++ b/packaging/linux/tsgw.service @@ -3,6 +3,8 @@ # Write /etc/tsgw/tsgw.toml (example in /usr/share/doc/tsgw/examples), put the # query password in /etc/tsgw/tsgw.env as TSGW_QUERY_PASSWORD=… (mode 600), # then: systemctl enable --now tsgw. State (tsgw.db) is kept in /var/lib/tsgw. +# Logs: journalctl -u tsgw -f; more detail with TSGW_LOG_LEVEL=debug in tsgw.env, +# a log file as well with TSGW_LOG_FILE (under /var/lib/tsgw or /var/log/tsgw). [Unit] Description=tsgw, the Voelin gateway for TeamSpeak servers Documentation=https://github.com/Faumaray/Voelin/blob/main/docs/gateway-admin.md @@ -18,6 +20,7 @@ ExecReload=/bin/kill -HUP $MAINPID EnvironmentFile=-/etc/tsgw/tsgw.env DynamicUser=yes StateDirectory=tsgw +LogsDirectory=tsgw WorkingDirectory=/var/lib/tsgw Restart=on-failure RestartSec=5 diff --git a/tools/voelinctl/src/client.rs b/tools/voelinctl/src/client.rs index f58cb28..5a4990c 100644 --- a/tools/voelinctl/src/client.rs +++ b/tools/voelinctl/src/client.rs @@ -461,7 +461,11 @@ impl Runner<'_> { { let data = std::fs::read(&path)?; let actual = format!("{:x}", md5_of(&data)); - if actual != hash { + // A server avatar is named by its MD5; a myTeamSpeak + // avatar by its address. + let server_avatar = + hash.len() == 32 && hash.bytes().all(|b| b.is_ascii_hexdigit()); + if server_avatar && actual != hash { bail!("avatar file hash {actual} is not the announced {hash}"); } if let Some(md5) = md5 diff --git a/tools/voelinctl/src/engine.rs b/tools/voelinctl/src/engine.rs index 2ba88a5..df52c73 100644 --- a/tools/voelinctl/src/engine.rs +++ b/tools/voelinctl/src/engine.rs @@ -99,7 +99,7 @@ pub async fn run(args: GatewayArgs) -> Result<()> { } engine.send(Command::ObserveGateway { session: SESSION, - url: args.url.clone(), + urls: vec![args.url.clone()], identity: Box::new(identity.clone()), }); if let Some(addr) = &args.voice {