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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
This commit is contained in:
Claude committed 2026-10-08 02:14:08 +00:00
commit 507dff58b2
78 files changed
+10311 -765

No files matched your search

+15 -1
View File
@@ -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.
+1
View File
@@ -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.
+294
View File
@@ -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<u8>,
/// 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<String>,
pub user_tag: Option<UserTag>,
}
/// Something signed and the certificate that verifies it; empty: nothing.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Signed {
pub certificate: Vec<u8>,
pub data: Vec<u8>,
}
/// 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<u8>,
}
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<u8>,
pub badges: Option<Vec<u8>>,
pub avatar: Option<Vec<u8>>,
}
/// 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<MytsUpdate> {
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<MessageHandle> {
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<MessageHandle> {
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<u8> { 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();
@@ -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"\\\\"),
@@ -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="`<state>,<url>;…` 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 },
+48 -6
View File
@@ -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();
+228
View File
@@ -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<LicenseBlockType>,
/// 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<Self, CertificateError> {
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::<Scalar>::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<u8>, Scalar) {
fn block(key: &Scalar, kind: u8, from: i64, to: i64, extra: &[u8]) -> (Vec<u8>, 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<u8> {
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());
}
}
+11 -1
View File
@@ -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" }
+84 -22
View File
@@ -3,7 +3,7 @@
use tsclientlib::{ClientType, MaxClients, data};
use voelin_model::{
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType, HostMessageMode,
Presence, ServerDetails, parse_badges,
Presence, ServerDetails, myts_avatar_url, shown_badges,
};
fn group_info(
@@ -46,7 +46,7 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
tsclientlib::HostMessageMode::Modalquit => HostMessageMode::ModalQuit,
},
banner_url: server.hostbanner_url.clone(),
banner_gfx_url: server.hostbanner_gfx_url.clone(),
banner_gfx_url: server.hostbanner_gfx_url.trim().to_owned(),
banner_gfx_interval_s: server.hostbanner_gfx_interval.whole_seconds().max(0) as u64,
banner_mode: match server.hostbanner_mode {
tsclientlib::HostBannerMode::NoAdjust => BannerMode::NoAdjust,
@@ -117,7 +117,12 @@ pub(crate) fn presence_from_book(
needed_talk_power: c.needed_talk_power.unwrap_or(0),
is_default: c.is_default.unwrap_or(false),
icon: c.icon.map_or(0, |i| i.0),
banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()),
banner_gfx_url: c
.banner_gfx_url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.map(str::to_owned),
// A number the book keeps as text.
banner_mode: c
.banner_mode
@@ -149,11 +154,15 @@ pub(crate) fn presence_from_book(
server_groups,
country: Some(c.country_code.clone()).filter(|c| !c.is_empty()),
avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()),
myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url),
description: Some(c.description.clone()).filter(|d| !d.is_empty()),
talk_power: c.talk_power,
talker: c.talk_power_granted,
channel_group: Some(c.channel_group.0),
badges: parse_badges(&c.badges),
badges: shown_badges(
&c.badges,
c.signed_badges.as_deref().unwrap_or_default(),
),
icon: c.icon.0,
recording: c.is_recording,
priority_speaker: c.is_priority_speaker,
@@ -179,10 +188,8 @@ mod tests {
InMessage::new(&packet.header(), text.as_bytes()).unwrap()
}
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
/// in the channel list, when a channel is created and when it is edited.
#[test]
fn channel_banners() {
/// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`.
fn ts6_book() -> data::Connection {
let InMessage::InitServer(init) = message(concat!(
"initserver virtualserver_name=Test virtualserver_welcomemessage ",
"virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ",
@@ -202,20 +209,29 @@ mod tests {
)) else {
panic!("not an initserver");
};
let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init);
let channel = |cid: u64, order: u64, name: &str, banner: &str| {
format!(
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
channel_storage_quota=4294967295"
)
};
data::Connection::new(EccKeyPrivP256::create().to_pub(), &init)
}
/// A `channellist` entry as TeamSpeak 6 sends it.
fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String {
format!(
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
channel_storage_quota=4294967295"
)
}
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
/// in the channel list, when a channel is created and when it is edited.
#[test]
fn channel_banners() {
let mut book = ts6_book();
let list = format!(
"channellist {}|{}",
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
@@ -269,4 +285,50 @@ mod tests {
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
assert_eq!(p.server.priority_speaker_dimm_db, -18);
}
/// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it:
/// when the client enters and when it changes.
#[test]
fn myts_avatars() {
let mut book = ts6_book();
book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", ""))))
.unwrap();
let enter = |clid: u16, avatar: &str| {
format!(
"notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \
client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \
client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
client_output_hardware=1 client_meta_data client_is_recording=0 \
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \
client_talk_request=0 client_talk_request_msg client_is_talker=0 \
client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \
client_needed_serverquery_view_power=75 client_is_channel_commander=0 \
client_country=RU client_badges client_myteamspeak_id=m{clid} \
client_integrations{avatar}"
)
};
for text in [
enter(
5,
r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png",
),
// A TeamSpeak 3 server, or a client without one.
enter(6, ""),
enter(7, " client_myteamspeak_avatar"),
] {
book.handle_command(&message(&text)).unwrap();
}
let p = presence_from_book(&book, None, |_| false);
let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone();
assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png"));
assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None));
book.handle_command(&message(
r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png",
))
.unwrap();
let p = presence_from_book(&book, None, |_| false);
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
}
}
+270 -7
View File
@@ -14,16 +14,113 @@
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
//! download (into a temporary path), later askers wait for the same
//! download ([`Cache::finish`] answers them all).
//!
//! A picture from the web keeps its host's validators (`ETag`,
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
//! again, it is downloaded only if it changed ([`Cache::validators`],
//! [`Arrived::Unchanged`]).
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::time::SystemTime;
use std::time::{Duration, SystemTime};
use tracing::debug;
/// Called with the cached file's path, or why it could not be fetched.
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, String>) + Send>;
pub(crate) type Waiter = Box<dyn FnOnce(Result<PathBuf, FetchError>) + Send>;
/// Why a fetch failed (for the log), and when it may be tried again.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct FetchError {
pub text: String,
pub retry: RetryHint,
}
/// When a failed fetch may be tried again, as its host told.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum RetryHint {
/// Whenever the asker's own schedule says.
#[default]
Default,
/// Not before this long (the host's `Retry-After`).
After(Duration),
/// The address is wrong or gone (HTTP 400, 404, 410): not soon.
Permanent,
}
impl FetchError {
pub fn new(text: impl Into<String>, retry: RetryHint) -> Self {
Self { text: text.into(), retry }
}
}
impl From<String> for FetchError {
fn from(text: String) -> Self {
Self::new(text, RetryHint::Default)
}
}
impl From<&str> for FetchError {
fn from(text: &str) -> Self {
Self::new(text, RetryHint::Default)
}
}
impl fmt::Display for FetchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
/// What a host said identifies the version of a picture it sent, to ask
/// later whether it changed (`If-None-Match`, `If-Modified-Since`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Validators {
pub etag: Option<String>,
pub last_modified: Option<String>,
}
impl Validators {
pub fn is_empty(&self) -> bool {
self.etag.is_none() && self.last_modified.is_none()
}
/// As kept: a `name: value` line each.
fn to_text(&self) -> String {
let mut text = String::new();
for (name, value) in [("etag", &self.etag), ("last-modified", &self.last_modified)] {
if let Some(value) = value {
text.push_str(&format!("{name}: {value}\n"));
}
}
text
}
fn from_text(text: &str) -> Self {
let mut validators = Self::default();
for line in text.lines() {
match line.split_once(": ") {
Some(("etag", value)) => validators.etag = Some(value.to_owned()),
Some(("last-modified", value)) => validators.last_modified = Some(value.to_owned()),
_ => {}
}
}
validators
}
}
/// How a download ended well.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Arrived {
/// In the temporary path, with what identifies its version (when the
/// host said).
File(Validators),
/// The host said the cached copy is still what it has (HTTP 304): the
/// copy stays, nothing was downloaded.
Unchanged,
}
/// What [`Cache::fetch`] decided.
pub(crate) enum Fetch {
@@ -80,16 +177,17 @@ pub(crate) fn icon_key(id: u32) -> String {
/// The largest picture downloaded into the cache, from the web or from the
/// server's files: animated banners of several megabytes are common. The
/// download goes to disk as it arrives, so this bounds the disk, not memory.
pub(crate) const MAX_PICTURE_BYTES: u64 = 64 << 20;
pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
/// The slowest a picture may arrive on average after its first seconds:
/// a large banner on a slow link still arrives, one trickling in forever
/// does not hold a download slot.
pub(crate) const MIN_PICTURE_RATE: u64 = 32 << 10;
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
/// The cache key of a picture on the web: only `http` and `https`
/// addresses.
/// addresses (blanks around one are not part of it).
pub(crate) fn picture_key(url: &str) -> Option<String> {
let url = url.trim();
let (scheme, rest) = url.split_once("://")?;
let web = scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https");
(web && !rest.is_empty()).then(|| format!("pictures/{:x}", md5::compute(url)))
@@ -198,10 +296,35 @@ impl Cache {
&self,
key: &str,
temp: &Path,
result: Result<(), String>,
result: Result<(), FetchError>,
max_bytes: u64,
) {
let result = result.and_then(|()| self.insert_file(key, temp, max_bytes));
let arrived = result.map(|()| Arrived::File(Validators::default()));
self.finish_with(key, temp, arrived, max_bytes);
}
/// [`finish`](Self::finish) a download from the web: a new file with
/// its validators, or the cached copy confirmed (kept, and marked as
/// used).
pub(crate) fn finish_with(
&self,
key: &str,
temp: &Path,
result: Result<Arrived, FetchError>,
max_bytes: u64,
) {
let result = result.and_then(|arrived| match arrived {
Arrived::File(validators) => {
let path = self.insert_file(key, temp, max_bytes)?;
self.keep_validators(key, &validators);
Ok(path)
}
Arrived::Unchanged => {
let mut index = self.lock();
self.touch(&mut index, key)
.ok_or_else(|| FetchError::from("cache: the copy was removed meanwhile"))
}
});
let _ = std::fs::remove_file(temp);
let waiters = self.lock().in_flight.remove(key).unwrap_or_default();
for waiter in waiters {
@@ -209,6 +332,32 @@ impl Cache {
}
}
/// What identifies the cached version of `key` (a picture from the
/// web), if it is cached and its host said.
pub(crate) fn validators(&self, key: &str) -> Option<Validators> {
if !self.lock().entries.contains_key(key) || !self.dir.join(key).is_file() {
return None;
}
let text = std::fs::read_to_string(validators_path(&self.dir, key)).ok()?;
Some(Validators::from_text(&text)).filter(|v| !v.is_empty())
}
/// Keep `validators` with `key`'s new file (none: the old ones go).
fn keep_validators(&self, key: &str, validators: &Validators) {
let path = validators_path(&self.dir, key);
if validators.is_empty() {
let _ = std::fs::remove_file(&path);
return;
}
let written = path
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&path, validators.to_text()));
if let Err(e) = written {
debug!("cache: cannot keep the validators of {key}: {e}");
}
}
/// Put a file we have (e.g. our own avatar) into the cache.
pub(crate) fn insert_copy(
&self,
@@ -263,6 +412,7 @@ impl Cache {
if let Err(e) = std::fs::remove_file(self.dir.join(&key)) {
debug!("cache: cannot remove {key}: {e}");
}
let _ = std::fs::remove_file(validators_path(&self.dir, &key));
}
}
@@ -296,6 +446,22 @@ fn scan(dir: &Path, index: &mut Index) {
index.lru.insert(tick, key.clone());
index.entries.insert(key, Entry { size, tick });
}
// Validators of pictures no longer here.
let Ok(kept) = std::fs::read_dir(dir.join(VALIDATORS).join("pictures")) else { return };
for entry in kept.flatten() {
let key = format!("pictures/{}", entry.file_name().to_string_lossy());
if !index.entries.contains_key(&key) {
let _ = std::fs::remove_file(entry.path());
}
}
}
/// The directory of the pictures' validators.
const VALIDATORS: &str = "validators";
/// Where the validators of `key` are kept.
fn validators_path(dir: &Path, key: &str) -> PathBuf {
dir.join(VALIDATORS).join(key)
}
/// The engine's cache: one [`Cache`] that [`crate::Command::AttachCache`]
@@ -464,6 +630,103 @@ mod tests {
}
}
/// A picture keeps its host's validators; confirmed unchanged, the copy
/// stays and is used; replaced without validators or evicted, they go.
#[test]
fn validators_go_with_their_picture() {
let dir = temp_dir("validators");
let cache = Cache::new(&dir);
let key = picture_key("https://example.com/v.png").unwrap();
let validators = Validators {
etag: Some("W/\"v1\"".into()),
last_modified: Some("Tue, 06 Oct 2026 10:00:00 GMT".into()),
};
assert_eq!(cache.validators(&key), None);
let (tx, rx) = mpsc::channel();
let waiter = |tx: &mpsc::Sender<_>| -> Waiter {
let tx = tx.clone();
Box::new(move |r| tx.send(r).unwrap())
};
let Fetch::Download(temp) = cache.fetch(&key, false, waiter(&tx)) else { panic!() };
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"v1").unwrap();
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
let path = rx.recv().unwrap().unwrap();
assert_eq!(cache.validators(&key), Some(validators.clone()));
// Asked again: unchanged, the same file answers both askers.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
assert!(matches!(cache.fetch(&key, true, waiter(&tx)), Fetch::Waiting));
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
assert_eq!(rx.recv().unwrap(), Ok(path.clone()));
assert_eq!(std::fs::read(&path).unwrap(), b"v1");
// They survive a restart, with their picture.
assert_eq!(Cache::new(&dir).validators(&key), Some(validators.clone()));
// A new version without validators: the old ones are not sent again.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
// (The restart above cleared the temporary files' directory.)
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"new").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
rx.recv().unwrap().unwrap();
assert_eq!(cache.validators(&key), None);
// Evicted with the picture.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
std::fs::write(&temp, b"v2").unwrap();
cache.finish_with(&key, &temp, Ok(Arrived::File(validators.clone())), 0);
rx.recv().unwrap().unwrap();
assert!(validators_path(&dir, &key).is_file());
put(&cache, "icons/1", 10, 10);
assert!(!path.exists());
assert!(!validators_path(&dir, &key).exists());
// Unchanged, but the copy went meanwhile: a failure, retried in full.
let Fetch::Download(temp) = cache.fetch(&key, true, waiter(&tx)) else { panic!() };
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 0);
assert!(rx.recv().unwrap().is_err());
std::fs::remove_dir_all(dir).unwrap();
}
/// A picture confirmed unchanged counts as used: others go first.
#[test]
fn an_unchanged_picture_counts_as_used() {
let dir = temp_dir("unchanged-used");
let cache = Cache::new(&dir);
let key = picture_key("https://example.com/u.png").unwrap();
let picture = put(&cache, &key, 400, 1000);
let icon = put(&cache, "icons/1", 400, 1000);
let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(|_| {})) else { panic!() };
cache.finish_with(&key, &temp, Ok(Arrived::Unchanged), 1000);
put(&cache, "icons/2", 400, 1000);
assert!(picture.exists(), "the picture confirmed unchanged stays");
assert!(!icon.exists(), "the least recently used file goes");
std::fs::remove_dir_all(dir).unwrap();
}
/// Validators whose picture is gone go at the next start.
#[test]
fn orphaned_validators_are_removed() {
let dir = temp_dir("orphans");
let key = picture_key("https://example.com/o.png").unwrap();
let orphan = validators_path(&dir, &key);
std::fs::create_dir_all(orphan.parent().unwrap()).unwrap();
std::fs::write(&orphan, "etag: \"x\"\n").unwrap();
let cache = Cache::new(&dir);
assert_eq!(cache.size(), 0);
assert!(!orphan.exists());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn fetch_errors_carry_their_retry_hint() {
let error = FetchError::from("HTTP 503 Service Unavailable");
assert_eq!(error.retry, RetryHint::Default);
assert_eq!(error.to_string(), "HTTP 503 Service Unavailable");
let gone = FetchError::new("HTTP 404 Not Found", RetryHint::Permanent);
assert_ne!(gone, FetchError::from("HTTP 404 Not Found"));
let text = Validators { etag: Some("\"a: b\"".into()), last_modified: None }.to_text();
assert_eq!(Validators::from_text(&text).etag.as_deref(), Some("\"a: b\""));
}
/// Pictures are cached files like the others (counted after a restart).
#[test]
fn pictures_survive_restart() {
+478 -90
View File
@@ -8,16 +8,31 @@
//! - SRV `_tsgws._tcp.<name>`: `wss://<target>:<port><path>`,
//! - SRV `_tsgw._tcp.<name>`: `ws://<target>:<port><path>`,
//!
//! TLS first at the same name; `<path>` is `path=…` from a TXT record at the
//! SRV record's name, `/v1` without one. Without any such record, as TSDNS
//! has its well-known port, the gateway itself is asked at tsgw's default
//! port: `http://<name>:7788/.well-known/tsgw` answers `{"url": "…"}`. For an
//! IP address (or `localhost`) only that is tried. What an admin publishes is
//! in `docs/gateway-admin.md`.
//! `<path>` is `path=…` from a TXT record at the SRV record's name, `/v1`
//! without one. As TSDNS has its well-known port, the gateway itself is also
//! asked at tsgw's default port: `http://<name>:7788/.well-known/tsgw`
//! answers `{"url": "…"}`; for an IP address (or `localhost`) only that is
//! tried. That answer is plain HTTP, so it is used only when nothing or a
//! plain record is published: a TLS-only publication stays TLS-only.
//!
//! Everything is asked at once (SRV and TXT at every name, and the gateway
//! at every name), so a discovery takes as long as its slowest needed
//! answer, not their sum; DNS gives up after 2 s (twice).
//!
//! The most specific name with a record wins: a parent domain's records
//! are another server's gateway when the host publishes its own. Every
//! gateway of that name is kept, best first (TLS before plain, by
//! priority, then the gateway's own answer at that name), and tried in turn
//! ([`crate::Command::ObserveGateway`]): a TLS proxy that fails falls back
//! to the plain gateway published next to it. Discovery trusts DNS and the
//! network as TSDNS does; falling back from a published `_tsgws` to a
//! published `_tsgw` is no weaker than publishing only `_tsgw`. What an
//! admin publishes is in `docs/gateway-admin.md`. Each discovery is logged
//! (target `voelin_core::discover`, the details at debug).
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};
use futures::future::{BoxFuture, FutureExt, join_all};
use hickory_resolver::TokioResolver;
@@ -26,7 +41,9 @@ use hickory_resolver::net::runtime::TokioRuntimeProvider;
use hickory_resolver::proto::rr::RData;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::task::JoinHandle;
use tokio::time::timeout;
use tracing::{debug, info};
/// The port tsgw listens on by default, where it is asked for its URL.
pub const DEFAULT_PORT: u16 = 7788;
@@ -34,9 +51,14 @@ pub const DEFAULT_PORT: u16 = 7788;
const DEFAULT_PATH: &str = "/v1";
/// Give up on asking one name's gateway after this long.
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
/// Give up on one DNS query after this long (it is sent twice).
const DNS_TIMEOUT: Duration = Duration::from_secs(2);
/// At most this many gateways are kept, best first.
const MAX_CANDIDATES: usize = 8;
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync;
type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec<String>> + Send + Sync;
type ProbeFn = dyn Fn(String) -> BoxFuture<'static, Option<String>> + Send + Sync;
/// Where [`gateway`] gets its answers from; the tests put fakes in.
#[derive(Clone)]
@@ -45,28 +67,47 @@ struct Lookups {
srv: Arc<SrvFn>,
/// The strings of the TXT records at a name.
txt: Arc<TxtFn>,
/// Where a gateway is asked for its URL.
probe_port: u16,
/// The URL a gateway at a name gives for itself (`/.well-known/tsgw`).
probe: Arc<ProbeFn>,
}
impl Lookups {
fn system() -> Self {
// The system's resolver, else (Android) a public one, as the voice
// connection's resolver does.
let resolver = TokioResolver::builder_tokio().and_then(|b| b.build()).or_else(|_| {
TokioResolver::builder_with_config(
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
TokioRuntimeProvider::default(),
)
.build()
});
let resolver = resolver.ok();
// connection's resolver does. A query that is not answered is sent
// again soon: discovery runs once a run, and finding nothing is
// final until the next.
let resolver = TokioResolver::builder_tokio()
.map(|mut b| {
let options = b.options_mut();
options.timeout = DNS_TIMEOUT;
options.attempts = options.attempts.max(2);
b
})
.and_then(|b| b.build())
.or_else(|_| {
let mut b = TokioResolver::builder_with_config(
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
TokioRuntimeProvider::default(),
);
b.options_mut().timeout = DNS_TIMEOUT;
b.build()
});
let resolver = match resolver {
Ok(resolver) => Some(resolver),
Err(e) => {
debug!(error = %e, "no DNS resolver for gateway discovery");
None
}
};
let txt_resolver = resolver.clone();
Self {
srv: Arc::new(move |name| {
let resolver = resolver.clone();
async move {
let lookup = resolver?.srv_lookup(name).await.ok()?;
let started = Instant::now();
let lookup = resolver?.srv_lookup(name.as_str()).await;
let lookup = dns_answer(&name, "SRV", started, lookup)?;
Some(
lookup
.answers()
@@ -84,7 +125,9 @@ impl Lookups {
txt: Arc::new(move |name| {
let resolver = txt_resolver.clone();
async move {
let lookup = resolver?.txt_lookup(name).await.ok()?;
let started = Instant::now();
let lookup = resolver?.txt_lookup(name.as_str()).await;
let lookup = dns_answer(&name, "TXT", started, lookup)?;
Some(
lookup
.answers()
@@ -101,30 +144,150 @@ impl Lookups {
.map(Option::unwrap_or_default)
.boxed()
}),
probe_port: DEFAULT_PORT,
probe: Arc::new(|name| {
async move {
let started = Instant::now();
let answer = match timeout(PROBE_TIMEOUT, well_known(&name, DEFAULT_PORT)).await
{
Ok(answer) => answer,
Err(_) => Err(format!("no answer within {} s", PROBE_TIMEOUT.as_secs())),
};
let elapsed_ms = started.elapsed().as_millis() as u64;
match &answer {
Ok(url) => debug!(name, %url, elapsed_ms, "tsgw well-known probe answered"),
Err(outcome) => debug!(name, %outcome, elapsed_ms, "tsgw well-known probe"),
}
answer.ok()
}
.boxed()
}),
}
}
}
/// The URL of the gateway of the server at `address` (as a bookmark has it:
/// host, host:port, an IP), if one is published.
pub async fn gateway(address: &str) -> Option<String> {
gateway_with(address, Lookups::system()).await
/// A DNS answer, the failure logged (no record at most names is normal).
fn dns_answer<T>(
name: &str,
kind: &str,
started: Instant,
lookup: Result<T, hickory_resolver::net::NetError>,
) -> Option<T> {
let elapsed_ms = started.elapsed().as_millis() as u64;
match lookup {
Ok(lookup) => Some(lookup),
Err(e) if e.is_no_records_found() => {
debug!(name, kind, elapsed_ms, "no DNS record");
None
}
Err(e) => {
debug!(name, kind, elapsed_ms, error = %e, "DNS lookup failed");
None
}
}
}
async fn gateway_with(address: &str, lookups: Lookups) -> Option<String> {
/// The URLs of the gateway of the server at `address` (as a bookmark has
/// it: host, host:port, an IP), best first: everything published, to be
/// tried in turn. Empty: none is published.
pub async fn gateways(address: &str) -> Vec<String> {
gateways_with(address, Lookups::system()).await
}
async fn gateways_with(address: &str, lookups: Lookups) -> Vec<String> {
let started = Instant::now();
let host = host_of(address);
let names = names(host);
if names.is_empty() {
return None;
debug!(address, "no gateway discovery for a server nickname");
return Vec::new();
}
if host.parse::<IpAddr>().is_err()
&& host.contains('.')
&& let Some(url) = from_srv(&names, &lookups).await
{
return Some(url);
// The gateway's own answer is asked at every name while DNS is; only
// the answer that counts is waited for.
let mut probes = Probes::start(&names, &lookups);
let srv = if host.parse::<IpAddr>().is_err() && host.contains('.') {
from_srv(&names, &lookups).await
} else {
None
};
// The gateway's own answer comes over plain HTTP: not for a server that
// publishes only TLS; at the name that publishes, or without records the
// most specific name that answers.
let (mut urls, well_known) = match &srv {
None => match probes.first().await {
Some((name, url)) => (vec![url.clone()], format!("{name}: {url}")),
None => (Vec::new(), "none".to_owned()),
},
Some(found) if found.urls.iter().any(|url| url.starts_with("ws://")) => {
let mut urls = found.urls.clone();
match probes.of(found.name).await {
Some(url) => {
let well_known = format!("{}: {url}", found.name);
if !urls.contains(&url) {
urls.push(url);
}
(urls, well_known)
}
None => (urls, "none".to_owned()),
}
}
Some(found) => (found.urls.clone(), "not used (TLS only)".to_owned()),
};
urls.truncate(MAX_CANDIDATES);
let (srv_name, srv_urls, txt) = match &srv {
Some(found) => (found.name, found.urls.as_slice(), found.txt.as_slice()),
None => ("", &[][..], &[][..]),
};
info!(
address,
names = ?names,
srv_name,
srv = ?srv_urls,
txt = ?txt,
%well_known,
result = ?urls,
elapsed_ms = started.elapsed().as_millis() as u64,
"gateway discovery"
);
urls
}
/// The gateway's own answers being asked, one per name, most specific
/// first; those still asking when dropped are given up.
struct Probes<'a>(Vec<(&'a str, JoinHandle<Option<String>>)>);
impl<'a> Probes<'a> {
fn start(names: &[&'a str], lookups: &Lookups) -> Self {
Self(
names
.iter()
.map(|name| (*name, tokio::spawn((lookups.probe)(name.to_string()))))
.collect(),
)
}
/// The answer at `name`.
async fn of(&mut self, name: &str) -> Option<String> {
let (_, probe) = self.0.iter_mut().find(|(n, _)| *n == name)?;
probe.await.ok().flatten()
}
/// The answer of the most specific name that answers.
async fn first(&mut self) -> Option<(&'a str, String)> {
for (name, probe) in &mut self.0 {
if let Some(url) = probe.await.ok().flatten() {
return Some((*name, url));
}
}
None
}
}
impl Drop for Probes<'_> {
fn drop(&mut self) {
for (_, probe) in &self.0 {
probe.abort();
}
}
from_well_known(&names, lookups.probe_port).await
}
/// The host of an address: without the port, the brackets of an IPv6
@@ -155,59 +318,103 @@ fn names(host: &str) -> Vec<&str> {
.collect()
}
/// The URL from SRV records, every name and service asked at once.
async fn from_srv(names: &[&str], lookups: &Lookups) -> Option<String> {
let queries: Vec<(&str, String)> = names
/// What SRV records publish: at `name`, the most specific name with a
/// usable record.
struct Published<'a> {
name: &'a str,
/// TLS first, by priority.
urls: Vec<String>,
/// The TXT strings at the records' names.
txt: Vec<String>,
}
/// The URLs from SRV records, every name and service asked at once, with
/// the TXT records there (the path; most names have none): those of the
/// most specific name with a usable record.
async fn from_srv<'a>(names: &[&'a str], lookups: &Lookups) -> Option<Published<'a>> {
let queries: Vec<(&str, &str, String)> = names
.iter()
.flat_map(|name| {
[("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))]
[
(*name, "wss", format!("_tsgws._tcp.{name}.")),
(*name, "ws", format!("_tsgw._tcp.{name}.")),
]
})
.collect();
let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await;
// The first (most specific, TLS first) name with a usable record.
let ((scheme, owner), (_, target, port)) =
queries.iter().zip(answers).find_map(|(q, records)| {
let (answers, texts) = futures::join!(
join_all(queries.iter().map(|(.., owner)| (lookups.srv)(owner.clone()))),
join_all(queries.iter().map(|(.., owner)| (lookups.txt)(owner.clone()))),
);
let mut found: Vec<_> = queries
.iter()
.zip(answers)
.zip(texts)
.filter_map(|((query, mut records), txt)| {
// A target of "." says there is no such service there.
let best = records.into_iter().filter(|r| r.1 != ".").min_by_key(|r| r.0)?;
Some((q, best))
})?;
let mut path = (lookups.txt)(owner.clone())
.await
.into_iter()
records.retain(|r| r.1 != ".");
records.sort_by_key(|r| r.0);
(!records.is_empty()).then_some((query, records, txt))
})
.collect();
let name = found.first()?.0.0;
found.retain(|((n, ..), ..)| *n == name);
let mut published = Published { name, urls: Vec::new(), txt: Vec::new() };
for ((_, scheme, _), records, txt) in found {
let path = path_in(&txt);
published.txt.extend(txt);
for (_, target, port) in records {
let url = format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.'));
if !published.urls.contains(&url) {
published.urls.push(url);
}
}
}
Some(published)
}
/// The path in a SRV record's name's TXT strings: `path=…`, `/v1` without
/// one.
fn path_in(txt: &[String]) -> String {
let mut path = txt
.iter()
.find_map(|s| s.strip_prefix("path=").map(str::to_owned))
.unwrap_or_else(|| DEFAULT_PATH.to_owned());
if !path.starts_with('/') {
path.insert(0, '/');
}
Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')))
path
}
/// The URL a gateway gives for itself at one of `names`, all asked at once;
/// the most specific that answers wins.
async fn from_well_known(names: &[&str], port: u16) -> Option<String> {
let answers =
join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await;
answers.into_iter().find_map(|answer| answer.ok().flatten())
}
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`.
async fn well_known(host: &str, port: u16) -> Option<String> {
let mut stream = TcpStream::connect((host, port)).await.ok()?;
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`; else what
/// happened instead.
async fn well_known(host: &str, port: u16) -> Result<String, String> {
let mut stream =
TcpStream::connect((host, port)).await.map_err(|e| format!("cannot connect: {e}"))?;
let authority =
if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
let request =
format!("GET /.well-known/tsgw HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n");
stream.write_all(request.as_bytes()).await.ok()?;
stream.write_all(request.as_bytes()).await.map_err(|e| format!("cannot ask: {e}"))?;
let mut response = Vec::new();
stream.take(16 * 1024).read_to_end(&mut response).await.ok()?;
let response = String::from_utf8(response).ok()?;
let (head, body) = response.split_once("\r\n\r\n")?;
if head.split_whitespace().nth(1) != Some("200") {
return None;
stream
.take(16 * 1024)
.read_to_end(&mut response)
.await
.map_err(|e| format!("no answer: {e}"))?;
let response = String::from_utf8(response).map_err(|_| "not text".to_owned())?;
let (head, body) = response.split_once("\r\n\r\n").ok_or("not HTTP")?;
let status = head.split_whitespace().nth(1).unwrap_or_default();
if status != "200" {
return Err(format!("http {status}"));
}
let answer: serde_json::Value =
serde_json::from_str(body).map_err(|_| "not a tsgw answer".to_owned())?;
let url = answer.get("url").and_then(|url| url.as_str()).ok_or("no url in the answer")?;
if url.starts_with("ws://") || url.starts_with("wss://") {
Ok(url.to_owned())
} else {
Err(format!("not a gateway URL: {url}"))
}
let answer: serde_json::Value = serde_json::from_str(body).ok()?;
let url = answer.get("url")?.as_str()?;
(url.starts_with("ws://") || url.starts_with("wss://")).then(|| url.to_owned())
}
#[cfg(test)]
@@ -215,8 +422,8 @@ mod tests {
use super::*;
/// DNS answers from these lists only: SRV `(name, priority, target,
/// port)`, TXT `(name, string)`.
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)], probe_port: u16) -> Lookups {
/// port)`, TXT `(name, string)`; no gateway answers for itself.
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)]) -> Lookups {
let srv: Vec<(String, u16, String, u16)> =
srv.iter().map(|(n, p, t, port)| (n.to_string(), *p, t.to_string(), *port)).collect();
let txt: Vec<(String, String)> =
@@ -231,10 +438,29 @@ mod tests {
let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect();
futures::future::ready(found).boxed()
}),
probe_port,
probe: Arc::new(|_| futures::future::ready(None).boxed()),
}
}
/// `lookups` where the gateway at a name answers `(name, url)`.
fn answering(mut lookups: Lookups, answers: &[(&str, &str)]) -> Lookups {
let answers: Vec<(String, String)> =
answers.iter().map(|(n, u)| (n.to_string(), u.to_string())).collect();
lookups.probe = Arc::new(move |name| {
let url = answers.iter().find(|a| a.0 == name).map(|a| a.1.clone());
futures::future::ready(url).boxed()
});
lookups
}
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
lookups.probe = Arc::new(move |name| {
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
});
lookups
}
/// A port nothing listens on.
fn closed_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
@@ -242,20 +468,22 @@ mod tests {
#[tokio::test]
async fn finds_the_gateway_at_the_host_or_its_domain() {
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[], 0);
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[]);
for address in ["ts.example.test", "ts.example.test:9987", "example.test"] {
assert_eq!(
gateway_with(address, lookups.clone()).await.as_deref(),
Some("ws://gw.example.test:7788/v1"),
gateways_with(address, lookups.clone()).await,
["ws://gw.example.test:7788/v1"],
"{address}"
);
}
// The parent's parent is not the domain any more.
assert_eq!(gateway_with("example", lookups).await, None);
assert!(gateways_with("example", lookups).await.is_empty());
}
/// All of the most specific name's gateways, TLS first, by priority; a
/// parent domain's only for a host without its own.
#[tokio::test]
async fn the_most_specific_name_wins_then_tls() {
async fn the_most_specific_name_wins_with_all_its_gateways() {
let lookups = fake(
&[
("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443),
@@ -264,18 +492,181 @@ mod tests {
("_tsgws._tcp.ts.example.test.", 1, "tls.example.test.", 8443),
],
&[("_tsgws._tcp.ts.example.test.", "path=/tsgw/v1")],
0,
);
assert_eq!(
gateway_with("ts.example.test", lookups.clone()).await.as_deref(),
Some("wss://tls.example.test:8443/tsgw/v1")
gateways_with("ts.example.test", lookups.clone()).await,
[
"wss://tls.example.test:8443/tsgw/v1",
"wss://backup.example.test:443/tsgw/v1",
"ws://plain.example.test:7788/v1",
]
);
assert_eq!(
gateway_with("voice.example.test", lookups).await.as_deref(),
Some("wss://domain.example.test:443/v1")
gateways_with("voice.example.test", lookups).await,
["wss://domain.example.test:443/v1"]
);
}
/// A TLS proxy in front of tsgw and tsgw itself published next to the
/// server (and again at the domain): TLS first, the plain one after it,
/// once; the gateway's own answer is the plain one again.
#[tokio::test]
async fn a_tls_proxy_falls_back_to_the_published_plain_gateway() {
let lookups = answering(
fake(
&[
("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443),
("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788),
("_tsgw._tcp.example.test.", 0, "ts.example.test.", 7788),
],
&[],
),
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
);
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["wss://gw.example.test:443/v1", "ws://ts.example.test:7788/v1"]
);
}
/// A gateway at the domain fronts another server than one of its hosts
/// that publishes its own: never a fallback for it, nor the domain's own
/// answer.
#[tokio::test]
async fn another_servers_gateway_is_no_fallback() {
let lookups = answering(
fake(
&[
("_tsgws._tcp.ts1.example.test.", 0, "gw1.example.test.", 443),
("_tsgw._tcp.ts1.example.test.", 0, "ts1.example.test.", 7788),
("_tsgws._tcp.example.test.", 0, "gw-main.example.test.", 443),
],
&[],
),
&[("example.test", "ws://main.example.test:7788/v1")],
);
assert_eq!(
gateways_with("ts1.example.test", lookups).await,
["wss://gw1.example.test:443/v1", "ws://ts1.example.test:7788/v1"]
);
}
#[tokio::test]
async fn the_gateways_own_answer_comes_last() {
let lookups = answering(
fake(&[("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788)], &[]),
&[("ts.example.test", "wss://gw.example.test/v1")],
);
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["ws://plain.example.test:7788/v1", "wss://gw.example.test/v1"]
);
}
/// The gateway's plain answer is asked with DNS, but not used.
#[tokio::test]
async fn a_tls_only_publication_is_not_widened() {
let lookups = answering(
fake(&[("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)], &[]),
&[("ts.example.test", "ws://ts.example.test:7788/v1")],
);
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["wss://gw.example.test:443/v1"]
);
}
/// `lookups` whose DNS answers take `dns` and the gateway's own `probe`.
fn slow(lookups: Lookups, dns: Duration, probe: Duration) -> Lookups {
let Lookups { srv, txt, probe: answer } = lookups;
Lookups {
srv: Arc::new(move |name| {
let found = srv(name);
async move {
tokio::time::sleep(dns).await;
found.await
}
.boxed()
}),
txt: Arc::new(move |name| {
let found = txt(name);
async move {
tokio::time::sleep(dns).await;
found.await
}
.boxed()
}),
probe: Arc::new(move |name| {
let found = answer(name);
async move {
tokio::time::sleep(probe).await;
found.await
}
.boxed()
}),
}
}
/// SRV, TXT and the gateway's own answer are asked at once: a slow
/// gateway and slow DNS cost the slower of them, not the sum; an answer
/// that is not used is not waited for.
#[tokio::test(start_paused = true)]
async fn everything_is_asked_at_once() {
let published = |srv: &[(&str, u16, &str, u16)]| {
answering(
fake(srv, &[("_tsgw._tcp.ts.example.test.", "path=/gw")]),
&[("ts.example.test", "wss://proxy.example.test/v1")],
)
};
let plain = [("_tsgw._tcp.ts.example.test.", 0, "ts.example.test.", 7788)];
let (dns, probe) = (Duration::from_millis(400), Duration::from_millis(2500));
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", slow(published(&plain), dns, probe)).await,
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
);
assert_eq!(started.elapsed().as_millis(), 2500);
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", slow(published(&plain), probe, dns)).await,
["ws://ts.example.test:7788/gw", "wss://proxy.example.test/v1"]
);
assert_eq!(started.elapsed().as_millis(), 2500);
// TLS only: the gateway's plain answer is not waited for.
let tls = [("_tsgws._tcp.ts.example.test.", 0, "gw.example.test.", 443)];
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", slow(published(&tls), dns, probe)).await,
["wss://gw.example.test:443/v1"]
);
assert_eq!(started.elapsed().as_millis(), 400);
}
/// Without records, the most specific name's gateway is waited for
/// before a parent domain's answer is taken.
#[tokio::test(start_paused = true)]
async fn without_records_the_most_specific_answer_wins() {
let mut lookups = fake(&[], &[]);
lookups.probe = Arc::new(|name| {
async move {
match name.as_str() {
"ts.example.test" => {
tokio::time::sleep(Duration::from_secs(2)).await;
Some("ws://ts.example.test:7788/v1".to_owned())
}
_ => Some("ws://example.test:7788/v1".to_owned()),
}
}
.boxed()
});
let started = tokio::time::Instant::now();
assert_eq!(
gateways_with("ts.example.test", lookups).await,
["ws://ts.example.test:7788/v1"]
);
assert_eq!(started.elapsed().as_millis(), 2000);
}
#[tokio::test]
async fn a_record_that_says_no_service_is_skipped() {
let lookups = fake(
@@ -284,12 +675,8 @@ mod tests {
("_tsgw._tcp.example.test.", 0, "gw.example.test.", 80),
],
&[("_tsgw._tcp.example.test.", "path=ws")],
closed_port(),
);
assert_eq!(
gateway_with("ts.example.test", lookups).await.as_deref(),
Some("ws://gw.example.test:80/ws")
);
assert_eq!(gateways_with("ts.example.test", lookups).await, ["ws://gw.example.test:80/ws"]);
}
/// Without records the gateway next to the server answers at its port,
@@ -313,16 +700,17 @@ mod tests {
socket.write_all(response.as_bytes()).await.unwrap();
}
});
let lookups = fake(&[], &[], port);
let lookups = probing(fake(&[], &[]), port);
for address in ["127.0.0.1", "127.0.0.1:9987", "localhost"] {
assert_eq!(
gateway_with(address, lookups.clone()).await.as_deref(),
Some("wss://gw.example.test/v1"),
gateways_with(address, lookups.clone()).await,
["wss://gw.example.test/v1"],
"{address}"
);
}
// Nothing there.
assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None);
let nothing = probing(fake(&[], &[]), closed_port());
assert!(gateways_with("127.0.0.1", nothing).await.is_empty());
}
#[test]
+520 -52
View File
@@ -38,14 +38,24 @@
//! and is removed when it ends. The directory is also where the session's
//! streams look for streams that started before we joined, next to the
//! server's `requeststreaminfo`.
//!
//! A gateway that cannot be reached, or cannot log us in yet (the server
//! does not know the identity before voice connected once; its server is
//! restarting), is tried again by itself: after 1, 2, 5, 10, 20, then every
//! 30 s, give or take 30 %, and at once when voice connects. Only a refused
//! login (signature, security level, ban, not allowed) ends it. A connection
//! is pinged every 30 s and left after 60 s without an answer. All of it is
//! logged (target `voelin_core::gateway`), never shown.
use std::time::Duration;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use futures::future::{Fuse, FusedFuture, FutureExt};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tracing::{debug, info, warn};
use voelin_gateway_proto::client::Login;
pub use voelin_gateway_proto::client::{ClientError, GatewayClient, Push};
use voelin_gateway_proto::client::{Login, Progress};
use voelin_gateway_proto::{
Action, ActivityEntry, ClientMsg, ConfigEntry, ErrorCode, EventInfo, EventQuery, EventSpec,
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
@@ -61,12 +71,16 @@ pub(crate) enum GatewayCmd {
OpenChat(ChatTarget),
CloseChat(ChatTarget),
SendChat(ChatTarget, String),
/// Waiting for the next attempt: make it now (voice connected, which
/// makes the identity known to the server; the server was selected
/// again). Nothing while connected.
RetryNow,
Stop,
}
pub(crate) enum GatewayEvent {
/// Logged in; requests go through `client`.
Connected(GatewayClient),
/// Logged in at the URL; requests go through the client.
Connected(GatewayClient, String),
Presence(Box<Presence>),
/// A push other than presence.
Push(Box<Push>),
@@ -83,42 +97,84 @@ pub async fn connect(
url: &str,
identity: &tsclientlib::Identity,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() };
voelin_gateway_proto::client::connect(url, login).await
connect_watched(url, identity, &Progress::default()).await
}
/// [`connect`], telling `progress` each step (for the log).
async fn connect_watched(
url: &str,
identity: &tsclientlib::Identity,
progress: &Progress,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
let login = Login::Identity { key: identity.key().clone(), key_offset: identity.counter() };
voelin_gateway_proto::client::connect_watched(url, login, progress).await
}
/// Observe through the first of `urls` (best first, as published) that
/// logs in.
pub(crate) async fn run(
url: String,
mut urls: Vec<String>,
identity: tsclientlib::Identity,
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
events: mpsc::UnboundedSender<GatewayEvent>,
) {
// A gateway that is away (down, restarting, a network change) is tried
// again until the session stops observing; only a refused login ends it.
// A gateway that is away (down, restarting, a network change, a proxy
// in front of it that fails) or cannot log us in yet (it does not know
// the identity before voice connected once, its server is restarting)
// is tried again until the session stops observing; only a refused
// login ends it. A round tries every URL in turn without waiting; only
// a round that fails waits.
debug!(?urls, "gateway: starting");
let mut chats = Chats::default();
let mut failures = 0;
let mut last_reason = String::new();
let reason = loop {
match attempt(&url, &identity, &mut commands, &events, &mut chats, &mut failures).await {
Ended::Stopped => break None,
Ended::Refused(reason) => break Some(reason),
Ended::Lost(reason) => {
failures += 1;
let delay = retry_delay(failures);
// Once per cause, not every minute of a long absence.
if reason != last_reason {
warn!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway unreachable");
} else {
debug!(%url, error = %reason, retry_in_s = delay.as_secs(), "gateway still unreachable");
}
last_reason.clone_from(&reason);
let _ = events.send(GatewayEvent::Retrying(reason));
if !chats.wait(delay, &mut commands).await {
break None;
let mut told = Told::default();
// Why the last failed round failed.
let mut last_round: Option<String> = None;
// Attempts since observing started or the connection was lost.
let (mut attempts, mut since) = (0, Instant::now());
let reason = 'observe: loop {
let mut lost = None;
let mut index = 0;
while index < urls.len() {
attempts += 1;
let url = urls[index].clone();
let next = urls.get(index + 1).map(String::as_str);
debug!(%url, attempt = attempts, "gateway: trying");
let at = Try { url: &url, number: attempts, since, next };
match attempt(&at, &identity, &mut commands, &events, &mut chats, &mut told).await {
Ended::Stopped => break 'observe None,
Ended::Refused(reason) => break 'observe Some(reason),
Ended::Lost { reason, logged_in } => {
lost = Some(reason);
if logged_in {
// It worked: it is tried first again, after a wait.
urls[..=index].rotate_right(1);
failures = 0;
(attempts, since) = (0, Instant::now());
break;
}
index += 1;
}
}
}
let Some(reason) = lost else { break None };
failures += 1;
let delay = retry_delay(failures, jitter());
// Past the longest wait, the same cause again is not news (a server
// only observed, never joined, cannot log us in at all).
let wait = delay.as_secs_f64();
if failures as usize > RETRY_SECONDS.len() && last_round.as_ref() == Some(&reason) {
debug!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
} else {
info!(failures, error = %reason, "gateway: trying again in {wait:.1} s");
}
last_round = Some(reason.clone());
let _ = events.send(GatewayEvent::Retrying(reason));
if !chats.wait(delay, &mut commands).await {
break None;
}
};
debug!(?reason, "gateway: stopped");
let _ = events.send(GatewayEvent::Disconnected(reason));
}
@@ -128,15 +184,125 @@ enum Ended {
Stopped,
/// The gateway refused the login: trying again would not help.
Refused(String),
/// Not reached, or lost: try again.
Lost(String),
/// Not reached, not logged in yet, or lost (after logging in): try
/// again.
Lost { reason: String, logged_in: bool },
}
/// The wait before the next attempt after `failures` failed ones in a row.
fn retry_delay(failures: u32) -> Duration {
const SECONDS: [u64; 5] = [2, 5, 15, 30, 60];
let index = (failures.max(1) as usize - 1).min(SECONDS.len() - 1);
Duration::from_secs(SECONDS[index])
/// Login errors that trying again does not change: the identity or the
/// user is not allowed. Anything else (the gateway's server away, an
/// identity voice has not made known yet, too many logins) passes.
fn refused(code: ErrorCode) -> bool {
matches!(
code,
ErrorCode::AuthFailed | ErrorCode::LevelTooLow | ErrorCode::Banned | ErrorCode::Forbidden
)
}
/// One attempt of [`run`], for the log.
struct Try<'a> {
url: &'a str,
/// Since observing started, or the connection was lost; 1 first.
number: u32,
/// When observing started, or the connection was lost.
since: Instant,
/// The URL tried next in this round if this one fails.
next: Option<&'a str>,
}
/// What was logged per URL: each cause once while it lasts (until a login
/// works), not at every attempt of a long absence.
#[derive(Default)]
struct Told(Vec<(String, String)>);
impl Told {
/// Whether `url` failing with `cause` is news.
fn news(&mut self, url: &str, cause: &str) -> bool {
if self.0.iter().any(|(u, c)| u == url && c == cause) {
return false;
}
self.0.retain(|(u, _)| u != url);
self.0.push((url.to_owned(), cause.to_owned()));
true
}
}
/// One attempt to reach a gateway and log in (TCP, TLS, the WebSocket
/// upgrade, the login's own queries at the gateway) gives up after this
/// long, so a gateway that never answers does not hold up the next one.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
/// The waits after failed rounds in a row, the last one repeated.
const RETRY_SECONDS: [u64; 6] = [1, 2, 5, 10, 20, 30];
/// The wait before the next attempt after `failures` failed rounds in a
/// row, give or take 30 % (`jitter`, -1 to 1): clients that lost the same
/// gateway do not all come back at the same moment.
fn retry_delay(failures: u32, jitter: f64) -> Duration {
let index = (failures.max(1) as usize - 1).min(RETRY_SECONDS.len() - 1);
Duration::from_secs(RETRY_SECONDS[index]).mul_f64(1.0 + 0.3 * jitter.clamp(-1.0, 1.0))
}
/// A number from -1 to 1, another each time: the standard library's
/// randomly keyed hasher over a counter and the clock.
fn jitter() -> f64 {
use std::hash::{BuildHasher, Hasher};
static COUNT: AtomicU64 = AtomicU64::new(0);
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u64(COUNT.fetch_add(1, Ordering::Relaxed));
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
hasher.write_u128(now.unwrap_or_default().as_nanos());
(hasher.finish() >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
}
/// Asking a gateway that is still connecting to try again at once, at most
/// this often ([`Observed::nudge`]): selecting servers does not hammer a
/// struggling gateway.
const NUDGE_EVERY: Duration = Duration::from_secs(5);
/// What a session's gateway observes with, so that asking again for the
/// same ([`crate::Command::ObserveGateway`], e.g. the server selected again)
/// does not start it over, at most makes it try again sooner.
pub(crate) struct Observed {
urls: Vec<String>,
/// The identity's public key.
key: String,
/// The identity's counter, which the login sends: a raised security
/// level keeps the key and changes only this.
counter: u64,
nudged: Option<Instant>,
}
impl Observed {
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
Self {
urls: urls.to_vec(),
key: identity.key().to_pub().to_ts(),
counter: identity.counter(),
nudged: None,
}
}
/// Whether this is what is observed with.
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
self.urls == urls
&& self.counter == identity.counter()
&& self.key == identity.key().to_pub().to_ts()
}
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
/// within [`NUDGE_EVERY`].
pub(crate) fn nudge(&mut self) -> bool {
self.nudge_at(Instant::now())
}
fn nudge_at(&mut self, now: Instant) -> bool {
if self.nudged.is_some_and(|at| now.saturating_duration_since(at) < NUDGE_EVERY) {
return false;
}
self.nudged = Some(now);
true
}
}
/// Messages written while the gateway is away, at most this many, go out
@@ -166,7 +332,7 @@ impl Chats {
self.unsent.push((target, text));
}
}
GatewayCmd::Stop => {}
GatewayCmd::RetryNow | GatewayCmd::Stop => {}
}
}
@@ -184,7 +350,7 @@ impl Chats {
client.send(ClientMsg::CloseChat { target })
}
GatewayCmd::SendChat(target, text) => client.send(ClientMsg::SendChat { target, text }),
GatewayCmd::Stop => Ok(()),
GatewayCmd::RetryNow | GatewayCmd::Stop => Ok(()),
}
}
@@ -200,7 +366,8 @@ impl Chats {
}
/// Wait `delay` before the next attempt, noting the commands that come
/// meanwhile; false when the session stops observing.
/// meanwhile, or until told to try now; false when the session stops
/// observing.
async fn wait(
&mut self,
delay: Duration,
@@ -213,6 +380,10 @@ impl Chats {
() = &mut sleep => return true,
cmd = commands.recv() => match cmd {
None | Some(GatewayCmd::Stop) => return false,
Some(GatewayCmd::RetryNow) => {
debug!("gateway: trying again now");
return true;
}
Some(cmd) => self.note(cmd),
},
}
@@ -230,55 +401,153 @@ const CHAT_EXTENSIONS: [&str; 4] = [
/// One connection: log in, then relay until it ends.
async fn attempt(
url: &str,
at: &Try<'_>,
identity: &tsclientlib::Identity,
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
events: &mpsc::UnboundedSender<GatewayEvent>,
chats: &mut Chats,
failures: &mut u32,
told: &mut Told,
) -> Ended {
let (client, mut pushes) = match connect(url, identity).await {
Ok(connected) => connected,
Err(ClientError::Gateway { code, message }) => {
let url = at.url;
let lost = |reason: String| Ended::Lost { reason, logged_in: false };
let progress = Progress::default();
let started = Instant::now();
let result =
tokio::time::timeout(CONNECT_TIMEOUT, connect_watched(url, identity, &progress)).await;
let elapsed_ms = started.elapsed().as_millis() as u64;
let (stage, peer) = (progress.stage(), progress.peer_addr());
let (client, mut pushes) = match result {
Ok(Ok(connected)) => connected,
Ok(Err(ClientError::Gateway { code, message })) if refused(code) => {
warn!(%url, ?code, %message, "gateway refused the login");
return Ended::Refused(format!("gateway refused login: {code:?}: {message}"));
}
Err(e) => return Ended::Lost(e.to_string()),
// Observing starts before voice: on a server we never joined, the
// first login cannot work. Voice connecting makes it try again.
Ok(Err(ClientError::Gateway { code: ErrorCode::UnknownIdentity, message })) => {
if told.news(url, "unknown identity") {
info!(%url, elapsed_ms, "the server does not know this identity yet (voice connects it); trying again");
} else {
debug!(%url, elapsed_ms, "the server does not know this identity yet");
}
return lost(format!("UnknownIdentity: {message}"));
}
Ok(Err(ClientError::Gateway { code, message })) => {
if told.news(url, &format!("{code:?}")) {
warn!(%url, ?code, %message, elapsed_ms, next = ?at.next, "gateway did not log us in; trying again");
} else {
debug!(%url, ?code, %message, elapsed_ms, "gateway still does not log us in");
}
return lost(format!("{code:?}: {message}"));
}
Ok(Err(e)) => {
let reason = e.to_string();
if told.news(url, &reason) {
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, error = %reason, next = ?at.next, "gateway unreachable");
} else {
debug!(%url, %stage, steps = %progress, elapsed_ms, error = %reason, "gateway still unreachable");
}
return lost(reason);
}
Err(_) => {
let reason = format!("no answer within {} s ({stage})", CONNECT_TIMEOUT.as_secs());
if told.news(url, &reason) {
warn!(%url, %stage, ?peer, steps = %progress, elapsed_ms, next = ?at.next, "gateway unreachable: {reason}");
} else {
debug!(%url, %stage, steps = %progress, elapsed_ms, "gateway still unreachable: {reason}");
}
return lost(reason);
}
};
*failures = 0;
info!(%url, server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
match relay(&client, &mut pushes, commands, events, chats).await {
Ok(ended) => ended,
Err(e) => Ended::Lost(e.to_string()),
*told = Told::default();
info!(
%url,
attempt = at.number,
connect_ms = elapsed_ms,
since_start_ms = at.since.elapsed().as_millis() as u64,
server = %client.info().server_name,
?peer,
steps = %progress,
capabilities = ?client.capabilities(),
"gateway connected"
);
let connected = Instant::now();
let reason = match relay(url, &client, &mut pushes, commands, events, chats, connected).await {
Ok(Ended::Lost { reason, .. }) => reason,
Ok(ended) => {
debug!(%url, connected_for_s = connected.elapsed().as_secs(), "gateway: left");
return ended;
}
Err(e) => e.to_string(),
};
warn!(%url, connected_for_s = connected.elapsed().as_secs(), error = %reason, "gateway connection lost");
Ended::Lost { reason, logged_in: true }
}
/// A connection is checked this often while nothing else asks the gateway
/// anything ([`ClientMsg::Ping`])…
const PING_EVERY: Duration = Duration::from_secs(30);
/// …and taken as lost without an answer within this long (the gateway
/// answers in turn, after requests that can take a while).
const PING_TIMEOUT: Duration = Duration::from_secs(60);
/// Whether the gateway still answers: a ping, answered in time.
async fn alive(client: &GatewayClient) -> Result<(), String> {
match tokio::time::timeout(PING_TIMEOUT, client.request(ClientMsg::Ping)).await {
// Any answer will do, also an error from an older gateway.
Ok(Ok(_) | Err(ClientError::Gateway { .. })) => Ok(()),
Ok(Err(e)) => Err(e.to_string()),
Err(_) => Err(format!("no answer to a ping within {} s", PING_TIMEOUT.as_secs())),
}
}
async fn relay(
url: &str,
client: &GatewayClient,
pushes: &mut mpsc::UnboundedReceiver<Push>,
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
events: &mpsc::UnboundedSender<GatewayEvent>,
chats: &mut Chats,
connected: Instant,
) -> Result<Ended, ClientError> {
let lost = |reason: String| Ended::Lost { reason, logged_in: true };
// Messages with their gateway ids, pins, reactions and topics of open
// chats (older gateways answer `unknown_type` as a push; ignored).
if CHAT_EXTENSIONS.iter().any(|f| client.has(f)) {
client.send(ClientMsg::Enable { features: Vec::new() })?;
}
let _ = events.send(GatewayEvent::Connected(client.clone()));
let _ = events.send(GatewayEvent::Connected(client.clone(), url.to_owned()));
client.subscribe_presence()?;
chats.restore(client)?;
let mut presence = Presence::default();
let mut synced = false;
// A connection that died without closing (a network change, sleep, a
// NAT that forgot it) shows only when the gateway stops answering.
let start = tokio::time::Instant::now() + PING_EVERY;
let mut keepalive = tokio::time::interval_at(start, PING_EVERY);
keepalive.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let ping = Fuse::terminated();
tokio::pin!(ping);
loop {
tokio::select! {
push = pushes.recv() => match push {
None | Some(Push::Disconnected(None)) => {
return Ok(Ended::Lost("the gateway closed the connection".into()));
return Ok(lost("the gateway closed the connection".into()));
}
Some(Push::Disconnected(Some(reason))) => return Ok(Ended::Lost(reason)),
Some(Push::Disconnected(Some(reason))) => return Ok(lost(reason)),
Some(Push::PresenceSnapshot(snapshot)) => {
presence = Presence::from_snapshot(snapshot);
if !synced {
synced = true;
info!(
%url,
channels = presence.channels.len(),
clients = presence.clients.len(),
since_connect_ms = connected.elapsed().as_millis() as u64,
"gateway presence"
);
}
let _ = events.send(GatewayEvent::Presence(Box::new(presence.clone())));
}
Some(Push::PresenceDelta(delta)) => {
@@ -289,7 +558,7 @@ async fn relay(
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
// The gateway forgot the login (restarted): log in again.
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
return Ok(Ended::Lost(format!("gateway session lost: {message}")));
return Ok(lost(format!("gateway session lost: {message}")));
}
Some(push) => {
let _ = events.send(GatewayEvent::Push(Box::new(push)));
@@ -299,6 +568,12 @@ async fn relay(
None | Some(GatewayCmd::Stop) => return Ok(Ended::Stopped),
Some(cmd) => chats.apply(client, cmd)?,
},
_ = keepalive.tick(), if ping.is_terminated() => ping.set(alive(client).fuse()),
answer = &mut ping => {
if let Err(reason) = answer {
return Ok(lost(reason));
}
}
}
}
}
@@ -528,6 +803,8 @@ pub struct Pin {
pub enum GatewayUpdate {
/// Logged in.
Connected {
/// Where: the first of the published URLs that logged in.
url: String,
gateway_id: String,
server_uid: String,
server_name: String,
@@ -873,3 +1150,194 @@ pub(crate) struct ReactionPush {
pub added: bool,
pub count: u32,
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use futures::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::Message;
use voelin_gateway_proto::{Envelope, ServerMsg};
use super::*;
fn millis(d: Duration) -> u64 {
(d.as_secs_f64() * 1000.0).round() as u64
}
#[test]
fn retries_come_soon_then_every_30_s_spread() {
let seconds: Vec<u64> = (0..=8).map(|n| retry_delay(n, 0.0).as_secs()).collect();
assert_eq!(seconds, [1, 1, 2, 5, 10, 20, 30, 30, 30]);
// Give or take 30 %.
assert_eq!(millis(retry_delay(1, -1.0)), 700);
assert_eq!(millis(retry_delay(1, 1.0)), 1300);
assert_eq!(millis(retry_delay(6, 1.0)), 39_000);
assert_eq!(millis(retry_delay(3, 7.0)), millis(retry_delay(3, 1.0)));
let samples: Vec<f64> = (0..1000).map(|_| jitter()).collect();
assert!(samples.iter().all(|j| (-1.0..1.0).contains(j)), "{samples:?}");
assert!(samples.iter().any(|j| *j < -0.5) && samples.iter().any(|j| *j > 0.5));
}
#[test]
fn the_same_observation_is_nudged_at_most_every_5_s() {
let identity = tsclientlib::Identity::create();
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
let mut observed = Observed::new(&urls, &identity);
assert!(observed.same(&urls, &identity));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
// Its security level raised: logged in with the new counter.
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
assert!(!observed.same(&urls, &raised));
let now = Instant::now();
assert!(observed.nudge_at(now));
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
assert!(observed.nudge_at(now + NUDGE_EVERY));
assert!(!observed.nudge_at(now + NUDGE_EVERY + Duration::from_secs(1)));
}
#[test]
fn only_some_login_errors_are_final() {
use ErrorCode as E;
for code in [E::AuthFailed, E::LevelTooLow, E::Banned, E::Forbidden] {
assert!(refused(code), "{code:?}");
}
for code in [
E::Unavailable,
E::Internal,
E::RateLimited,
E::UnknownIdentity,
E::NotAuthenticated,
E::BadRequest,
E::Unknown,
] {
assert!(!refused(code), "{code:?}");
}
}
#[tokio::test(start_paused = true)]
async fn retry_now_ends_the_wait() {
let (tx, mut rx) = mpsc::unbounded_channel();
let mut chats = Chats::default();
let start = tokio::time::Instant::now();
// What comes meanwhile is noted; RetryNow ends the wait at once.
tx.send(GatewayCmd::OpenChat(ChatTarget::Channel(1))).unwrap();
tx.send(GatewayCmd::RetryNow).unwrap();
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
assert_eq!(start.elapsed(), Duration::ZERO);
assert_eq!(chats.open, [ChatTarget::Channel(1)]);
// Told 3 s into a wait of 30.
let told = tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(3)).await;
tx.send(GatewayCmd::RetryNow).unwrap();
tx
});
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
assert_eq!(millis(start.elapsed()), 3000);
let tx = told.await.unwrap();
// Not told: the whole wait.
assert!(chats.wait(Duration::from_secs(30), &mut rx).await);
assert_eq!(millis(start.elapsed()), 33_000);
tx.send(GatewayCmd::Stop).unwrap();
assert!(!chats.wait(Duration::from_secs(30), &mut rx).await);
}
/// A logged-in client of a gateway on an in-memory connection that
/// answers pings when `pings`; counts the pings.
async fn gateway(
pings: bool,
) -> (GatewayClient, mpsc::UnboundedReceiver<Push>, Arc<AtomicUsize>) {
let (near, far) = tokio::io::duplex(64 * 1024);
let count = Arc::new(AtomicUsize::new(0));
let counted = count.clone();
tokio::spawn(async move {
let mut ws = tokio_tungstenite::accept_async(far).await.unwrap();
let hello = ServerMsg::Hello {
gateway_id: "gw".into(),
server_uid: "server".into(),
server_name: "Server".into(),
nonce: "n".into(),
capabilities: Vec::new(),
};
let text = serde_json::to_string(&Envelope::new(hello)).unwrap();
ws.send(Message::Text(text.into())).await.unwrap();
while let Some(Ok(frame)) = ws.next().await {
let Message::Text(text) = frame else { continue };
let env: Envelope<ClientMsg> = serde_json::from_str(text.as_str()).unwrap();
let reply = match env.msg {
ClientMsg::Resume { .. } => ServerMsg::AuthOk {
uid: "me".into(),
token: "t".into(),
token_expires: 0,
capabilities: Vec::new(),
},
ClientMsg::Ping => {
counted.fetch_add(1, Ordering::SeqCst);
if !pings {
continue;
}
ServerMsg::Pong
}
_ => ServerMsg::Ok,
};
let text = serde_json::to_string(&Envelope::with_id(env.id.unwrap_or(0), reply));
if ws.send(Message::Text(text.unwrap().into())).await.is_err() {
break;
}
}
});
let (ws, _) = tokio_tungstenite::client_async("ws://gw.test/v1", near).await.unwrap();
let (client, pushes) = GatewayClient::start(ws, Login::Token("t".into())).await.unwrap();
(client, pushes, count)
}
#[tokio::test(start_paused = true)]
async fn a_gateway_that_stops_answering_is_left() {
let (client, mut pushes, pings) = gateway(false).await;
let (_tx, mut commands) = mpsc::unbounded_channel();
let (events, _events) = mpsc::unbounded_channel();
let start = tokio::time::Instant::now();
let mut chats = Chats::default();
let ended = relay(
"ws://gw.test/v1",
&client,
&mut pushes,
&mut commands,
&events,
&mut chats,
Instant::now(),
)
.await
.unwrap();
let Ended::Lost { reason, logged_in: true } = ended else { panic!("not lost") };
assert!(reason.contains("ping"), "{reason}");
assert_eq!(millis(start.elapsed()), millis(PING_EVERY + PING_TIMEOUT));
assert_eq!(pings.load(Ordering::SeqCst), 1);
}
#[tokio::test(start_paused = true)]
async fn a_gateway_that_answers_pings_is_kept() {
let (client, mut pushes, pings) = gateway(true).await;
let (_tx, mut commands) = mpsc::unbounded_channel();
let (events, _events) = mpsc::unbounded_channel();
let mut chats = Chats::default();
let relayed = tokio::time::timeout(
// The 20th ping at 600 s, answered.
Duration::from_secs(615),
relay(
"ws://gw.test/v1",
&client,
&mut pushes,
&mut commands,
&events,
&mut chats,
Instant::now(),
),
)
.await;
assert!(relayed.is_err(), "the connection was left");
assert_eq!(pings.load(Ordering::SeqCst), 20);
}
}
+32 -5
View File
@@ -96,6 +96,10 @@ use voelin_stream::{
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
};
pub use voice::VoiceOptions;
/// Banners are downloaded and shown by the same rule.
pub use web::is_svg;
/// Pictures from the web go through the desktop's proxy (set at startup).
pub use web::set_proxy_resolver;
pub type SessionId = u64;
@@ -108,6 +112,11 @@ pub const POKE_MESSAGE_MAX: usize = 100;
pub enum Command {
/// Main account proof for every current and future voice connection.
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
/// What voice servers are shown of the main account (its avatar and
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
/// every connection that presents the account's myTS ID, once connected
/// and when it changes; cleared on a sign-out.
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
ConnectVoice {
session: SessionId,
options: Box<VoiceOptions>,
@@ -115,10 +124,14 @@ pub enum Command {
DisconnectVoice {
session: SessionId,
},
/// Invisible presence and relay chat through a `tsgw` gateway.
/// Invisible presence and relay chat through a `tsgw` gateway: the first
/// of `urls` (best first, [`discover::gateways`]) that logs in, tried in
/// turn again whenever it is lost. Sent again with the same `urls` and
/// identity while it runs, it is not started over; while still
/// connecting, it tries again at once (at most every 5 s).
ObserveGateway {
session: SessionId,
url: String,
urls: Vec<String>,
identity: Box<tsclientlib::Identity>,
},
/// Invisible presence and relay chat with own ServerQuery credentials.
@@ -671,9 +684,10 @@ pub enum Event {
request: RequestId,
result: Result<(), String>,
},
/// A client's avatar is in the cache: `path`, its MD5 `hash`
/// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears
/// with an avatar and when it changes.
/// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a
/// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address
/// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]).
/// Comes when the client appears with an avatar and when it changes.
AvatarReady {
session: SessionId,
client_uid: String,
@@ -849,6 +863,7 @@ async fn run(
contacts.load().await;
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let (myts_identity, _) = watch::channel(None);
let (myts_data, _) = watch::channel(None);
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
@@ -906,6 +921,16 @@ async fn run(
});
continue;
}
Command::SetMytsData(data) => {
myts_data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
continue;
}
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
@@ -982,6 +1007,7 @@ async fn run(
settings.clone(),
engine.clone(),
myts_identity.subscribe(),
myts_data.subscribe(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -1061,6 +1087,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. }
+581 -53
View File
@@ -15,7 +15,7 @@ use std::time::Duration;
use tokio::time::Instant;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::{debug, warn};
use tracing::{debug, info, warn};
use tsclientlib::ClientId;
use voelin_audio::AudioSettings;
use voelin_gateway_proto::{ErrorCode, HistoryEntry, StreamEntry, StreamSpec, feature};
@@ -23,7 +23,7 @@ use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails,
use voelin_stream::ClientState;
use crate::audio::{self, AudioEvent, AudioHandle, AudioIn};
use crate::cache::{self, Fetch, SharedCache, Waiter};
use crate::cache::{self, Fetch, FetchError, RetryHint, SharedCache, Waiter};
use crate::contacts::{Contacts, Relation};
use crate::files::{self, DownloadTo, Report, RequestId, Sink, TransferId, TransferState};
use crate::gateway::{
@@ -87,10 +87,12 @@ impl SessionHandle {
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(
Session::new(id, events, frames, audio_settings, shared, myts_identity).run(rx),
Session::new(id, events, frames, audio_settings, shared, myts_identity, myts_data)
.run(rx),
);
Self { tx }
}
@@ -119,15 +121,26 @@ enum SourceEvent {
/// Time to fetch the host banner again (`banner_gfx_interval_s`).
ReloadBanner(String),
/// Image completion is checked against the current connection and presence.
ImageFinished(bool, u64, ImageRequest, Result<PathBuf, String>),
ImageFinished(bool, u64, ImageRequest, Result<PathBuf, FetchError>),
}
/// Identity of a wanted image, independent of its transport.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum ImageRequest {
Avatar { uid: String, hash: String },
Avatar {
uid: String,
hash: String,
},
/// A client's myTeamSpeak avatar (TeamSpeak 6), on the web.
MytsAvatar {
uid: String,
url: String,
},
Icon(u32),
Picture(String),
/// A picture a chat message shows ([`Command::FetchPicture`]), on the
/// web.
ChatPicture(String),
}
/// An image download over the voice connection, finished in the cache
@@ -146,6 +159,7 @@ struct ImageDownload {
impl ImageDownload {
fn finish(&self, result: Result<(), String>) {
if !self.done.swap(true, Ordering::AcqRel) {
let result = result.map_err(FetchError::from);
self.cache.finish(&self.key, &self.temp, result, max_cache_bytes(&self.settings));
}
}
@@ -157,11 +171,113 @@ impl Drop for ImageDownload {
}
}
/// At most three retries (after 1, 4 and 16 seconds) per image version.
/// Keeping exhausted entries prevents presence traffic from causing a retry storm.
/// Retries per image version ([`retry_delay`]). Keeping exhausted entries
/// prevents presence traffic from causing a retry storm.
#[derive(Default)]
struct ImageRetry {
failures: u8,
due: Option<Instant>,
/// Its host asked to wait until `due` (`Retry-After`): the host
/// banner's reloads wait too.
busy: bool,
/// Its address was found wrong or gone (HTTP 400, 404, 410).
gone: bool,
}
/// When to try an image again after its `failures`-th failed download,
/// which ended as `hint` says (`gone`: its address was found wrong or gone
/// before). A banner after 1, 4, 16, 60, 300 and 900 seconds, then every
/// 15 minutes while it is shown (its host may be away for a while); one
/// whose address is wrong or gone after 15 minutes, then every hour; one
/// whose host is busy when it says. Avatars, icons and chat pictures after
/// 1, 4 and 16 seconds, then no more.
fn retry_delay(
request: &ImageRequest,
failures: u8,
hint: RetryHint,
gone: bool,
) -> Option<Duration> {
const BANNERS: [u64; 6] = [1, 4, 16, 60, 300, 900];
let failures = usize::from(failures.max(1));
match (request, hint) {
(ImageRequest::Picture(_), RetryHint::Permanent) => {
Some(Duration::from_secs(if gone { 3600 } else { 900 }))
}
(ImageRequest::Picture(_), RetryHint::After(wait)) => Some(wait),
(ImageRequest::Picture(_), RetryHint::Default) => {
Some(Duration::from_secs(BANNERS[(failures - 1).min(5)]))
}
_ if failures <= 3 => Some(Duration::from_secs(1 << (2 * (failures - 1)))),
_ => None,
}
}
/// A failed image download in the log, with what it was and why: banners
/// at once, with the address the first time (its host, port and path: a
/// query may be a signed link's secret) and the host after, and once when
/// their address is found wrong or gone (`newly_gone`; `reload_s`: the
/// host banner's reload interval); avatars and icons in the server's files
/// when they give up (their files unreachable, a closed file transfer
/// port).
fn log_image_failure(
request: &ImageRequest,
failures: u8,
retry_in: Option<Duration>,
error: &FetchError,
newly_gone: bool,
reload_s: Option<u64>,
) {
let retry_in_s = retry_in.map(|d| d.as_secs());
match request {
ImageRequest::Picture(url)
if newly_gone || (failures <= 6 && error.retry != RetryHint::Permanent) =>
{
let host = web::host_of(url);
let url = (failures == 1).then(|| web::loggable(url));
let what = match (newly_gone, reload_s) {
(false, _) => "banner not downloaded",
(true, None) => {
"banner not downloaded: its address is wrong or gone, so it is tried again only \
after 15 minutes, then hourly"
}
(true, Some(_)) => {
"host banner not downloaded: its address is wrong or gone, so it is tried again \
only at the server's reload interval, or hourly"
}
};
match url {
Some(url) => {
info!(%host, %url, failures, ?retry_in_s, ?reload_s, %error, "{what}");
}
None => info!(%host, failures, ?retry_in_s, ?reload_s, %error, "{what}"),
}
}
// Not the address: a query may be a signed link's secret.
ImageRequest::Picture(url) => {
let host = web::host_of(url);
debug!(%host, failures, ?retry_in_s, %error, "banner not downloaded");
}
ImageRequest::MytsAvatar { url, .. } if retry_in.is_none() => {
let host = web::host_of(url);
info!(%host, %error, "myTeamSpeak avatar not downloaded");
}
ImageRequest::Avatar { .. } | ImageRequest::Icon(_) if retry_in.is_none() => {
info!(?request, %error, "server file not downloaded (avatar or icon)");
}
// Not the address: someone's message gave it.
ImageRequest::ChatPicture(url) => {
let host = web::host_of(url);
debug!(%host, failures, ?retry_in_s, %error, "chat picture not downloaded");
}
_ => debug!(?request, failures, ?retry_in_s, %error, "image download failed"),
}
}
/// Whether an explicitly requested image belongs to the voice connection
/// (downloaded over it, so dropped with it); a myTeamSpeak avatar is on the
/// web.
fn voice_bound(request: &ImageRequest) -> bool {
!matches!(request, ImageRequest::MytsAvatar { .. })
}
/// Our live stream, for the gateway's directory.
@@ -175,6 +291,7 @@ struct OwnStream {
struct Session {
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
@@ -187,6 +304,9 @@ struct Session {
gateway_presence: Option<Presence>,
/// The logged-in gateway, for requests.
gateway_client: Option<GatewayClient>,
/// What the running `gateway` observes with: asking again for the same
/// does not start it over.
gateway_observed: Option<gateway::Observed>,
query: Option<(u64, mpsc::UnboundedSender<QueryCmd>)>,
query_presence: Option<Presence>,
audio: Option<AudioHandle>,
@@ -222,6 +342,13 @@ struct Session {
contacts_rx: Option<watch::Receiver<u64>>,
/// Avatars reported per client unique id (their hash), voice only.
avatars: HashMap<String, String>,
/// myTeamSpeak avatars wanted per client unique id (their link), any
/// presence: where the server's avatar is not shown.
myts_avatars: HashMap<String, String>,
/// Server avatars that could not be downloaded (retries used up), per
/// client unique id (their hash): the client's myTeamSpeak avatar is
/// shown instead, until it sets another.
server_avatars_failed: HashMap<String, String>,
/// Icons reported or being fetched, voice only.
icons: HashSet<u32>,
/// Pictures on the web (banners, badges) reported or being fetched, by
@@ -231,6 +358,9 @@ struct Session {
/// fetched, by address, with the size they may have
/// ([`Command::FetchPicture`]).
chat_pictures: HashMap<String, u64>,
/// Banner addresses that cannot be fetched at all (another scheme),
/// logged once.
unfetchable: HashSet<String>,
image_epoch: u64,
images_enabled: bool,
image_retries: HashMap<ImageRequest, ImageRetry>,
@@ -257,19 +387,24 @@ impl Session {
audio_settings: AudioSettings,
shared: Shared,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
let contacts_rx = Some(contacts.watch());
Self {
myts_identity,
myts_data,
cache,
contacts,
contacts_rx,
avatars: HashMap::new(),
myts_avatars: HashMap::new(),
server_avatars_failed: HashMap::new(),
icons: HashSet::new(),
pictures: HashSet::new(),
chat_pictures: HashMap::new(),
unfetchable: HashSet::new(),
image_epoch: 0,
images_enabled: settings.current().get(&CACHE_FETCH_IMAGES),
image_retries: HashMap::new(),
@@ -290,6 +425,7 @@ impl Session {
gateway: None,
gateway_presence: None,
gateway_client: None,
gateway_observed: None,
query: None,
query_presence: None,
audio: None,
@@ -398,6 +534,7 @@ impl Session {
}
let link = VoiceLink {
myts_identity: self.myts_identity.clone(),
myts_data: self.myts_data.clone(),
session: self.id,
events: self.events.clone(),
settings: self.settings.clone(),
@@ -414,13 +551,32 @@ impl Session {
let _ = tx.send(VoiceCmd::Disconnect);
}
}
Command::ObserveGateway { url, identity, .. } => {
Command::ObserveGateway { urls, identity, .. } => {
// Asked again for the same (the server selected again): not
// started over; while still connecting, it tries again now
// (not every time: a struggling gateway is not hammered).
if let (Some((_, tx)), Some(observed)) = (&self.gateway, &mut self.gateway_observed)
&& observed.same(&urls, &identity)
{
if self.state.observe == ObserveState::Connecting && observed.nudge() {
let _ = tx.send(GatewayCmd::RetryNow);
}
return;
}
self.stop_observing();
if urls.is_empty() {
return;
}
let generation = self.next_generation();
self.known_server(format!("gateway:{url}"));
// Each is published for this server (history before its
// unique id is known).
for url in &urls {
self.known_server(format!("gateway:{url}"));
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (ev_tx, ev_rx) = mpsc::unbounded_channel();
tokio::spawn(gateway::run(url, *identity, cmd_rx, ev_tx));
self.gateway_observed = Some(gateway::Observed::new(&urls, &identity));
tokio::spawn(gateway::run(urls, *identity, cmd_rx, ev_tx));
self.forward(ev_rx, move |e| SourceEvent::Gateway(generation, e));
self.gateway = Some((generation, cmd_tx));
self.state.observe = ObserveState::Connecting;
@@ -676,9 +832,13 @@ impl Session {
.voice_presence
.as_ref()
.and_then(|p| p.client_by_uid(&client_uid))
.and_then(|c| c.avatar.clone());
if let Some(hash) = hash {
.and_then(|c| c.avatar.clone())
.filter(|hash| self.server_avatars_failed.get(&client_uid) != Some(hash));
let myts = self.shown_client(&client_uid).and_then(|c| c.myts_avatar.clone());
if let Some(hash) = hash.filter(|_| self.voice.is_some()) {
self.fetch_avatar(&client_uid, &hash, true);
} else if let Some(url) = myts {
self.fetch_myts_avatar(&client_uid, &url, true);
}
}
Command::FetchPicture { url, max_bytes, .. } => {
@@ -687,7 +847,7 @@ impl Session {
&& !self.chat_pictures.contains_key(&url)
{
self.chat_pictures.insert(url.clone(), max_bytes);
self.fetch_picture(&url, false);
self.fetch_chat_picture(&url);
}
}
Command::ListOfflineMessages { request, .. } => {
@@ -718,6 +878,7 @@ impl Session {
}
// Engine-wide.
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
@@ -840,9 +1001,12 @@ impl Session {
self.image_epoch += 1;
self.image_retries.clear();
self.avatars.clear();
self.myts_avatars.clear();
self.server_avatars_failed.clear();
self.icons.clear();
self.pictures.clear();
self.chat_pictures.clear();
self.unfetchable.clear();
self.contact_audio.clear();
self.priority_audio = Default::default();
self.stream_friends.clear();
@@ -880,7 +1044,7 @@ impl Session {
}
fn image_waiter(&self, request: ImageRequest, requested: bool) -> Waiter {
let epoch = if requested {
let epoch = if requested && voice_bound(&request) {
self.voice.as_ref().map_or(0, |(generation, _)| *generation)
} else {
self.image_epoch
@@ -898,6 +1062,45 @@ impl Session {
self.fetch_image(key, files::avatar_path(uid).map(|path| (0, path)), false, waiter);
}
/// The myTeamSpeak avatars of the presence shown (any source) where the
/// server's avatar is not shown: none set, no voice connection to
/// download it over, or its download gave up. As the official client:
/// the server's avatar first.
fn fetch_myts_avatars(&mut self, p: &Presence) {
if !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
let mut wanted = HashMap::with_capacity(self.myts_avatars.len());
for c in p.clients.values() {
let (Some(uid), Some(url)) = (&c.uid, &c.myts_avatar) else { continue };
let server_avatar = c.avatar.is_some()
&& self.voice.is_some()
&& self.server_avatars_failed.get(uid) != c.avatar.as_ref();
if server_avatar {
continue;
}
if self.myts_avatars.get(uid) != Some(url) {
self.fetch_myts_avatar(uid, url, false);
}
wanted.insert(uid.clone(), url.clone());
}
self.myts_avatars = wanted;
}
fn fetch_myts_avatar(&self, uid: &str, url: &str, requested: bool) {
let request = ImageRequest::MytsAvatar { uid: uid.into(), url: url.into() };
let waiter = self.image_waiter(request, requested);
web::fetch_avatar(self.cache.current(), url, max_cache_bytes(&self.settings), waiter);
}
/// The client shown (any presence) with this unique id.
fn shown_client(&self, uid: &str) -> Option<&voelin_model::ClientInfo> {
[&self.voice_presence, &self.gateway_presence, &self.query_presence]
.into_iter()
.find_map(|p| p.as_ref())
.and_then(|p| p.client_by_uid(uid))
}
fn fetch_icon(&self, icon: u32) {
let waiter = self.image_waiter(ImageRequest::Icon(icon), false);
self.fetch_image(cache::icon_key(icon), Some((0, files::icon_path(icon))), false, waiter);
@@ -908,19 +1111,10 @@ impl Session {
ImageRequest::Avatar { uid, hash } => {
self.voice.is_some() && self.avatars.get(uid) == Some(hash)
}
ImageRequest::MytsAvatar { uid, url } => self.myts_avatars.get(uid) == Some(url),
ImageRequest::Icon(id) => self.voice.is_some() && self.icons.contains(id),
ImageRequest::Picture(url) => {
self.pictures.contains(url) || self.chat_pictures.contains_key(url)
}
}
}
/// How large the picture at `url` may be: a chat picture as large as
/// it was asked for, unless it is also a banner or badge.
fn picture_limit(&self, url: &str) -> u64 {
match self.chat_pictures.get(url) {
Some(max) if !self.pictures.contains(url) => (*max).min(cache::MAX_PICTURE_BYTES),
_ => cache::MAX_PICTURE_BYTES,
ImageRequest::Picture(url) => self.pictures.contains(url),
ImageRequest::ChatPicture(url) => self.chat_pictures.contains_key(url),
}
}
@@ -929,16 +1123,28 @@ impl Session {
requested: bool,
epoch: u64,
request: ImageRequest,
result: Result<PathBuf, String>,
result: Result<PathBuf, FetchError>,
) {
let wanted = if requested {
matches!(&request, ImageRequest::Avatar { uid, hash }
if self.voice.is_some() && self.voice_presence.as_ref()
.and_then(|p| p.client_by_uid(uid)).and_then(|c| c.avatar.as_ref()) == Some(hash))
match &request {
ImageRequest::Avatar { uid, hash } => {
self.voice.is_some()
&& self
.voice_presence
.as_ref()
.and_then(|p| p.client_by_uid(uid))
.and_then(|c| c.avatar.as_ref())
== Some(hash)
}
ImageRequest::MytsAvatar { uid, url } => {
self.shown_client(uid).and_then(|c| c.myts_avatar.as_ref()) == Some(url)
}
_ => false,
}
} else {
self.wants_image(&request)
};
let current = if requested {
let current = if requested && voice_bound(&request) {
self.is_current(Source::Voice, epoch)
} else {
epoch == self.image_epoch
@@ -949,13 +1155,24 @@ impl Session {
match result {
Ok(path) => {
self.image_retries.remove(&request);
// A server avatar given up on came after all (asked for
// again): it is shown again in place of the myTeamSpeak one.
if let ImageRequest::Avatar { uid, hash } = &request
&& self.server_avatars_failed.get(uid) == Some(hash)
{
self.server_avatars_failed.remove(uid);
if let Some(presence) = self.voice_presence.clone() {
self.fetch_myts_avatars(&presence);
}
}
if !requested && !self.settings.current().get(&CACHE_FETCH_IMAGES) {
return;
}
// A chat picture already in the cache may be larger than
// asked for now.
if let ImageRequest::Picture(url) = &request
&& std::fs::metadata(&path).is_ok_and(|m| m.len() > self.picture_limit(url))
if let ImageRequest::ChatPicture(url) = &request
&& let Some(max) = self.chat_pictures.get(url)
&& std::fs::metadata(&path).is_ok_and(|m| m.len() > *max)
{
return;
}
@@ -964,23 +1181,49 @@ impl Session {
ImageRequest::Avatar { uid: client_uid, hash } => {
Event::AvatarReady { session, client_uid, hash, path }
}
// The address in place of a hash: it changes with the
// picture.
ImageRequest::MytsAvatar { uid: client_uid, url } => {
Event::AvatarReady { session, client_uid, hash: url, path }
}
ImageRequest::Icon(icon) => Event::IconReady { session, icon, path },
ImageRequest::Picture(url) => Event::PictureReady { session, url, path },
ImageRequest::Picture(url) | ImageRequest::ChatPicture(url) => {
Event::PictureReady { session, url, path }
}
});
}
Err(error) => {
debug!(?request, %error, "image download failed");
let retry = self
.image_retries
.entry(request)
.or_insert(ImageRetry { failures: 0, due: None });
retry.failures = retry.failures.saturating_add(1);
retry.due = match retry.failures {
1..=3 => {
Some(Instant::now() + Duration::from_secs(1 << (2 * (retry.failures - 1))))
let avatar_of = match &request {
ImageRequest::Avatar { uid, hash } => Some((uid.clone(), hash.clone())),
_ => None,
};
// The host banner is asked for again at its reload interval too.
let reload_s = match (&request, &self.banner_reload) {
(ImageRequest::Picture(url), Some((reloaded, every_s, _)))
if url == reloaded =>
{
Some((*every_s).max(web::MIN_RELOAD.as_secs()))
}
_ => None,
};
let retry = self.image_retries.entry(request.clone()).or_default();
retry.failures = retry.failures.saturating_add(1);
let delay = retry_delay(&request, retry.failures, error.retry, retry.gone);
retry.due = delay.map(|delay| Instant::now() + delay);
retry.busy = matches!(error.retry, RetryHint::After(_));
let newly_gone = error.retry == RetryHint::Permanent && !retry.gone;
retry.gone |= newly_gone;
log_image_failure(&request, retry.failures, delay, &error, newly_gone, reload_s);
// The server's avatar gave up (its files unreachable): the
// myTeamSpeak one, if the client has one.
if let (None, Some((uid, hash))) = (retry.due, avatar_of)
&& self.server_avatars_failed.get(&uid) != Some(&hash)
{
self.server_avatars_failed.insert(uid, hash);
if let Some(presence) = self.voice_presence.clone() {
self.fetch_myts_avatars(&presence);
}
}
}
}
}
@@ -991,6 +1234,8 @@ impl Session {
self.images_enabled = enabled;
self.image_epoch += 1;
self.avatars.clear();
self.myts_avatars.clear();
self.server_avatars_failed.clear();
self.icons.clear();
self.pictures.clear();
self.chat_pictures.clear();
@@ -1029,8 +1274,10 @@ impl Session {
for request in ready {
match request {
ImageRequest::Avatar { uid, hash } => self.fetch_avatar(&uid, &hash, false),
ImageRequest::MytsAvatar { uid, url } => self.fetch_myts_avatar(&uid, &url, false),
ImageRequest::Icon(icon) => self.fetch_icon(icon),
ImageRequest::Picture(url) => self.fetch_picture(&url, true),
ImageRequest::ChatPicture(url) => self.fetch_chat_picture(&url),
}
}
}
@@ -1075,17 +1322,25 @@ impl Session {
if !enabled {
return;
}
let all = std::iter::once(&p.server.banner_gfx_url)
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref()))
.filter(|u| !u.is_empty());
let mut urls = HashSet::new();
for url in all {
if self.can_fetch_picture(url) {
urls.insert(url.clone());
} else if files::server_image(url).is_none() && self.unfetchable.insert(url.clone()) {
let scheme = url.split(':').next().unwrap_or_default();
info!(%scheme, "banner not downloaded: only http, https and ts3image addresses");
}
}
// The badges shown, from TeamSpeak's server.
let badge_urls = p
.clients
.values()
.flat_map(|c| c.badges.iter().take(badges::SHOWN))
.filter_map(|guid| badges::icon_url(guid));
let urls: HashSet<String> = std::iter::once(p.server.banner_gfx_url.clone())
.chain(p.channels.values().filter_map(|c| c.banner_gfx_url.clone()))
.chain(badge_urls)
.filter(|u| self.can_fetch_picture(u))
.collect();
urls.extend(badge_urls);
self.pictures.retain(|url| urls.contains(url));
for url in &urls {
if self.pictures.insert(url.clone()) {
@@ -1094,6 +1349,13 @@ impl Session {
}
}
/// Whether the host of the picture at `url` asked to wait
/// (`Retry-After`) and the wait is not over.
fn picture_host_busy(&self, url: &str) -> bool {
let retry = self.image_retries.get(&ImageRequest::Picture(url.into()));
retry.is_some_and(|r| r.busy && r.due.is_some_and(|due| due > Instant::now()))
}
/// Get the picture at `url` into the cache (again with `fresh`): from
/// the web, or from the server's files through the voice connection.
fn fetch_picture(&self, url: &str, fresh: bool) {
@@ -1103,11 +1365,19 @@ impl Session {
let key = cache::server_picture_key(server, url);
self.fetch_image(key, Some(file), fresh, waiter);
} else {
let (max_cache, max) = (max_cache_bytes(&self.settings), self.picture_limit(url));
web::fetch(self.cache.current(), url, fresh, max_cache, max, waiter);
web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter);
}
}
/// Get the picture a chat message shows at `url` into the cache, if it
/// is no larger than it was asked for ([`Command::FetchPicture`]).
fn fetch_chat_picture(&self, url: &str) {
let Some(&max_bytes) = self.chat_pictures.get(url) else { return };
let waiter = self.image_waiter(ImageRequest::ChatPicture(url.into()), false);
let max_cache = max_cache_bytes(&self.settings);
web::fetch_chat_picture(self.cache.current(), url, max_cache, max_bytes, waiter);
}
/// Get `key` from the cache, downloading `file` (channel and path) once
/// (again with `fresh`).
fn fetch_image(&self, key: String, file: Option<(u64, String)>, fresh: bool, waiter: Waiter) {
@@ -1531,6 +1801,7 @@ impl Session {
if let Some((_, tx)) = self.gateway.take() {
let _ = tx.send(GatewayCmd::Stop);
}
self.gateway_observed = None;
if let Some((_, tx)) = self.query.take() {
let _ = tx.send(QueryCmd::Stop);
}
@@ -1643,6 +1914,7 @@ impl Session {
if let Some((url, ..)) = &self.banner_reload
&& *url == address
&& self.settings.current().get(&CACHE_FETCH_IMAGES)
&& !self.picture_host_busy(url)
{
self.fetch_picture(url, true);
}
@@ -1661,6 +1933,13 @@ impl Session {
}
self.learn_server_uid(server_uid, Source::Voice);
self.emit_state();
// The server knows our identity now: a gateway that could not
// log us in before (on a server we never joined) tries at once.
if self.state.observe == ObserveState::Connecting
&& let Some((_, tx)) = &self.gateway
{
let _ = tx.send(GatewayCmd::RetryNow);
}
let capabilities = flavor.capabilities();
if capabilities.streams
&& let Some((generation, voice)) = &self.voice
@@ -1773,7 +2052,7 @@ impl Session {
fn gateway_event(&mut self, e: GatewayEvent) {
match e {
GatewayEvent::Connected(client) => {
GatewayEvent::Connected(client, url) => {
self.state.observe = ObserveState::Observing;
let info = client.info().clone();
self.gateway_client = Some(client.clone());
@@ -1783,6 +2062,7 @@ impl Session {
self.learn_server_uid(info.server_uid.clone(), Source::Gateway);
self.emit_state();
self.gateway_update(GatewayUpdate::Connected {
url,
gateway_id: info.gateway_id,
server_uid: info.server_uid,
server_name: info.server_name,
@@ -1809,6 +2089,7 @@ impl Session {
}
GatewayEvent::Disconnected(reason) => {
self.gateway = None;
self.gateway_observed = None;
self.gateway_gone(reason.clone());
self.gateway_presence = None;
self.state.observe = ObserveState::Off;
@@ -1981,6 +2262,7 @@ impl Session {
self.emit_state();
}
self.fetch_pictures(&presence);
self.fetch_myts_avatars(&presence);
let presence = Arc::new(presence);
self.contacts.presence(self.id, presence.clone());
self.emit(Event::Presence { session: self.id, presence });
@@ -2009,7 +2291,17 @@ mod banner_tests {
// No myTeamSpeak account; its source stays open, as the engine's does
// (a closed one ends voice connections).
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
(Session::new(1, events, frames, AudioSettings::default(), shared, myts_identity), receiver)
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let session = Session::new(
1,
events,
frames,
AudioSettings::default(),
shared,
myts_identity,
myts_data,
);
(session, receiver)
}
#[tokio::test]
@@ -2185,6 +2477,143 @@ mod banner_tests {
let _ = std::fs::remove_dir_all(cache.dir());
}
#[test]
fn banners_keep_trying_avatars_and_icons_give_up() {
let banner = ImageRequest::Picture("https://example.com/b.png".into());
let delay = |f, hint, gone| retry_delay(&banner, f, hint, gone).map(|d| d.as_secs());
let delays: Vec<_> =
(1..=8).map(|f| delay(f, RetryHint::Default, false).unwrap()).collect();
assert_eq!(delays, [1, 4, 16, 60, 300, 900, 900, 900]);
// An address wrong or gone: after 15 minutes, then every hour.
assert_eq!(delay(1, RetryHint::Permanent, false), Some(900));
assert_eq!(delay(2, RetryHint::Permanent, true), Some(3600));
// A busy host: when it says.
assert_eq!(delay(1, RetryHint::After(Duration::from_secs(120)), false), Some(120));
let icon = ImageRequest::Icon(1234);
let delays: Vec<_> = (1..=4)
.map(|f| retry_delay(&icon, f, RetryHint::Default, false).map(|d| d.as_secs()))
.collect();
assert_eq!(delays, [Some(1), Some(4), Some(16), None]);
// So does a chat picture, not shown as a banner.
let chat = ImageRequest::ChatPicture("https://example.com/b.png".into());
assert_eq!(retry_delay(&chat, 3, RetryHint::Default, false), Some(Duration::from_secs(16)));
assert_eq!(retry_delay(&chat, 4, RetryHint::Permanent, false), None);
}
/// A banner whose address is wrong or gone is tried again after 15
/// minutes, then every hour, until the connection is made again; a
/// busy host's banner waits as long as it asks, and so do its reloads.
#[tokio::test]
async fn banners_wait_as_their_hosts_say() {
let (mut session, _events) = session("hints");
let url = "https://example.com/gone.png";
let request = ImageRequest::Picture(url.into());
let wait = |session: &Session, request: &ImageRequest| {
let due = session.image_retries[request].due.unwrap();
due.saturating_duration_since(Instant::now()).as_secs_f64().round() as u64
};
let gone = || Err(FetchError::new("HTTP 404 Not Found", RetryHint::Permanent));
session.pictures.insert(url.into());
session.image_finished(false, session.image_epoch, request.clone(), gone());
assert_eq!(wait(&session, &request), 900);
assert!(session.image_retries[&request].gone);
session.image_finished(false, session.image_epoch, request.clone(), gone());
assert_eq!(wait(&session, &request), 3600);
// Something else in between: the usual schedule.
let failed = Err("timed out".into());
session.image_finished(false, session.image_epoch, request.clone(), failed);
assert_eq!(wait(&session, &request), 16);
// Connected again: from the start.
session.forget_images();
session.pictures.insert(url.into());
session.image_finished(false, session.image_epoch, request.clone(), gone());
assert_eq!(wait(&session, &request), 900);
// The host banner of a busy host: its reloads wait too.
let banner = "https://example.com/busy.png";
let request = ImageRequest::Picture(banner.into());
session.pictures.insert(banner.into());
let timer = tokio::spawn(async {}).abort_handle();
session.banner_reload = Some((banner.into(), 60, timer));
let busy = FetchError::new("HTTP 429", RetryHint::After(Duration::from_secs(600)));
session.image_finished(false, session.image_epoch, request.clone(), Err(busy));
assert_eq!(wait(&session, &request), 600);
let cache = session.cache.current();
let key = cache::picture_key(banner).unwrap();
// Downloaded here, so a fetch by the session waits for this one.
let reload = |session: &mut Session| {
let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(|_| {})) else {
panic!("own download");
};
session.source_event(SourceEvent::ReloadBanner(banner.into()));
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(&temp, b"picture").unwrap();
cache.finish(&key, &temp, Ok(()), 0);
session.sources_rx.as_mut().unwrap().try_recv().is_ok()
};
assert!(!reload(&mut session), "reloaded while its host is busy");
session.image_retries.get_mut(&request).unwrap().due = Some(Instant::now());
assert!(reload(&mut session), "not reloaded once the wait was over");
std::fs::remove_dir_all(cache.dir()).unwrap();
}
/// What a failed download of `request` logs at info.
fn failure_lines(
session: &mut Session,
request: &ImageRequest,
result: Result<PathBuf, FetchError>,
) -> Vec<String> {
let epoch = session.image_epoch;
let finish = || session.image_finished(false, epoch, request.clone(), result);
web::tests::info_lines(finish).1
}
/// A failing banner's address is logged on its first failure, without
/// its query; that it is wrong or gone, once.
#[tokio::test]
async fn a_failing_banner_is_logged_once_with_its_address() {
let (mut session, _events) = session("log-once");
let url = "https://example.com/gone.png?sig=secret";
let request = ImageRequest::Picture(url.into());
session.pictures.insert(url.into());
let gone = || Err(FetchError::new("HTTP 404 Not Found", RetryHint::Permanent));
let lines = failure_lines(&mut session, &request, gone());
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(
lines[0].starts_with(
"banner not downloaded: its address is wrong or gone, so it is tried again only \
after 15 minutes, then hourly host=example.com url=https://example.com/gone.png \
failures=1 retry_in_s=Some(900)"
),
"{lines:?}"
);
assert!(!lines[0].contains("secret"), "{lines:?}");
assert_eq!(failure_lines(&mut session, &request, gone()), Vec::<String>::new());
// Something else meanwhile: by its host only.
let lines = failure_lines(&mut session, &request, Err("timed out".into()));
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(lines[0].starts_with("banner not downloaded host=example.com failures=3"));
assert!(!lines[0].contains("url="), "{lines:?}");
// The host banner is asked for at the server's reload interval too.
let banner = "https://example.com/host.png";
let request = ImageRequest::Picture(banner.into());
session.pictures.insert(banner.into());
let timer = tokio::spawn(async {}).abort_handle();
session.banner_reload = Some((banner.into(), 30, timer));
let lines = failure_lines(&mut session, &request, gone());
assert_eq!(lines.len(), 1, "{lines:?}");
assert!(
lines[0].starts_with(
"host banner not downloaded: its address is wrong or gone, so it is tried again \
only at the server's reload interval, or hourly"
),
"{lines:?}"
);
assert!(lines[0].contains(" reload_s=Some(60) "), "{lines:?}");
let _ = std::fs::remove_dir_all(session.cache.current().dir());
}
#[tokio::test]
async fn retries_are_bounded_and_obey_policy_presence_and_epoch() {
let (mut session, mut events) = session("retry-guards");
@@ -2200,7 +2629,8 @@ mod banner_tests {
);
let retry = &session.image_retries[&request];
assert_eq!(retry.failures, failure);
assert_eq!(retry.due.is_some(), failure <= 3);
// A banner is tried again while it is shown.
assert!(retry.due.is_some());
}
assert!(events.try_recv().is_err());
// Disabling fetch invalidates pending retries and completions.
@@ -2317,6 +2747,82 @@ mod banner_tests {
std::fs::remove_dir_all(cache.dir()).unwrap();
}
/// myTeamSpeak avatars (TeamSpeak 6) come from the web where the
/// server's avatar is not shown: none set, no voice connection to get it
/// over (observing), or its download gave up.
#[tokio::test]
async fn myts_avatars_where_the_servers_is_not_shown() {
let (mut session, mut events) = session("myts-avatar");
let cache = session.cache.current();
let client = |id, uid: &str, avatar: Option<&str>, myts: &str| voelin_model::ClientInfo {
id,
uid: Some(uid.into()),
avatar: avatar.map(Into::into),
myts_avatar: Some(myts.into()),
..Default::default()
};
let (a, b) = ("https://a.example.test/a.png", "https://a.example.test/b.png");
let hash = "0123456789abcdef0123456789abcdef";
let mut presence = Presence::default();
presence.clients.insert(1, client(1, "A=", None, a));
presence.clients.insert(2, client(2, "B=", Some(hash), b));
// Owned here, so nothing goes to the network.
let temps: Vec<_> = [a, b]
.iter()
.map(|url| {
let key = cache::picture_key(url).unwrap();
let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else {
panic!("first download");
};
(key, temp)
})
.collect();
// Observing: both, even the one with a server avatar.
session.gateway_presence = Some(presence.clone());
session.publish_presence();
assert_eq!(session.myts_avatars.len(), 2);
for (key, temp) in &temps {
std::fs::create_dir_all(temp.parent().unwrap()).unwrap();
std::fs::write(temp, b"\x89PNG\r\n\x1a\npicture").unwrap();
cache.finish(key, temp, Ok(()), 0);
let done = session.sources_rx.as_mut().unwrap().recv().await.unwrap();
session.source_event(done);
}
let mut ready = Vec::new();
while let Ok(event) = events.try_recv() {
if let Event::AvatarReady { client_uid, hash, .. } = event {
ready.push((client_uid, hash));
}
}
ready.sort();
assert_eq!(ready, [("A=".to_owned(), a.to_owned()), ("B=".to_owned(), b.to_owned())]);
// With voice the server's avatar is shown where there is one.
let (tx, _rx) = mpsc::unbounded_channel();
session.voice = Some((1, tx));
session.voice_presence = Some(presence.clone());
session.publish_presence();
assert_eq!(session.myts_avatars.keys().collect::<Vec<_>>(), ["A="]);
// Until its download gives up (the server's files unreachable).
let request = ImageRequest::Avatar { uid: "B=".into(), hash: hash.into() };
session.avatars.insert("B=".into(), hash.into());
for _ in 0..4 {
session.image_finished(
false,
session.image_epoch,
request.clone(),
Err("refused".into()),
);
}
assert_eq!(session.myts_avatars.get("B=").map(String::as_str), Some(b));
// A new server avatar is tried again: the failure was that one's.
let presence = session.voice_presence.as_mut().unwrap();
presence.clients.get_mut(&2).unwrap().avatar =
Some("fedcba9876543210fedcba9876543210".into());
session.publish_presence();
assert_eq!(session.myts_avatars.keys().collect::<Vec<_>>(), ["A="]);
std::fs::remove_dir_all(cache.dir()).unwrap();
}
#[tokio::test]
async fn enabling_images_replays_current_presence_without_server_updates() {
let (mut session, mut events) = session("policy-enable");
@@ -2463,4 +2969,26 @@ mod banner_tests {
assert_eq!(sent(), [(vec![], -30.0)]);
session.stop_all();
}
#[tokio::test]
async fn voice_connected_wakes_a_gateway_still_connecting() {
let (mut session, _events) = session("gateway-wake");
let (tx, mut rx) = mpsc::unbounded_channel();
session.gateway = Some((session.next_generation(), tx));
let connected = || VoiceEvent::Connected {
name: "test".into(),
flavor: voelin_model::ServerFlavor::Unknown(String::new()),
own_client: 1,
server_uid: "server=".into(),
own_uid: None,
};
session.state.observe = ObserveState::Connecting;
session.voice_event(connected());
assert!(matches!(rx.try_recv(), Ok(GatewayCmd::RetryNow)));
assert!(rx.try_recv().is_err());
// Logged in already: nothing to hurry.
session.state.observe = ObserveState::Observing;
session.voice_event(connected());
assert!(rx.try_recv().is_err());
}
}
+2 -2
View File
@@ -1121,8 +1121,8 @@ pub static CHAT_RETENTION_DAYS: Key<u32> = Key::new(
pub static CACHE_MAX_MB: Key<u64> = Key::new(
"cache.max_mb",
Kind::UInt { min: 0 },
"Size of the avatar and icon cache in MiB (0: no limit).",
|| 256,
"Size of the picture cache (avatars, icons, banners) in MiB (0: no limit).",
|| 1024,
);
/// Download the avatars, icons, banners and badges of servers we are on,
+374 -13
View File
@@ -76,6 +76,8 @@ impl VoiceOptions {
#[derive(Clone)]
pub(crate) struct VoiceLink {
pub myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
pub myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
pub session: SessionId,
pub events: broadcast::Sender<Event>,
pub settings: SharedSettings,
@@ -231,8 +233,35 @@ fn now_ms() -> i64 {
.unwrap_or_default()
}
/// What `client_user_tag` is to be set to, if anything: on servers that
/// know it (`user_tags`), the tag `wanted` where `shown` is another (or
/// none), or `again` after a new account proof; empty (cleared) where one
/// is shown that is no longer wanted.
fn user_tag_update(
wanted: Option<&tsclientlib::UserTag>,
shown: Option<&tsclientlib::UserTag>,
user_tags: bool,
again: bool,
now_ms: i64,
) -> Option<String> {
match (wanted, shown) {
_ if !user_tags => None,
(Some(tag), shown) if again || shown != Some(tag) => Some(tag.value(now_ms)),
(None, Some(_)) => Some(String::new()),
_ => None,
}
}
/// Which of the badges sent (`sent`, their ids) the server does not
/// publish (`client_signed_badges`: the ids that verified, joined by `,`).
fn badges_dropped<'a>(sent: &'a [String], published: &str) -> Vec<&'a str> {
let published: Vec<&str> = published.split(',').collect();
sent.iter().map(String::as_str).filter(|id| !published.contains(id)).collect()
}
enum Input {
MytsIdentityChanged,
MytsDataChanged,
AccountSourceClosed,
Item(Option<Result<StreamItem, tsclientlib::Error>>),
Cmd(Option<VoiceCmd>),
@@ -242,6 +271,16 @@ enum Input {
/// A command waiting for the server's answer.
enum Pending {
MytsIdentity(Instant),
/// `updatemytsdata`: whether it showed the avatar and the badges (else
/// it cleared them), and the ids of the badges shown; what the server
/// published is only logged.
MytsData {
avatar: Option<bool>,
badges: Option<bool>,
badge_ids: Vec<String>,
},
/// `clientupdate client_user_tag`: the value (empty: cleared); only logged.
UserTag(String),
Stream(Request),
FileList {
request: RequestId,
@@ -300,17 +339,21 @@ impl Job {
}
}
/// How long a picture of `size` bytes may take to arrive: half a minute,
/// plus its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on
/// slow links while a stalled transfer still ends.
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
fn image_download_time(size: u64) -> Duration {
Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE)
Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30);
/// Bound background image handshakes without imposing a deadline on user transfers.
fn expire_image_jobs(jobs: &mut HashMap<FiletransferHandle, Job>, now: Instant) {
jobs.retain(|_, job| {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= Duration::from_secs(15)) {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) {
job.report()(TransferState::Failed("image transfer negotiation timed out".into()));
false
} else {
@@ -350,6 +393,12 @@ struct Voice {
pending: HashMap<MessageHandle, Pending>,
jobs: HashMap<FiletransferHandle, Job>,
transfers: HashMap<TransferId, Slot>,
/// `updatemytsdata` is to be sent once connected again: a reconnect
/// (tsclientlib's own) leaves the server without it.
myts_data_due: bool,
/// What this connection has shown the server of the account (avatar,
/// badges, User Tag): what changes, and what a sign-out clears.
myts_shown: tsclientlib::MytsData,
}
async fn run_inner(
@@ -382,6 +431,7 @@ async fn run_inner(
builder = builder.default_token(token.clone());
}
let mut identity = link.myts_identity.clone();
let mut data = link.myts_data.clone();
// A changed account invalidates an in-flight handshake. Drop that connection
// and take a fresh snapshot before publishing any connected state.
let mut con = timeout(Duration::from_secs(30), async {
@@ -449,8 +499,14 @@ async fn run_inner(
pending: HashMap::new(),
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
myts_shown: tsclientlib::MytsData::default(),
};
voice.publish_state()?;
// The account's avatar, badges and User Tag, for everyone on the
// server (as the official client, once connected).
data.borrow_and_update();
voice.send_myts_data(true);
let mut tick = tokio::time::interval(Duration::from_millis(250));
let result = loop {
@@ -461,7 +517,9 @@ async fn run_inner(
}) {
break Err(anyhow::anyhow!("myTeamSpeak account update timed out"));
}
let input = next_input(&mut voice.con.events(), commands, &mut tick, &mut identity).await;
let input =
next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data)
.await;
match input {
Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")),
Input::MytsIdentityChanged => {
@@ -472,6 +530,15 @@ async fn run_inner(
}
Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")),
}
// After the proof, what is shown of the account (a sign-in):
// its change, if any, is in this one. All of it again: the
// server checks it for the myTS ID it holds when it comes.
data.borrow_and_update();
voice.send_myts_data(true);
}
Input::MytsDataChanged => {
data.borrow_and_update();
voice.send_myts_data(false);
}
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
Input::Item(Some(Err(e))) => break Err(e.into()),
@@ -504,6 +571,7 @@ async fn next_input(
commands: &mut mpsc::UnboundedReceiver<VoiceCmd>,
tick: &mut tokio::time::Interval,
identity: &mut watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
data: &mut watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Input {
tokio::select! {
biased;
@@ -512,6 +580,11 @@ async fn next_input(
} else {
Input::AccountSourceClosed
},
changed = data.changed() => if changed.is_ok() {
Input::MytsDataChanged
} else {
Input::AccountSourceClosed
},
input = async {
// Keep account changes first without starving network or timers when
// the audio command queue remains ready.
@@ -578,6 +651,10 @@ impl Voice {
self.message(target, invoker, message);
}
}
// Connected again after a reconnect.
if self.myts_data_due {
self.send_myts_data(true);
}
self.publish_state()?;
}
StreamItem::Audio(packet) => {
@@ -660,6 +737,9 @@ impl Voice {
}
StreamItem::DisconnectedTemporarily(reason) => {
warn!(?reason, "voice connection interrupted, reconnecting");
// A new client on the server: it shows nothing of the account.
self.myts_data_due = true;
self.myts_shown = tsclientlib::MytsData::default();
}
_ => {}
}
@@ -825,6 +905,30 @@ impl Voice {
}
}
Pending::Quiet | Pending::MytsIdentity(_) => {}
Pending::MytsData { avatar, badges, badge_ids } => match result {
Ok(()) => self.myts_published(avatar, badges, &badge_ids),
Err(TsError::ParameterInvalid) => warn!(
"the server refused the account's myTeamSpeak certificate (error 1538): it \
is expired, revoked or not a myTeamSpeak signing certificate, or the \
server could not load myTeamSpeak's revocation list"
),
Err(e) => warn!(error = %e, "the server refused the account's avatar or badges"),
},
Pending::UserTag(value) => match result {
Ok(()) => {
let own = self.con.get_state().ok().and_then(|state| {
state.clients.get(&state.own_client).and_then(|c| c.user_tag.clone())
});
if value.is_empty() {
info!("the server no longer shows a User Tag for the account");
} else if own.as_deref() == Some(value.as_str()) {
info!("the server shows the account's User Tag");
} else {
warn!("the server took the account's User Tag but shows another value");
}
}
Err(e) => warn!(error = %e, "the server refused the account's User Tag"),
},
Pending::Report(what) => {
if let Err(e) = result {
let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}")));
@@ -833,6 +937,129 @@ impl Voice {
}
}
/// What is to be shown of the account on this connection: what the UI
/// gave, when it is for the myTS ID this connection presents; nothing
/// without one (signed out).
fn myts_wanted(&self) -> tsclientlib::MytsData {
let identity = self.link.myts_identity.borrow();
let data = self.link.myts_data.borrow();
match (identity.as_deref(), data.as_deref()) {
(Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(),
_ => tsclientlib::MytsData::default(),
}
}
/// Whether the server knows the User Tag (TeamSpeak 6: it names
/// `client_user_tag` for our client, protocol 8 on).
fn has_user_tags(&self) -> bool {
self.con.get_state().is_ok_and(|state| {
state.server.protocol_version >= 8
|| state.clients.get(&state.own_client).is_some_and(|c| c.user_tag.is_some())
})
}
/// Show the server the account's avatar, badges and User Tag where it
/// shows something else (`updatemytsdata`, `clientupdate`), or clear
/// them; `again`: all of it, after a new account proof. While
/// reconnecting, once connected again.
fn send_myts_data(&mut self, again: bool) {
self.myts_data_due = false;
if self.con.get_state().is_err() {
self.myts_data_due = true;
return;
}
let mut wanted = self.myts_wanted();
let user_tags = self.has_user_tags();
if !user_tags {
wanted.user_tag = None;
}
for update in wanted.updates(&self.myts_shown, again) {
let shows = |part: &Option<Vec<u8>>| part.as_ref().map(|data| !data.is_empty());
let (avatar, badges) = (shows(&update.avatar), shows(&update.badges));
let badge_ids =
if badges == Some(true) { wanted.badge_ids.clone() } else { Vec::new() };
info!(
avatar = ?avatar.map(|shown| if shown { "shown" } else { "cleared" }),
badges = ?badges.map(|shown| if shown { "shown" } else { "cleared" }),
?badge_ids,
"telling the server what to show of the account (updatemytsdata)"
);
match self.con.send_myts_update(&update) {
Ok(handle) => {
let pending = Pending::MytsData { avatar, badges, badge_ids };
self.pending.insert(handle, pending);
}
Err(tsclientlib::Error::NotConnected) => {
self.myts_data_due = true;
return;
}
Err(e) => warn!(error = %e, "the account's avatar or badges were not sent"),
}
}
let shown = self.myts_shown.user_tag.as_ref();
if let Some(value) =
user_tag_update(wanted.user_tag.as_ref(), shown, user_tags, again, now_ms())
{
match &wanted.user_tag {
Some(tag) if !value.is_empty() => {
info!(tag = %tag.tag, "setting the account's User Tag")
}
_ => info!("clearing the account's User Tag"),
}
match self.con.send_user_tag(&value) {
Ok(handle) => {
self.pending.insert(handle, Pending::UserTag(value));
}
Err(tsclientlib::Error::NotConnected) => {
self.myts_data_due = true;
return;
}
Err(e) => warn!(error = %e, "the account's User Tag was not sent"),
}
}
self.myts_shown = wanted;
}
/// What the server published of an `updatemytsdata` it took: it says so
/// for our client before its answer, and shows nothing of what does not
/// verify, without an error.
fn myts_published(&self, avatar: Option<bool>, badges: Option<bool>, badge_ids: &[String]) {
let Ok(state) = self.con.get_state() else { return };
let Some(own) = state.clients.get(&state.own_client) else { return };
let has_id = own.my_team_speak_id.as_deref().is_some_and(|id| !id.is_empty());
let why = if has_id {
"its signature does not verify with the certificate for the account's myTS ID"
} else {
"the server holds no myTS ID for this client (the account proof was not accepted)"
};
match avatar {
Some(true) if own.my_team_speak_avatar.as_deref().is_some_and(|a| !a.is_empty()) => {
info!("the server shows the account's avatar")
}
Some(true) => warn!(why, "the server took the account's avatar but shows none"),
Some(false) => info!("the server no longer shows an avatar for the account"),
None => {}
}
let published = own.signed_badges.as_deref().unwrap_or_default();
let dropped = badges_dropped(badge_ids, published);
match badges {
Some(true) if published.is_empty() => {
warn!(why, "the server took the account's badges but shows none")
}
Some(true) if dropped.is_empty() => {
info!(published, "the server shows the account's badges")
}
Some(true) => warn!(
published,
?dropped,
"the server shows only some of the account's badges: the others' signatures do \
not verify for the account's myTS ID"
),
Some(false) => info!("the server no longer shows badges for the account"),
None => {}
}
}
fn send(&mut self, cmd: OutCommand, pending: Pending) -> anyhow::Result<()> {
let handle = cmd.send_with_result(&mut self.con)?;
self.pending.insert(handle, pending);
@@ -1195,10 +1422,10 @@ mod image_download_tests {
},
);
}
expire_image_jobs(&mut jobs, started + Duration::from_secs(14));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1));
assert_eq!(jobs.len(), 2);
assert!(reports.lock().unwrap().is_empty());
expire_image_jobs(&mut jobs, started + Duration::from_secs(15));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION);
assert_eq!(jobs.len(), 1);
assert!(jobs.contains_key(&FiletransferHandle(2)));
assert!(
@@ -1210,10 +1437,10 @@ mod image_download_tests {
#[test]
fn large_pictures_get_time_to_arrive() {
assert_eq!(image_download_time(0), Duration::from_secs(30));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(33));
assert_eq!(image_download_time(0), Duration::from_secs(60));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048));
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384));
}
}
@@ -1224,6 +1451,7 @@ mod account_tests {
#[tokio::test(start_paused = true)]
async fn account_priority_preserves_ready_network_and_timer_progress() {
let (account, mut identity) = watch::channel(None);
let (account_data, mut data) = watch::channel(None);
let (commands, mut receiver) = mpsc::unbounded_channel();
for _ in 0..512 {
commands.send(VoiceCmd::SetInputMuted(false)).unwrap();
@@ -1234,14 +1462,22 @@ mod account_tests {
let mut tick = tokio::time::interval(Duration::from_millis(1));
account.send_replace(None);
assert!(matches!(
next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await,
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
Input::MytsIdentityChanged
));
identity.borrow_and_update();
// What is shown of the account changes too, ahead of the rest.
account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default())));
assert!(matches!(
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
Input::MytsDataChanged
));
data.borrow_and_update();
let (mut network, mut timers, mut audio) = (0, 0, 0);
for _ in 0..512 {
tokio::time::advance(Duration::from_millis(1)).await;
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await {
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await
{
Input::Item(_) => network += 1,
Input::Tick => timers += 1,
Input::Cmd(_) => audio += 1,
@@ -1251,6 +1487,130 @@ mod account_tests {
assert!(network > 0 && timers > 0 && audio > 0);
}
fn account_data(myts_id: &[u8]) -> tsclientlib::MytsData {
let signed = |data: &[u8]| tsclientlib::Signed { certificate: vec![1], data: data.into() };
tsclientlib::MytsData {
myts_id: myts_id.to_vec(),
avatar: signed(b"avatar"),
badges: signed(b"badges"),
badge_ids: vec!["b1".into()],
user_tag: Some(tsclientlib::UserTag {
tag: "a@myteamspeak.com".into(),
token: vec![2],
}),
}
}
/// The User Tag is set where it is not shown yet, or after a new account
/// proof, and cleared where it is no longer wanted: on TeamSpeak 6
/// servers only.
#[test]
fn the_user_tag_is_set_where_it_changed() {
let tag = |tag: &str| tsclientlib::UserTag { tag: tag.into(), token: vec![2] };
let (a, b) = (tag("a@myteamspeak.com"), tag("b@myteamspeak.com"));
let update =
|wanted, shown, user_tags, again| user_tag_update(wanted, shown, user_tags, again, 5);
let set = Some(a.value(5));
assert!(set.as_deref().unwrap().starts_with(r#"{"myts_token":"Ag==","tag":"a@"#));
assert_eq!(update(Some(&a), None, true, false), set);
assert_eq!(update(Some(&a), Some(&a), true, false), None, "unchanged");
assert_eq!(update(Some(&a), Some(&a), true, true), set, "after a new account proof");
assert_eq!(update(Some(&a), Some(&b), true, false), set, "another tag");
assert_eq!(update(None, Some(&a), true, false).as_deref(), Some(""), "cleared");
assert_eq!(update(None, Some(&a), true, true).as_deref(), Some(""));
assert_eq!(update(None, None, true, true), None, "nothing to clear");
// Not a TeamSpeak 6 server: nothing, set or cleared.
assert_eq!(update(Some(&a), None, false, true), None);
assert_eq!(update(None, Some(&a), false, false), None);
}
/// The server publishes the ids of the badges that verified.
#[test]
fn badges_the_server_dropped_are_named() {
let sent: Vec<String> = ["b1", "b2", "b3"].map(String::from).to_vec();
assert!(badges_dropped(&sent, "b1,b2,b3").is_empty());
assert!(badges_dropped(&sent, "b3,b1,b2").is_empty());
assert_eq!(badges_dropped(&sent, "b1,b3"), ["b2"]);
assert_eq!(badges_dropped(&sent, ""), ["b1", "b2", "b3"]);
assert!(badges_dropped(&[], "b1").is_empty());
}
/// A voice source that never connects (a silent UDP peer) presenting
/// the account with myTS ID `[1; 33]`, told to show `data`.
fn unconnected(server: &tokio::net::UdpSocket, data: tsclientlib::MytsData) -> Voice {
// Scalar one and the standard compressed Edwards base point.
let mut private = [0; 32];
private[0] = 1;
let mut public = [0x66; 32];
public[0] = 0x58;
let identity =
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap();
let (events, _) = broadcast::channel(8);
let link = VoiceLink {
session: 1,
events,
settings: SharedSettings::new(crate::settings::Settings::default()),
myts_identity: watch::channel(Some(Arc::new(identity))).1,
myts_data: watch::channel(Some(Arc::new(data))).1,
};
Voice {
con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(),
link,
events: mpsc::unbounded_channel().0,
server_uid: String::new(),
talking: HashMap::new(),
pending: HashMap::new(),
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
myts_shown: tsclientlib::MytsData::default(),
}
}
/// A reconnect (tsclientlib's own) leaves the server without the
/// account's avatar: it goes again once connected, not before.
#[tokio::test]
async fn account_data_waits_for_the_connection() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let mut voice = unconnected(&server, account_data(&[1; 33]));
voice.send_myts_data(true);
assert!(voice.myts_data_due && voice.pending.is_empty());
assert_eq!(voice.myts_shown, tsclientlib::MytsData::default(), "nothing shown yet");
voice.myts_data_due = false;
voice.myts_shown = account_data(&[1; 33]);
let reconnecting = tsclientlib::TemporaryDisconnectReason::Timeout("test");
voice.item(StreamItem::DisconnectedTemporarily(reconnecting)).unwrap();
assert!(voice.myts_data_due);
assert_eq!(
voice.myts_shown,
tsclientlib::MytsData::default(),
"a new client shows nothing"
);
// Not connected yet: still due.
let _ = voice.item(StreamItem::BookEvents(Vec::new()));
assert!(voice.myts_data_due && voice.pending.is_empty());
timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap();
}
/// Only what is signed for the myTS ID the connection presents is shown.
#[tokio::test]
async fn account_data_is_for_the_presented_myts_id() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let voice = unconnected(&server, account_data(&[1; 33]));
assert_eq!(voice.myts_wanted(), account_data(&[1; 33]));
let other = unconnected(&server, account_data(&[2; 33]));
assert_eq!(other.myts_wanted(), tsclientlib::MytsData::default());
let mut signed_out = unconnected(&server, account_data(&[1; 33]));
signed_out.link.myts_identity = watch::channel(None).1;
assert_eq!(signed_out.myts_wanted(), tsclientlib::MytsData::default());
for voice in [voice, other, signed_out] {
timeout(Duration::from_millis(100), shutdown_connection(voice.con))
.await
.unwrap()
.unwrap();
}
}
#[tokio::test]
async fn shutdown_never_polls_a_connecting_connection() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
@@ -1276,6 +1636,7 @@ mod account_tests {
events,
settings: SharedSettings::new(crate::settings::Settings::default()),
myts_identity: identity,
myts_data: watch::channel(None).1,
};
let (_commands, commands) = mpsc::unbounded_channel();
let (events, mut received) = mpsc::unbounded_channel();
File diff suppressed because it is too large. Load diff
+197 -7
View File
@@ -1,7 +1,7 @@
//! Chat history and gateway features through the engine, against a fake
//! gateway (a WebSocket server speaking the tsgw protocol from memory).
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -43,6 +43,10 @@ struct State {
requests: Vec<String>,
/// Close connections at once (the gateway is down).
refuse: bool,
/// Answers to the next logins, in turn, instead of logging in.
login_errors: VecDeque<ErrorCode>,
/// Logins asked for.
logins: usize,
}
impl State {
@@ -151,6 +155,10 @@ impl FakeGateway {
fn requests(&self) -> Vec<String> {
self.state.lock().unwrap().requests.clone()
}
fn logins(&self) -> usize {
self.state.lock().unwrap().logins
}
}
fn caps() -> Vec<String> {
@@ -236,6 +244,10 @@ fn answer(
) -> ServerMsg {
match msg {
ClientMsg::Auth { .. } => {
st.logins += 1;
if let Some(code) = st.login_errors.pop_front() {
return ServerMsg::Error { code, message: "not now".into() };
}
*logged_in = true;
st.sessions.push((push.clone(), open.clone()));
ServerMsg::AuthOk {
@@ -368,7 +380,8 @@ fn answer(
st.topics.push(topic.clone());
ServerMsg::Topic { topic }
}
ClientMsg::SubscribeEvents | ClientMsg::Ping => ServerMsg::Ok,
ClientMsg::Ping => ServerMsg::Pong,
ClientMsg::SubscribeEvents => ServerMsg::Ok,
_ => ServerMsg::Error { code: ErrorCode::UnknownType, message: "not in the fake".into() },
}
}
@@ -434,7 +447,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
let identity = tsclientlib::Identity::create();
engine.send(Command::ObserveGateway {
session,
url: gw.url.clone(),
urls: vec![gw.url.clone()],
identity: Box::new(identity),
});
}
@@ -550,7 +563,9 @@ async fn live_messages_and_gateway_requests() {
};
assert_eq!((server_uid.as_str(), uid.as_str()), ("fake-server", ME));
assert!(capabilities.iter().any(|c| c == feature::PINS));
// In sync (the chat is empty).
// In sync (the chat is empty): the latest page, then what changed since
// (else our message may come back with the sync instead of live).
batch(&mut rx, HistorySource::Gateway).await;
batch(&mut rx, HistorySource::Gateway).await;
// Our message: stored at once, then merged with the gateway's copy.
@@ -726,11 +741,11 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
engine.send(Command::OpenChat { session: 3, target: LOBBY });
engine.send(Command::ObserveGateway {
session: 3,
url: format!("ws://127.0.0.1:{port}/v1"),
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
identity: Box::new(tsclientlib::Identity::create()),
});
// The first attempt fails (the next one is 2 s later): still connecting,
// and the user is told nothing.
// The first attempts fail (the next ones about 1 s, then 2 s later):
// still connecting, and the user is told nothing.
let mut connecting = false;
let quiet = timeout(Duration::from_millis(1500), async {
loop {
@@ -766,3 +781,178 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
drop(engine);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A reverse proxy without a rule for the gateway's host, as Zoraxy's
/// default site answers: 404 to everything.
async fn not_found_proxy() -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
tokio::spawn(async move {
while let Ok((mut tcp, _)) = listener.accept().await {
tokio::spawn(async move {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut request = [0; 4096];
let _ = tcp.read(&mut request).await;
let _ = tcp
.write_all(
b"HTTP/1.1 404 Not Found\r\nContent-Type: text/plain; charset=utf-8\r\n\
Content-Length: 19\r\n\r\n404 page not found\n",
)
.await;
});
}
});
url
}
/// Every published gateway is tried in turn, without waiting: a TLS proxy
/// that answers 404 and a port nothing listens on are passed over, and the
/// plain gateway published after them is used, quietly.
#[tokio::test(flavor = "multi_thread")]
async fn the_next_published_gateway_is_used_when_one_fails() {
let proxy = not_found_proxy().await;
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let gw = FakeGateway::start().await;
let path = temp_db("fallback");
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
let mut rx = engine.subscribe();
engine.send(Command::ObserveGateway {
session: 4,
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
});
// Within one round: sooner than the shortest wait after a failed round
// (1 s, less 30 %).
let url = timeout(Duration::from_millis(650), async {
loop {
match rx.recv().await {
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
Ok(Event::Gateway { session: 4, update: GatewayUpdate::Connected { url, .. } }) => {
return url;
}
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(e) => panic!("{e}"),
}
}
})
.await
.expect("the plain gateway was not used within a round");
assert_eq!(url, gw.url);
wait(&mut rx, "observing", |e| match e {
Event::Error { message, .. } => panic!("the user was told: {message}"),
Event::State { session: 4, state } if state.observe == ObserveState::Observing => Some(()),
_ => None,
})
.await;
drop(engine);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// Events until `until` matches one, within `within`: never an error for
/// the user, never observing `session` off once it started.
async fn quietly_until(
rx: &mut Receiver<Event>,
session: u64,
within: Duration,
what: &str,
mut until: impl FnMut(&Event) -> bool,
) {
let mut started = false;
timeout(within, async {
loop {
let e = match rx.recv().await {
Ok(e) => e,
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(e) => panic!("{e}"),
};
if let Event::Error { message, .. } = &e {
panic!("the user was told: {message}");
}
if let Event::State { session: s, state } = &e
&& *s == session
{
// (Off before observing starts.)
assert!(!started || state.observe != ObserveState::Off, "gave up");
started |= state.observe != ObserveState::Off;
}
if until(&e) {
return;
}
}
})
.await
.unwrap_or_else(|_| panic!("timed out waiting for {what}"));
}
fn observing(session: u64) -> impl FnMut(&Event) -> bool {
move |e| {
matches!(e, Event::State { session: s, state }
if *s == session && state.observe == ObserveState::Observing)
}
}
/// A gateway that cannot log us in yet (its TeamSpeak server is away; the
/// server does not know the identity before voice connected once) is tried
/// again, quietly, and observed through once it can.
#[tokio::test(flavor = "multi_thread")]
async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
for (session, code) in [(5, ErrorCode::Unavailable), (6, ErrorCode::UnknownIdentity)] {
let gw = FakeGateway::start().await;
gw.state.lock().unwrap().login_errors.push_back(code);
let engine = Engine::start();
let mut rx = engine.subscribe();
engine.send(Command::ObserveGateway {
session,
urls: vec![gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
});
// After the first wait: about 1 s.
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
.await;
assert_eq!(gw.logins(), 2, "{code:?}");
}
}
/// A login the gateway refuses (banned, not allowed, a bad signature or
/// security level) is not tried again.
#[tokio::test(flavor = "multi_thread")]
async fn a_refused_login_ends_observing() {
let gw = FakeGateway::start().await;
gw.state.lock().unwrap().login_errors.push_back(ErrorCode::Banned);
let engine = Engine::start();
let mut rx = engine.subscribe();
observe(&engine, 8, &gw);
wait(&mut rx, "observing off", |e| match e {
Event::Error { message, .. } => panic!("the user was told: {message}"),
Event::State { session: 8, state } if state.observe == ObserveState::Off => Some(()),
_ => None,
})
.await;
tokio::time::sleep(Duration::from_millis(1500)).await;
assert_eq!(gw.logins(), 1);
}
/// Selecting the server again while its gateway is still connecting does
/// not start it over, and ends the wait for the next attempt.
#[tokio::test(flavor = "multi_thread")]
async fn asking_again_while_connecting_tries_at_once() {
let gw = FakeGateway::start().await;
gw.state.lock().unwrap().login_errors.extend([ErrorCode::UnknownIdentity; 3]);
let engine = Engine::start();
let mut rx = engine.subscribe();
let identity = tsclientlib::Identity::create();
let ask = || Command::ObserveGateway {
session: 9,
urls: vec![gw.url.clone()],
identity: Box::new(identity.clone()),
};
engine.send(ask());
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
quietly_until(&mut rx, 9, Duration::from_secs(6), "three logins", |_| gw.logins() >= 3).await;
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(gw.logins(), 3);
engine.send(ask());
// Sooner than the shortest such wait (3.5 s), without starting over.
quietly_until(&mut rx, 9, Duration::from_secs(2), "observing", observing(9)).await;
assert_eq!(gw.logins(), 4);
}
+1 -1
View File
@@ -20,7 +20,7 @@ serde_json = "1"
sha1 = { package = "sha-1", version = "0.10" }
sha2 = "0.10"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt", "sync"], optional = true }
tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional = true }
# TLS (`wss://`, as gateways run behind a proxy) with the system's
# certificates; rustls and its crates are in the tree already (reqwest).
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
+275 -4
View File
@@ -20,10 +20,14 @@
//! ```
use std::collections::HashMap;
use std::fmt;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
use futures_util::{Sink, SinkExt, Stream, StreamExt};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, oneshot};
use tokio_tungstenite::tungstenite::{self, Message};
use tsproto_types::crypto::EccKeyPrivP256;
@@ -196,15 +200,163 @@ pub struct GatewayClient {
pub async fn connect(
url: &str,
login: Login,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
connect_watched(url, login, &Progress::default()).await
}
/// [`connect`], telling `progress` each step as it is reached, so a
/// timeout around it can say which step hung, and how long each took.
pub async fn connect_watched(
url: &str,
login: Login,
progress: &Progress,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::error::UrlError;
let mut request = url.into_client_request()?;
request.headers_mut().insert(
"Sec-WebSocket-Protocol",
tungstenite::http::HeaderValue::from_static(crate::SUBPROTOCOL),
);
let (ws, _) = tokio_tungstenite::connect_async(request).await?;
GatewayClient::start(ws, login).await
// As tokio-tungstenite's connect_async, a step at a time.
let uri = request.uri();
let host = uri.host().ok_or(tungstenite::Error::Url(UrlError::NoHostName))?;
let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
let port = uri
.port_u16()
.or_else(|| match uri.scheme_str() {
Some("wss") => Some(443),
Some("ws") => Some(80),
_ => None,
})
.ok_or(tungstenite::Error::Url(UrlError::UnsupportedUrlScheme))?;
let tcp = open(host, port, progress).await?;
progress.enter(Stage::WebSocket);
let (ws, _) = tokio_tungstenite::client_async_tls_with_config(request, tcp, None, None).await?;
GatewayClient::login(ws, login, progress).await
}
/// The TCP connection to `host`: each of its addresses in turn.
async fn open(host: &str, port: u16, progress: &Progress) -> Result<TcpStream, ClientError> {
let io = |e| ClientError::WebSocket(tungstenite::Error::Io(e));
progress.enter(Stage::Dns);
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((host, port)).await.map_err(io)?.collect();
progress.enter(Stage::Tcp);
let mut error = None;
for addr in addrs {
progress.peer(addr);
match TcpStream::connect(addr).await {
Ok(tcp) => {
// Small frames, each answered: no waiting to fill packets.
let _ = tcp.set_nodelay(true);
return Ok(tcp);
}
Err(e) => error = Some(e),
}
}
Err(io(error.unwrap_or_else(|| {
std::io::Error::new(std::io::ErrorKind::NotFound, format!("no address for {host}"))
})))
}
/// A step of logging in to a gateway ([`connect_watched`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Stage {
/// Looking up the host's addresses.
#[default]
Dns,
/// The TCP connection.
Tcp,
/// TLS (`wss://`) and the WebSocket upgrade.
WebSocket,
/// Waiting for the gateway's `hello`.
Hello,
/// Waiting for the answer to the login.
Auth,
/// Logged in.
Done,
}
impl Stage {
pub fn name(self) -> &'static str {
match self {
Stage::Dns => "dns",
Stage::Tcp => "tcp",
Stage::WebSocket => "websocket",
Stage::Hello => "hello",
Stage::Auth => "auth",
Stage::Done => "done",
}
}
}
impl fmt::Display for Stage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// How far a login ([`connect_watched`]) got and how long each step took;
/// clones share it. Shown as e.g. `dns 2 ms, tcp 31 ms, websocket 64 ms,
/// hello 1 ms, auth 134 ms`, a step still under way as `hello for 19900 ms`.
#[derive(Clone, Debug, Default)]
pub struct Progress(Arc<Mutex<Steps>>);
#[derive(Debug, Default)]
struct Steps {
/// The step under way, since when.
stage: Stage,
since: Option<Instant>,
/// The steps done, with how long they took.
done: Vec<(Stage, Duration)>,
/// The address connected to (or being tried).
peer: Option<SocketAddr>,
}
impl Progress {
/// The step under way (the one that hung, after a timeout), or
/// [`Stage::Done`].
pub fn stage(&self) -> Stage {
self.0.lock().unwrap().stage
}
/// The gateway's address, once the TCP connection is being made.
pub fn peer_addr(&self) -> Option<SocketAddr> {
self.0.lock().unwrap().peer
}
fn enter(&self, stage: Stage) {
let mut steps = self.0.lock().unwrap();
let now = Instant::now();
if let Some(since) = steps.since {
let step = steps.stage;
steps.done.push((step, now - since));
}
steps.stage = stage;
steps.since = (stage != Stage::Done).then_some(now);
}
fn peer(&self, addr: SocketAddr) {
self.0.lock().unwrap().peer = Some(addr);
}
}
impl fmt::Display for Progress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let steps = self.0.lock().unwrap();
let mut parts: Vec<String> = steps
.done
.iter()
.map(|(stage, took)| format!("{stage} {} ms", took.as_millis()))
.collect();
if let Some(since) = steps.since {
parts.push(format!("{} for {} ms", steps.stage, since.elapsed().as_millis()));
}
if parts.is_empty() {
return f.write_str("not started");
}
f.write_str(&parts.join(", "))
}
}
fn now_secs() -> i64 {
@@ -241,7 +393,7 @@ impl GatewayClient {
/// Log in over an open WebSocket (subprotocol [`crate::SUBPROTOCOL`]) and
/// start the connection task.
pub async fn start<S>(
mut ws: S,
ws: S,
login: Login,
) -> Result<(Self, mpsc::UnboundedReceiver<Push>), ClientError>
where
@@ -251,12 +403,29 @@ impl GatewayClient {
+ Send
+ 'static,
{
Self::login(ws, login, &Progress::default()).await
}
async fn login<S>(
mut ws: S,
login: Login,
progress: &Progress,
) -> Result<(Self, mpsc::UnboundedReceiver<Push>), ClientError>
where
S: Stream<Item = Result<Message, tungstenite::Error>>
+ Sink<Message, Error = tungstenite::Error>
+ Unpin
+ Send
+ 'static,
{
progress.enter(Stage::Hello);
let (gateway_id, server_uid, server_name, nonce) = match recv(&mut ws).await?.msg {
ServerMsg::Hello { gateway_id, server_uid, server_name, nonce, .. } => {
(gateway_id, server_uid, server_name, nonce)
}
other => return Err(ClientError::unexpected(other)),
};
progress.enter(Stage::Auth);
let msg = match login {
Login::Identity { key, key_offset } => {
let ts = now_secs();
@@ -280,6 +449,7 @@ impl GatewayClient {
}
other => return Err(ClientError::unexpected(other)),
};
progress.enter(Stage::Done);
let info = Arc::new(SessionInfo {
gateway_id,
server_uid,
@@ -732,3 +902,104 @@ async fn run<S>(
};
let _ = pushes.send(Push::Disconnected(reason));
}
#[cfg(test)]
mod tests {
use tokio::net::TcpListener;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use super::*;
/// Wait (without a clock: tokio's `time` is not enabled here) until the
/// login in progress reaches `stage`.
async fn reaches(progress: &Progress, stage: Stage) {
for _ in 0..100_000 {
if progress.stage() == stage {
return;
}
tokio::task::yield_now().await;
}
panic!("at {} instead of {stage}", progress.stage());
}
#[tokio::test]
async fn a_closed_port_fails_at_the_tcp_step() {
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let progress = Progress::default();
assert_eq!(progress.to_string(), "not started");
let login = Login::Token("t".into());
let result = connect_watched(&format!("ws://127.0.0.1:{port}/v1"), login, &progress).await;
assert!(matches!(result, Err(ClientError::WebSocket(_))));
assert_eq!(progress.stage(), Stage::Tcp);
assert_eq!(progress.peer_addr(), Some(([127, 0, 0, 1], port).into()));
assert!(progress.to_string().starts_with("dns "), "{progress}");
}
/// A gateway that takes each step only when told: the login waits at
/// each, and tells which.
#[tokio::test]
async fn each_step_is_told_until_logged_in() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
let (go, mut steps) = mpsc::unbounded_channel::<()>();
let server = tokio::spawn(async move {
let (tcp, _) = listener.accept().await.unwrap();
steps.recv().await;
#[allow(clippy::result_large_err)] // tungstenite's callback type
let callback = |_: &Request, mut response: Response| {
response
.headers_mut()
.insert("Sec-WebSocket-Protocol", crate::SUBPROTOCOL.parse().unwrap());
Ok(response)
};
let mut ws = tokio_tungstenite::accept_hdr_async(tcp, callback).await.unwrap();
steps.recv().await;
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();
let Some(Ok(Message::Text(auth))) = ws.next().await else { panic!("no login") };
let auth: Envelope<ClientMsg> = serde_json::from_str(auth.as_str()).unwrap();
assert!(matches!(auth.msg, ClientMsg::Resume { .. }));
steps.recv().await;
let ok = ServerMsg::AuthOk {
uid: "me".into(),
token: "t".into(),
token_expires: 0,
capabilities: Vec::new(),
};
let text = serde_json::to_string(&Envelope::with_id(auth.id.unwrap(), ok)).unwrap();
ws.send(Message::Text(text.into())).await.unwrap();
// Open until the client is done.
while let Some(Ok(_)) = ws.next().await {}
});
let progress = Progress::default();
let login = {
let progress = progress.clone();
tokio::spawn(async move {
connect_watched(&url, Login::Token("t".into()), &progress).await.map(|(c, _)| c)
})
};
reaches(&progress, Stage::WebSocket).await;
go.send(()).unwrap();
reaches(&progress, Stage::Hello).await;
go.send(()).unwrap();
reaches(&progress, Stage::Auth).await;
assert!(progress.to_string().contains(", auth for "), "{progress}");
go.send(()).unwrap();
let client = login.await.unwrap().expect("logged in");
assert_eq!(client.uid(), "me");
assert_eq!(progress.stage(), Stage::Done);
let shown = progress.to_string();
let names: Vec<&str> =
shown.split(", ").map(|step| step.split(' ').next().unwrap()).collect();
assert_eq!(names, ["dns", "tcp", "websocket", "hello", "auth"], "{shown}");
drop(client);
server.await.unwrap();
}
}
+9 -2
View File
@@ -1,13 +1,20 @@
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
# Run: docker run -v ./tsgw.toml:/etc/tsgw/tsgw.toml -p 7788:7788 tsgw
# Run: docker run -d --name tsgw --init --restart unless-stopped \
# -v ./tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
FROM rust:1.94-bookworm AS build
WORKDIR /src
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
COPY . .
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /tsgw /usr/local/bin/tsgw
# The database (and a log file, if set) live here; owned by the image's user
# (nonroot, 65532), so a new volume mounted here is writable too.
COPY --from=build --chown=65532:65532 /data /var/lib/tsgw
ENV TSGW_CONFIG=/etc/tsgw/tsgw.toml
WORKDIR /var/lib/tsgw
EXPOSE 7788
+39
View File
@@ -130,6 +130,18 @@ pub static KEYS: &[KeyDef] = &[
"null",
"URL clients use, e.g. wss://gw.example.org/v1",
),
boot(
"log.level",
Kind::OptStr,
"null",
"What to log, e.g. \"debug\" or \"info,voelin_query=trace\"; default: RUST_LOG, else \"info\"",
),
boot(
"log.file",
Kind::OptStr,
"null",
"Also write the log to this file (appended; at 20 MB it moves to <name>.1.log, 5 files kept)",
),
boot(
"history.path",
Kind::Str,
@@ -493,6 +505,10 @@ impl Layers {
bind: self.get::<String>("listen.bind")?.parse().context("listen.bind")?,
public_url: self.get("listen.public_url")?,
db_path: self.get("history.path")?,
log_level: self.get::<Option<String>>("log.level")?.filter(|l| !l.trim().is_empty()),
log_file: self
.get::<Option<PathBuf>>("log.file")?
.filter(|p| !p.as_os_str().is_empty()),
})
}
}
@@ -514,6 +530,10 @@ pub struct Bootstrap {
pub bind: SocketAddr,
pub public_url: Option<String>,
pub db_path: PathBuf,
/// Log filter (`log.level`); `None`: `RUST_LOG`, else the default.
pub log_level: Option<String>,
/// Log file (`log.file`), on top of standard output.
pub log_file: Option<PathBuf>,
}
impl Bootstrap {
@@ -524,6 +544,8 @@ impl Bootstrap {
.unwrap_or_else(|| format!("tsgw@{}", self.addr))
}
/// How to open query connections. Connections opened with clones of
/// the result share one flood count, as the server counts them.
pub fn query_connect(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: self.transport,
@@ -751,4 +773,21 @@ mod tests {
assert!(cli_values(&["nope=1".into()]).is_err());
assert!(cli_values(&["history.retention_days=-1".into()]).is_err());
}
#[test]
fn log_settings_are_bootstrap_keys() {
let file = file_values(
"[query]\ntransport = \"ssh\"\naddr = \"127.0.0.1:10022\"\n\
[log]\nfile = \"logs/tsgw.log\"\n",
)
.unwrap();
let env = env_values(|name| (name == "TSGW_LOG_LEVEL").then(|| "debug".into())).unwrap();
let boot = Layers { file, env, ..Default::default() }.bootstrap().unwrap();
assert_eq!(boot.log_level.as_deref(), Some("debug"));
assert_eq!(boot.log_file, Some(PathBuf::from("logs/tsgw.log")));
assert!(key_def("log.level").unwrap().bootstrap);
let none = file_values("[query]\ntransport = \"raw\"\naddr = \"h:1\"\n").unwrap();
let boot = Layers { file: none, ..Default::default() }.bootstrap().unwrap();
assert_eq!((boot.log_level, boot.log_file), (None, None));
}
}
+1
View File
@@ -367,6 +367,7 @@ impl Db {
}
/// Whether `uid` reacted with `emoji`.
#[cfg(test)]
pub fn has_reaction(&self, message_id: i64, emoji: &str, uid: &str) -> rusqlite::Result<bool> {
self.lock()
.conn
+1
View File
@@ -253,6 +253,7 @@ impl Db {
self.0.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(test)]
pub fn schema_version(&self) -> rusqlite::Result<i64> {
self.lock().conn.pragma_query_value(None, "user_version", |r| r.get(0))
}
+139 -56
View File
@@ -5,7 +5,7 @@
//! feed are in `features.rs`, the stream directory in `streams.rs`, the
//! background tasks in `tasks.rs`.
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
@@ -21,10 +21,11 @@ use voelin_gateway_proto::{
};
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as};
use voelin_query::{Command, Connect, QueryClient};
use voelin_query::{Command, Connect};
use crate::config::{Bootstrap, Layers, Runtime};
use crate::config::{Layers, Runtime};
use crate::db::{Db, TokenInfo};
use crate::lookup::Lookup;
use crate::perms::{
ChannelAccess, GroupResolver, PermIds, PermResolver, UserGroups, channel_access, effective,
granted, rule_allows,
@@ -192,7 +193,6 @@ impl Feature {
}
pub struct Hub {
pub boot: Bootstrap,
pub settings: Settings,
pub gateway_id: String,
pub server_uid: String,
@@ -205,7 +205,7 @@ pub struct Hub {
relays: RwLock<RelayPool>,
/// Serializes rebuilding the relay pool.
relay_rebuild: tokio::sync::Mutex<()>,
lookup: QueryClient,
pub(crate) lookup: Arc<Lookup>,
/// One server-chat post at a time: each borrows the poster's nickname.
lookup_posting: tokio::sync::Mutex<()>,
perms: PermResolver,
@@ -214,57 +214,51 @@ pub struct Hub {
events: broadcast::Sender<Arc<HubEvent>>,
/// Readers per relayed channel, and when the last one left.
readers: Mutex<HashMap<ChannelId, (usize, Instant)>>,
/// Our own query clients, whose messages are echoes.
own_clients: Mutex<HashSet<u16>>,
/// Message ids while history is off.
next_message_id: Mutex<i64>,
pub(crate) directory: Mutex<Directory>,
}
impl Hub {
/// Connect to the server, open the database and start the background tasks.
/// Connect to the server, open the database and start the background
/// tasks. Waits for the TeamSpeak server as long as it takes.
pub async fn start(layers: Layers) -> Result<Arc<Self>> {
let started = Instant::now();
let boot = layers.bootstrap()?;
let db = Db::open(&boot.db_path)
.with_context(|| format!("failed to open {}", boot.db_path.display()))?;
let settings = Settings::new(layers, &db)?;
let rt = settings.current();
// Clones share the count of commands for the flood protection.
let connect = boot.query_connect();
let (lookup, _) =
QueryClient::connect(&connect).await.context("query login for lookups failed")?;
let info = lookup.send(&Command::new("serverinfo")).await?;
let info = info.first().context("empty serverinfo")?;
let version = info.get("virtualserver_version").unwrap_or_default();
let is_ts6 = matches!(ServerFlavor::from_version_string(version), ServerFlavor::Ts6(_));
let server_uid =
info.get("virtualserver_unique_identifier").unwrap_or_default().to_string();
let server_name = info.get("virtualserver_name").unwrap_or_default().to_string();
let needed_level = info.parse("virtualserver_needed_identity_security_level").unwrap_or(8);
let channels = lookup.send(&Command::new("channellist").flag("flags")).await?;
let default_channel = channels
.iter()
.find(|r| r.flag("channel_flag_default") == Some(true))
.and_then(|r| r.parse("cid"))
.unwrap_or(1);
let perms = PermResolver::new(PermIds::load(&lookup).await?);
let own_id = lookup.own_client_id().await?;
set_lookup_nickname(&lookup, &rt.relay.nickname).await;
let lookup = Lookup::open(connect.clone(), lookup_nickname(&rt.relay.nickname)).await;
lookup.log_address(boot.allowlisted).await;
let server = ServerFacts::load_until_it_works(&lookup, &connect).await;
let perms = PermResolver::new(server.perm_ids);
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
let relays = new_relay_pool(&connect, &rt.relay.nickname);
let directory = Directory::load(&db);
info!(%server_name, %server_uid, version, is_ts6, "gateway connected to server");
info!(
server_name = %server.name,
server_uid = %server.uid,
version = %server.version,
is_ts6 = server.is_ts6,
default_channel = server.default_channel,
needed_level = server.needed_level,
elapsed_ms = started.elapsed().as_millis() as u64,
"gateway connected to server"
);
let hub = Arc::new(Self {
gateway_id: boot.gateway_id(),
boot,
settings,
server_uid,
server_name,
is_ts6,
needed_level,
default_channel,
server_uid: server.uid,
server_name: server.name,
is_ts6: server.is_ts6,
needed_level: server.needed_level,
default_channel: server.default_channel,
observer,
connect,
relays: RwLock::new(relays),
@@ -276,15 +270,13 @@ impl Hub {
db,
events: broadcast::channel(4096).0,
readers: Default::default(),
own_clients: Mutex::new([own_id].into()),
next_message_id: Mutex::new(0),
directory: Mutex::new(directory),
});
crate::tasks::spawn_all(&hub);
// Apps may log in meanwhile.
for &cid in &rt.relay.pinned_channels {
if let Err(error) = hub.relays().open(cid).await {
warn!(cid, %error, "could not open pinned relay");
}
hub.open_relay_soon(cid);
}
Ok(hub)
}
@@ -306,7 +298,7 @@ impl Hub {
}
pub(crate) fn is_own_client(&self, id: u16) -> bool {
self.own_clients.lock().unwrap().contains(&id)
self.lookup.is_own(id)
}
/// Features for the `hello` message.
@@ -350,26 +342,37 @@ impl Hub {
let pool = new_relay_pool(&self.connect, nickname);
tokio::spawn(crate::tasks::pump_relays(self.clone(), pool.subscribe()));
let old = std::mem::replace(&mut *self.relays.write().unwrap(), pool);
let channels = old.channels().await;
old.close_all().await;
// Also the relays being opened now, which open no more in the old pool.
let channels = old.close_all().await;
drop(old);
set_lookup_nickname(&self.lookup, nickname).await;
self.lookup.set_nickname(&lookup_nickname(nickname)).await;
let pool = self.relays();
for cid in channels {
if let Err(error) = pool.open(cid).await {
warn!(cid, %error, "could not reopen relay");
// A failure is logged by the pool.
if pool.open(cid).await.is_err() && self.relay_wanted(cid) {
let hub = self.clone();
tokio::spawn(async move { hub.reopen_relay(cid).await });
}
}
info!(nickname, "relays renamed");
}
/// Pinned channels changed: open new ones, let removed ones idle out.
pub(crate) async fn apply_pinned_channels(&self, old: &[u64], new: &[u64]) {
let pool = self.relays();
for cid in new.iter().filter(|c| !old.contains(c)) {
if let Err(error) = pool.open(*cid).await {
warn!(cid, %error, "could not open pinned relay");
/// Open a channel's relay in the background, and while that fails, again
/// for as long as it is wanted ([`Hub::reopen_relay`]).
fn open_relay_soon(self: &Arc<Self>, cid: ChannelId) {
let hub = self.clone();
tokio::spawn(async move {
// A failure is logged by the pool.
if hub.relays().open(cid).await.is_err() {
hub.reopen_relay(cid).await;
}
});
}
/// Pinned channels changed: open new ones, let removed ones idle out.
pub(crate) fn apply_pinned_channels(self: &Arc<Self>, old: &[u64], new: &[u64]) {
for cid in new.iter().filter(|c| !old.contains(c)) {
self.open_relay_soon(*cid);
}
for cid in old.iter().filter(|c| !new.contains(c)) {
// The idle teardown closes it once nobody reads it.
@@ -377,6 +380,27 @@ impl Hub {
}
}
/// Someone reads the channel, or it is pinned.
pub(crate) fn relay_wanted(&self, cid: ChannelId) -> bool {
self.runtime().relay.pinned_channels.contains(&cid)
|| self.readers.lock().unwrap().get(&cid).is_some_and(|(n, _)| *n > 0)
}
/// Open a relay the server dropped again, waiting longer after each
/// failure, for as long as it is wanted.
pub(crate) async fn reopen_relay(&self, cid: ChannelId) {
let mut attempt = 0;
while self.relay_wanted(cid) {
attempt += 1;
tokio::time::sleep(self.connect.retry_delay(attempt)).await;
// A failure is logged by the pool.
if self.relays().open(cid).await.is_ok() {
info!(channel = cid, attempt, "relay reopened");
return;
}
}
}
/// Channels whose relay nobody needs any more.
pub(crate) fn idle_relays(&self, rt: &Runtime) -> Vec<ChannelId> {
let idle = std::time::Duration::from_secs(rt.relay.idle_teardown_secs);
@@ -711,7 +735,15 @@ impl Hub {
));
}
}
self.relays().open(cid).await?;
loop {
let pool = self.relays();
match pool.open(cid).await {
// Replaced on the way (a new nickname): open in the new pool.
Err(_) if pool.is_closed() => continue,
result => result?,
}
break;
}
self.readers.lock().unwrap().entry(cid).or_insert((0, Instant::now())).0 += 1;
Ok(())
}
@@ -760,7 +792,7 @@ impl Hub {
ChatTarget::Server => {
let _posting = self.lookup_posting.lock().await;
post_as(
&self.lookup,
&self.lookup.client().await,
&lookup_nickname(&rt.relay.nickname),
&user.nickname,
&relayed,
@@ -811,10 +843,61 @@ fn lookup_nickname(nickname: &str) -> String {
format!("{nickname} Gateway")
}
async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) {
let _ = lookup
.send(&Command::new("clientupdate").arg("client_nickname", lookup_nickname(nickname)))
.await;
/// What the gateway reads from the server once, at start.
struct ServerFacts {
version: String,
is_ts6: bool,
uid: String,
name: String,
needed_level: u8,
default_channel: ChannelId,
perm_ids: PermIds,
}
impl ServerFacts {
async fn load_until_it_works(lookup: &Lookup, connect: &Connect) -> Self {
let mut attempt = 0;
loop {
attempt += 1;
match Self::load(lookup).await {
Ok(facts) => return facts,
Err(error) => {
let retry_in = connect.retry_delay(attempt);
warn!(
error = format!("{error:#}"),
attempt,
retry_in_s = retry_in.as_secs_f32(),
"could not read the server's settings; trying again"
);
tokio::time::sleep(retry_in).await;
}
}
}
}
async fn load(lookup: &Lookup) -> Result<Self> {
// Failures are logged by the caller.
let info = lookup.send_quiet(&Command::new("serverinfo")).await.context("serverinfo")?;
let info = info.first().context("empty serverinfo")?;
let version = info.get("virtualserver_version").unwrap_or_default().to_string();
let channels = lookup
.send_quiet(&Command::new("channellist").flag("flags"))
.await
.context("channellist")?;
Ok(Self {
is_ts6: matches!(ServerFlavor::from_version_string(&version), ServerFlavor::Ts6(_)),
version,
uid: info.get("virtualserver_unique_identifier").unwrap_or_default().to_string(),
name: info.get("virtualserver_name").unwrap_or_default().to_string(),
needed_level: info.parse("virtualserver_needed_identity_security_level").unwrap_or(8),
default_channel: channels
.iter()
.find(|r| r.flag("channel_flag_default") == Some(true))
.and_then(|r| r.parse("cid"))
.unwrap_or(1),
perm_ids: PermIds::load(lookup).await.context("looking up permission ids")?,
})
}
}
/// Split `text` by a topic format like `[#{topic}] {text}` into title and
+202
View File
@@ -0,0 +1,202 @@
//! Where the log goes: standard output (journald, `docker logs`) and, with
//! `log.file`, a file as well.
//!
//! What is logged comes from `log.level` (`TSGW_LOG_LEVEL`), else
//! `RUST_LOG`, else [`DEFAULT_FILTER`]. The libraries that log every packet
//! stay at warnings unless the filter names them, so `debug` stays readable.
use std::fs::{File, OpenOptions};
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use tracing::warn;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{EnvFilter, fmt};
use crate::config::Bootstrap;
/// What is logged when nothing says otherwise.
pub const DEFAULT_FILTER: &str = "info,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn";
/// Libraries kept at warnings unless a filter names them.
const NOISY: &[&str] = &["russh", "hyper", "h2", "tower", "tungstenite", "tokio_tungstenite"];
/// One log file's limit before it moves aside.
const MAX_BYTES: u64 = 20 << 20;
/// Files kept: the one written and the ones moved aside.
const KEEP: usize = 5;
/// Start logging. Problems with the filter or the file are logged, not
/// fatal. Returns the log file in use.
pub fn init(boot: &Bootstrap) -> Option<PathBuf> {
let rust_log = std::env::var("RUST_LOG").ok();
let (directives, from) = match (&boot.log_level, &rust_log) {
(Some(level), _) => (level.as_str(), "log.level"),
(None, Some(rust_log)) if !rust_log.trim().is_empty() => (rust_log.as_str(), "RUST_LOG"),
_ => (DEFAULT_FILTER, "default"),
};
let (filter, bad_filter) = match EnvFilter::try_new(quiet_noisy(directives)) {
Ok(filter) => (filter, None),
Err(error) => (EnvFilter::new(DEFAULT_FILTER), Some(error)),
};
let ansi = io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();
let console = fmt::layer().with_ansi(ansi);
let file = boot.log_file.as_deref().map(|path| (path, LogFile::open(path, KEEP, MAX_BYTES)));
let to_file = match &file {
Some((_, Ok(log))) => {
let log = log.clone();
Some(fmt::layer().with_ansi(false).with_writer(move || log.clone()))
}
_ => None,
};
tracing_subscriber::registry().with(filter).with(console).with(to_file).init();
if let Some(error) = bad_filter {
warn!(filter = directives, from, %error, "not a log filter; using the default");
}
match file {
Some((path, Ok(_))) => Some(path.to_path_buf()),
Some((path, Err(error))) => {
warn!(
file = %path.display(),
%error,
"cannot write the log file; logging to standard output only"
);
None
}
None => None,
}
}
/// `directives` with the libraries in [`NOISY`] it does not name at
/// warnings.
fn quiet_noisy(directives: &str) -> String {
let named = |lib: &str| {
directives.split(',').any(|d| {
let target = d.trim().split(['=', '[']).next().unwrap_or_default();
target == lib || target.starts_with(&format!("{lib}::"))
})
};
let mut filter = directives.trim().trim_end_matches(',').to_string();
for lib in NOISY.iter().filter(|lib| !named(lib)) {
filter.push_str(&format!(",{lib}=warn"));
}
filter
}
/// A log file written by appending, also across restarts. When it would
/// grow past its limit it moves to `<name>.1.<ext>` (the older ones one
/// further along, the oldest dropped) and a new one starts. Clones write to
/// the same file.
#[derive(Clone)]
pub struct LogFile(Arc<Mutex<Inner>>);
struct Inner {
path: PathBuf,
file: File,
written: u64,
keep: usize,
max: u64,
}
impl LogFile {
pub fn open(path: &Path, keep: usize, max: u64) -> io::Result<Self> {
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir)?;
}
let file = append(path)?;
let written = file.metadata()?.len();
let inner = Inner { path: path.to_path_buf(), file, written, keep: keep.max(1), max };
Ok(Self(Arc::new(Mutex::new(inner))))
}
}
impl Write for LogFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut inner = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if inner.written > 0 && inner.written + buf.len() as u64 > inner.max {
rotate(&inner.path, inner.keep);
// If no new file can be made, the moved one goes on: moving the
// files along on every line would soon drop them all.
if let Ok(file) = append(&inner.path) {
inner.file = file;
}
inner.written = 0;
}
let n = inner.file.write(buf)?;
inner.written += n as u64;
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).file.flush()
}
}
fn append(path: &Path) -> io::Result<File> {
OpenOptions::new().create(true).append(true).open(path)
}
/// `tsgw.log` as the `n`th one moved aside: `tsgw.1.log`.
fn moved_aside(path: &Path, n: usize) -> PathBuf {
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
let name = match path.extension() {
Some(ext) => format!("{stem}.{n}.{}", ext.to_string_lossy()),
None => format!("{stem}.{n}"),
};
path.with_file_name(name)
}
/// Move the files one along; the oldest goes.
fn rotate(path: &Path, keep: usize) {
if keep <= 1 {
let _ = std::fs::remove_file(path);
return;
}
let _ = std::fs::remove_file(moved_aside(path, keep - 1));
for n in (1..keep - 1).rev() {
let _ = std::fs::rename(moved_aside(path, n), moved_aside(path, n + 1));
}
let _ = std::fs::rename(path, moved_aside(path, 1));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn noisy_libraries_stay_quiet_unless_named() {
assert_eq!(
quiet_noisy("debug"),
"debug,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn,tokio_tungstenite=warn"
);
let named = quiet_noisy("info,voelin_query=trace,russh=debug,hyper::proto=info,");
assert!(named.starts_with("info,voelin_query=trace,russh=debug,hyper::proto=info,h2=warn"));
assert!(!named.contains("russh=warn") && !named.contains("hyper=warn"));
assert!(EnvFilter::try_new(quiet_noisy(DEFAULT_FILTER)).is_ok());
assert_eq!(quiet_noisy(DEFAULT_FILTER).matches("russh").count(), 1);
}
#[test]
fn the_file_is_appended_to_and_moved_aside_when_full() {
let dir = std::env::temp_dir().join(format!("tsgw-log-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("logs").join("tsgw.log");
let read = |p: PathBuf| std::fs::read_to_string(p).ok();
LogFile::open(&path, 3, 12).unwrap().write_all(b"start 1\n").unwrap();
// A restart goes on in the same file.
let log = LogFile::open(&path, 3, 12).unwrap();
log.clone().write_all(b"two\n").unwrap();
assert_eq!(read(path.clone()).as_deref(), Some("start 1\ntwo\n"));
// Full: moved aside, and the oldest goes.
log.clone().write_all(b"three\n").unwrap();
log.clone().write_all(b"four 4\n").unwrap();
log.clone().write_all(b"five 5\n").unwrap();
assert_eq!(read(path.clone()).as_deref(), Some("five 5\n"));
assert_eq!(read(dir.join("logs/tsgw.1.log")).as_deref(), Some("four 4\n"));
assert_eq!(read(dir.join("logs/tsgw.2.log")).as_deref(), Some("three\n"));
assert_eq!(read(dir.join("logs/tsgw.3.log")), None, "three files in all");
assert_eq!(moved_aside(Path::new("/var/log/tsgw"), 2), Path::new("/var/log/tsgw.2"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+231
View File
@@ -0,0 +1,231 @@
//! The lookup query connection: logins, permission checks and server chat
//! posts go through it. When the TeamSpeak server drops it (a restart, a
//! network problem) it is opened again, and commands sent meanwhile wait
//! for it a little.
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use tracing::{debug, error, info, warn};
use voelin_query::{Command, Connect, QueryClient, Row, Transport, attempt_worth_a_warning};
/// How long a command waits for a lost connection to come back.
const RECONNECT_WAIT: Duration = Duration::from_secs(5);
pub struct Lookup {
connect: Connect,
client: watch::Sender<QueryClient>,
/// The session's nickname, set again on every new connection.
nickname: Mutex<String>,
/// The connection's client id while it is up: server chat from it is the
/// gateway's own. Not kept across reconnects: after a server restart the
/// old id may be a user's.
own_id: Mutex<Option<u16>>,
}
impl Lookup {
/// Log in, trying until it works, and keep the connection open from
/// then on.
pub async fn open(mut connect: Connect, nickname: String) -> Arc<Self> {
connect.line.label = "lookup".into();
let (client, own_id) = open_until_it_works(&connect, &nickname).await;
let lookup = Arc::new(Self {
connect,
client: watch::channel(client).0,
nickname: Mutex::new(nickname),
own_id: Mutex::new(Some(own_id)),
});
tokio::spawn(keep_open(Arc::downgrade(&lookup)));
lookup
}
/// The connection is up.
pub fn is_up(&self) -> bool {
!self.client.borrow().is_closed()
}
/// The connection's client id, while it is up.
pub fn own_id(&self) -> Option<u16> {
*self.own_id.lock().unwrap()
}
/// The id is the connection's own.
pub fn is_own(&self, id: u16) -> bool {
self.own_id() == Some(id)
}
/// Send a command; when the connection is lost on the way, once more
/// on the new one. A failure is logged with the command's name.
pub async fn send(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
let result = self.send_quiet(cmd).await;
if let Err(error) = &result {
warn!(command = %cmd.name, %error, "ServerQuery command failed");
}
result
}
/// [`Lookup::send`] for callers that log a failure themselves.
pub async fn send_quiet(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
let mut current = self.client.subscribe();
let client = current.borrow_and_update().clone();
match client.send(cmd).await {
Err(error) if lost(&error, &client) => {
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
Ok(Ok(())) => {
let client = current.borrow_and_update().clone();
client.send(cmd).await
}
_ => Err(error),
}
}
result => result,
}
}
/// The connection, after waiting a little for it if it is lost.
pub async fn client(&self) -> QueryClient {
let mut current = self.client.subscribe();
let client = current.borrow_and_update().clone();
if !client.is_closed() {
return client;
}
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
Ok(Ok(())) => current.borrow_and_update().clone(),
_ => client,
}
}
/// Rename the session, now and after reconnects.
pub async fn set_nickname(&self, nickname: &str) {
*self.nickname.lock().unwrap() = nickname.to_string();
set_nickname(&self.client().await, nickname).await;
}
/// Log the address the server sees the gateway's queries come from: it
/// counts the commands of each address for its flood protection, unless
/// the address is in its `query_ip_allowlist.txt`.
pub async fn log_address(&self, allowlisted: bool) {
let Some(own) = self.own_id() else { return };
let Ok(rows) = self.send(&Command::new("clientlist").flag("ip")).await else { return };
let address = rows
.iter()
.find(|r| r.parse::<u16>("clid") == Some(own))
.and_then(|r| r.get("connection_client_ip"));
let Some(address) = address.filter(|a| !a.is_empty()) else {
debug!("the server did not say where the gateway's queries come from");
return;
};
let loopback = address.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
match (allowlisted, loopback) {
(true, _) => info!(
address,
"the TeamSpeak server sees the gateway's queries coming from this address"
),
(false, true) => info!(
address,
hint = "the server's query_ip_allowlist.txt has this address by default; if it still \
does, set query.allowlisted = true so the gateway stops slowing itself down",
"the TeamSpeak server sees the gateway's queries coming from this address"
),
(false, false) => info!(
address,
hint = "add this address to the server's query_ip_allowlist.txt (read again within \
seconds) and set query.allowlisted = true; until then the server's flood \
protection limits the gateway",
"the TeamSpeak server sees the gateway's queries coming from this address"
),
}
}
}
/// The error means the connection is gone, not that the command failed.
fn lost(error: &voelin_query::Error, client: &QueryClient) -> bool {
use voelin_query::Error;
matches!(error, Error::Closed | Error::Io(_) | Error::Ssh(_)) || client.is_closed()
}
/// Wait for the connection to close, open it again, repeat.
async fn keep_open(lookup: Weak<Lookup>) {
loop {
let Some(client) = lookup.upgrade().map(|l| l.client.borrow().clone()) else { return };
client.closed().await;
let Some(lookup) = lookup.upgrade() else { return };
let lost_at = Instant::now();
*lookup.own_id.lock().unwrap() = None;
warn!(addr = %lookup.connect.addr, "lookup query connection lost; reconnecting");
let nickname = lookup.nickname.lock().unwrap().clone();
let (client, own_id) = open_until_it_works(&lookup.connect, &nickname).await;
*lookup.own_id.lock().unwrap() = Some(own_id);
lookup.client.send_replace(client);
info!(down_ms = lost_at.elapsed().as_millis() as u64, "lookup query connection restored");
}
}
/// Open a connection, waiting longer after each failure.
async fn open_until_it_works(connect: &Connect, nickname: &str) -> (QueryClient, u16) {
let started = Instant::now();
let transport = match connect.transport {
Transport::Ssh => "ssh",
Transport::Raw => "raw",
Transport::Http => "http",
};
let mut attempt = 0;
loop {
attempt += 1;
match open_once(connect, nickname).await {
Ok(opened) => {
let elapsed_ms = started.elapsed().as_millis() as u64;
info!(addr = %connect.addr, transport, attempt, elapsed_ms, "query login ok");
return opened;
}
Err(e) => {
let retry_in = connect.retry_delay(attempt);
let retry_in_s = retry_in.as_secs_f32();
let refused = matches!(&e, voelin_query::Error::SshAuth)
|| matches!(&e, voelin_query::Error::Query(q) if q.id == ERR_INVALID_LOGIN);
if refused {
error!(
addr = %connect.addr,
user = %connect.user,
attempt,
retry_in_s,
"the TeamSpeak server refused the query login; check query.user and the password"
);
} else if attempt_worth_a_warning(attempt) {
warn!(
addr = %connect.addr,
error = %e,
attempt,
retry_in_s,
"query login failed; trying again"
);
} else {
debug!(
addr = %connect.addr,
error = %e,
attempt,
retry_in_s,
"query login failed; trying again"
);
}
tokio::time::sleep(retry_in).await;
}
}
}
}
/// `login` with a wrong name or password.
const ERR_INVALID_LOGIN: u32 = 520;
async fn open_once(connect: &Connect, nickname: &str) -> voelin_query::Result<(QueryClient, u16)> {
let (client, _) = QueryClient::connect(connect).await?;
let own_id = client.own_client_id().await?;
set_nickname(&client, nickname).await;
Ok((client, own_id))
}
/// The name is cosmetic: failing keeps the server-assigned one.
async fn set_nickname(client: &QueryClient, nickname: &str) {
let _ = client.send(&Command::new("clientupdate").arg("client_nickname", nickname)).await;
}
+217 -31
View File
@@ -9,6 +9,8 @@ mod config;
mod db;
mod features;
mod hub;
mod logging;
mod lookup;
mod perms;
mod session;
mod settings;
@@ -17,20 +19,27 @@ mod tasks;
#[cfg(test)]
mod tests;
use std::future::IntoFuture;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use anyhow::Result;
use axum::extract::{State, WebSocketUpgrade};
use axum::http::{HeaderMap, header};
use axum::response::IntoResponse;
use anyhow::{Context, Result};
use axum::extract::{ConnectInfo, State, WebSocketUpgrade};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use axum::{Extension, Json, Router};
use clap::Parser;
use tracing::info;
use tracing_subscriber::EnvFilter;
use tokio::sync::watch;
use tracing::{debug, info, warn};
use voelin_query::Transport;
use crate::config::Bootstrap;
use crate::hub::Hub;
use crate::session::Peer;
#[derive(Parser, Debug)]
#[command(version, about)]
@@ -44,54 +53,207 @@ struct Args {
set: Vec<String>,
}
/// How long a WebSocket connection made while the gateway starts waits for
/// the TeamSpeak server before it is refused.
const START_WAIT: Duration = Duration::from_secs(10);
/// How long open connections get to close at shutdown.
const CLOSE_WAIT: Duration = Duration::from_secs(2);
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
)
.init();
let args = Args::parse();
let layers = config::Layers::load(&args.config, &args.set)?;
let bind = layers.bootstrap()?.bind;
let hub = Hub::start(layers).await?;
tokio::spawn(reload_on_hangup(hub.clone()));
let listener = tokio::net::TcpListener::bind(bind).await?;
info!(%bind, "listening");
axum::serve(listener, router(hub)).with_graceful_shutdown(shutdown()).await?;
let boot = layers.bootstrap()?;
let log_file = logging::init(&boot);
info!(
version = env!("CARGO_PKG_VERSION"),
config = %args.config.display(),
bind = %boot.bind,
public_url = boot.public_url.as_deref(),
gateway_id = %boot.gateway_id(),
voice_port = boot.voice_port,
query_transport = transport_name(boot.transport),
query_addr = %boot.addr,
query_user = %boot.user,
query_password = if boot.password.is_some() { "set" } else { "none" },
allowlisted = boot.allowlisted,
db = %boot.db_path.display(),
log_file = log_file.as_ref().map(|p| p.display().to_string()),
"tsgw starting"
);
// Listen at once: apps that come while the TeamSpeak server is not
// reachable yet wait for it a little instead of being turned away.
let listener = tokio::net::TcpListener::bind(boot.bind)
.await
.with_context(|| format!("cannot listen on {}", boot.bind))?;
info!(
bind = %boot.bind,
public_url = boot.public_url.as_deref(),
well_known = boot.public_url.as_deref().unwrap_or("ws://<host the app asked for>/v1"),
"listening"
);
let app = App::new(boot);
let service = router(app.clone()).into_make_service_with_connect_info::<SocketAddr>();
let server = axum::serve(listener, service).with_graceful_shutdown(shutdown(app.clone()));
let mut server = std::pin::pin!(server.into_future());
tokio::select! {
// Stopped before the TeamSpeak server answered.
served = &mut server => return served.context("serving failed"),
hub = Hub::start(layers) => {
let hub = hub?;
app.hub.send_replace(Some(hub.clone()));
tokio::spawn(reload_on_hangup(hub));
}
}
server.await.context("serving failed")?;
app.closed_within(CLOSE_WAIT).await;
Ok(())
}
pub fn router(hub: Arc<Hub>) -> Router {
fn transport_name(transport: Transport) -> &'static str {
match transport {
Transport::Ssh => "ssh",
Transport::Raw => "raw",
Transport::Http => "http",
}
}
/// What the HTTP handlers share.
pub struct App {
boot: Bootstrap,
/// The hub, once the gateway is logged in to the TeamSpeak server.
hub: watch::Sender<Option<Arc<Hub>>>,
/// Turns true at shutdown, which closes the WebSocket connections.
stop: watch::Sender<bool>,
/// WebSocket connections open now, and since the start.
open: AtomicUsize,
connections: AtomicU64,
}
impl App {
fn new(boot: Bootstrap) -> Arc<Self> {
Arc::new(Self {
boot,
hub: watch::channel(None).0,
stop: watch::channel(false).0,
open: AtomicUsize::new(0),
connections: AtomicU64::new(0),
})
}
/// An app for a hub that has started.
#[cfg(test)]
fn started(boot: Bootstrap, hub: Arc<Hub>) -> Arc<Self> {
let app = Self::new(boot);
app.hub.send_replace(Some(hub));
app
}
fn hub(&self) -> Option<Arc<Hub>> {
self.hub.borrow().clone()
}
/// The hub, waiting up to `wait` for it to start.
async fn hub_within(&self, wait: Duration) -> Option<Arc<Hub>> {
let mut hub = self.hub.subscribe();
let started = tokio::time::timeout(wait, hub.wait_for(Option::is_some)).await;
started.ok()?.ok()?.clone()
}
/// Wait for the WebSocket connections to close, at most `wait`.
async fn closed_within(&self, wait: Duration) {
let deadline = Instant::now() + wait;
while self.open.load(Ordering::Relaxed) > 0 && Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
}
pub fn router(app: Arc<App>) -> Router {
Router::new()
.route("/v1", get(ws))
.route("/health", get(|| async { "ok" }))
.route("/health", get(health))
.route("/.well-known/tsgw", get(well_known))
.with_state(hub)
.with_state(app)
}
/// `ok` while the gateway is logged in to the TeamSpeak server and watching
/// it; otherwise 503 and what is missing.
async fn health(State(app): State<Arc<App>>) -> (StatusCode, String) {
let Some(hub) = app.hub() else {
let starting = "starting: not logged in to the TeamSpeak server yet";
return (StatusCode::SERVICE_UNAVAILABLE, starting.into());
};
let (query, observer) = (hub.lookup.is_up(), hub.observer.is_connected());
if query && observer {
return (StatusCode::OK, "ok".into());
}
let state = |up| if up { "up" } else { "down" };
let text = format!("query: {}, observer: {}", state(query), state(observer));
(StatusCode::SERVICE_UNAVAILABLE, text)
}
/// Where apps reach this gateway, for those that find it by asking the
/// server's host on the default port (docs/gateway-admin.md): the
/// configured public URL, else this listener as the request reached it.
async fn well_known(State(hub): State<Arc<Hub>>, headers: HeaderMap) -> Json<serde_json::Value> {
let url = hub.boot.public_url.clone().unwrap_or_else(|| {
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("localhost");
format!("ws://{host}/v1")
});
async fn well_known(State(app): State<Arc<App>>, headers: HeaderMap) -> Json<serde_json::Value> {
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok());
let url = app
.boot
.public_url
.clone()
.unwrap_or_else(|| format!("ws://{}/v1", host.unwrap_or("localhost")));
debug!(host, answer = %url, "asked where the gateway is");
Json(serde_json::json!({ "url": url }))
}
async fn ws(State(hub): State<Arc<Hub>>, upgrade: WebSocketUpgrade) -> impl IntoResponse {
async fn ws(
State(app): State<Arc<App>>,
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
headers: HeaderMap,
upgrade: WebSocketUpgrade,
) -> Response {
let text = |name: header::HeaderName| {
headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned)
};
let peer = Peer {
id: app.connections.fetch_add(1, Ordering::Relaxed) + 1,
addr: connect_info.map(|Extension(ConnectInfo(addr))| addr),
forwarded_for: text(header::HeaderName::from_static("x-forwarded-for")),
user_agent: text(header::USER_AGENT),
};
let mut stop = app.stop.subscribe();
// Not held up by the wait at shutdown, which waits for open requests.
let hub = tokio::select! {
hub = app.hub_within(START_WAIT) => hub,
_ = stop.wait_for(|stopping| *stopping) => None,
};
if *stop.borrow_and_update() {
debug!(id = peer.id, peer = %peer.address(), "websocket refused: shutting down");
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is stopping").into_response();
}
let Some(hub) = hub else {
warn!(
id = peer.id,
peer = %peer.address(),
"websocket refused: not logged in to the TeamSpeak server yet"
);
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is starting").into_response();
};
upgrade
.protocols([voelin_gateway_proto::SUBPROTOCOL])
.on_upgrade(move |socket| session::run(hub, socket))
.on_upgrade(move |socket| async move {
app.open.fetch_add(1, Ordering::Relaxed);
session::run(hub, socket, peer, stop).await;
app.open.fetch_sub(1, Ordering::Relaxed);
})
.into_response()
}
/// `SIGHUP` reads the configuration file again.
#[cfg(unix)]
async fn reload_on_hangup(hub: Arc<Hub>) {
use tokio::signal::unix::{SignalKind, signal};
use tracing::warn;
let Ok(mut hangup) = signal(SignalKind::hangup()) else { return };
while hangup.recv().await.is_some() {
if let Err(error) = hub.settings.reload() {
@@ -103,7 +265,31 @@ async fn reload_on_hangup(hub: Arc<Hub>) {
#[cfg(not(unix))]
async fn reload_on_hangup(_hub: Arc<Hub>) {}
async fn shutdown() {
async fn shutdown(app: Arc<App>) {
terminated().await;
info!(connections = app.open.load(Ordering::Relaxed), "shutting down");
app.stop.send_replace(true);
}
/// Ctrl-C, or `SIGTERM` (`systemctl stop`, `docker stop`: as the
/// container's first process tsgw gets no default handling of it).
#[cfg(unix)]
async fn terminated() {
use tokio::signal::unix::{SignalKind, signal};
match signal(SignalKind::terminate()) {
Ok(mut term) => {
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
Err(_) => {
let _ = tokio::signal::ctrl_c().await;
}
}
}
#[cfg(not(unix))]
async fn terminated() {
let _ = tokio::signal::ctrl_c().await;
info!("shutting down");
}
+19 -7
View File
@@ -10,7 +10,9 @@ use std::sync::Mutex;
use std::time::{Duration, Instant};
use voelin_gateway_proto::PermRule;
use voelin_query::{Command, QueryClient, Row};
use voelin_query::{Command, Row};
use crate::lookup::Lookup;
const CACHE_TTL: Duration = Duration::from_secs(60);
@@ -87,7 +89,8 @@ pub struct PermIds {
}
impl PermIds {
pub async fn load(client: &QueryClient) -> voelin_query::Result<Self> {
/// Look the ids up. Failures are logged here or by the caller.
pub async fn load(client: &Lookup) -> voelin_query::Result<Self> {
let names = [
"i_channel_join_power",
"i_channel_needed_join_power",
@@ -98,7 +101,8 @@ impl PermIds {
];
let mut ids = [0u32; 6];
for (i, name) in names.iter().enumerate() {
let rows = client.send(&Command::new("permidgetbyname").arg("permsid", name)).await?;
let rows =
client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await?;
ids[i] = rows.first().and_then(|r| r.parse("permid")).ok_or_else(|| {
voelin_query::Error::Protocol(format!("unknown permission {name}"))
})?;
@@ -108,8 +112,16 @@ impl PermIds {
let mut optional = [0u32; 2];
for (i, name) in ["b_channel_modify_name", "b_virtualserver_modify_name"].iter().enumerate()
{
match client.send(&Command::new("permidgetbyname").arg("permsid", name)).await {
match client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await {
Ok(rows) => optional[i] = rows.first().and_then(|r| r.parse("permid")).unwrap_or(0),
// More commands now would get the gateway banned.
Err(voelin_query::Error::Query(e)) if e.is_flood() => {
tracing::warn!(
name,
"the server's flood protection refused looking up a permission; its default grants nobody"
);
break;
}
Err(error) => tracing::warn!(%error, name, "unknown permission"),
}
}
@@ -160,7 +172,7 @@ pub struct GroupResolver {
impl GroupResolver {
pub async fn server_groups(
&self,
client: &QueryClient,
client: &Lookup,
cldbid: u64,
) -> voelin_query::Result<Vec<u64>> {
if let Some((at, groups)) = self.server.lock().unwrap().get(&cldbid)
@@ -177,7 +189,7 @@ impl GroupResolver {
pub async fn channel_groups(
&self,
client: &QueryClient,
client: &Lookup,
cldbid: u64,
cid: u64,
) -> voelin_query::Result<Vec<u64>> {
@@ -231,7 +243,7 @@ impl PermResolver {
pub async fn entries(
&self,
client: &QueryClient,
client: &Lookup,
cldbid: u64,
cid: u64,
) -> voelin_query::Result<Vec<Entry>> {
+136 -20
View File
@@ -1,15 +1,17 @@
//! One WebSocket client.
use std::collections::HashSet;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::extract::ws::{Message, WebSocket};
use axum::extract::ws::{CloseFrame, Message, WebSocket, close_code};
use base64::prelude::*;
use rand::RngExt;
use serde::Deserialize;
use tokio::sync::broadcast::error::RecvError;
use tracing::{debug, info};
use tokio::sync::watch;
use tracing::{Instrument, Level, debug, info, info_span, warn};
use voelin_gateway_proto::{ClientMsg, Envelope, ErrorCode, EventInfo, ServerMsg, feature};
use voelin_model::{ChatTarget, Presence};
use voelin_observer::ObserverEvent;
@@ -53,13 +55,50 @@ struct Session {
actions: RateLimit,
}
/// Enough of an envelope to answer one that did not parse.
/// Enough of an envelope to answer one that did not parse, and to name it
/// in the log.
#[derive(Deserialize)]
struct RawEnvelope {
id: Option<u64>,
/// Any JSON value: a `type` that is no string must not cost the `id`.
#[serde(rename = "type")]
kind: Option<serde_json::Value>,
}
pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
/// Requests that take longer are logged.
const SLOW: Duration = Duration::from_secs(1);
/// Where a connection comes from, for the log.
#[derive(Debug)]
pub struct Peer {
/// Counts connections since the start.
pub id: u64,
/// The address the connection came from (a proxy's, behind one).
pub addr: Option<SocketAddr>,
pub forwarded_for: Option<String>,
pub user_agent: Option<String>,
}
impl Peer {
/// [`Peer::addr`] for the log.
pub fn address(&self) -> String {
self.addr.map_or_else(|| "unknown".to_string(), |a| a.to_string())
}
}
/// Serve one connection until it closes or `stop` turns true.
pub async fn run(hub: Arc<Hub>, socket: WebSocket, peer: Peer, stop: watch::Receiver<bool>) {
let span = info_span!("ws", id = peer.id, peer = %peer.address());
serve(hub, socket, peer, stop).instrument(span).await;
}
async fn serve(hub: Arc<Hub>, mut socket: WebSocket, peer: Peer, mut stop: watch::Receiver<bool>) {
let connected = Instant::now();
info!(
forwarded_for = peer.forwarded_for.as_deref(),
user_agent = peer.user_agent.as_deref(),
"websocket connected"
);
let nonce_bytes: [u8; 24] = rand::rng().random();
let mut session = Session {
nonce: BASE64_URL_SAFE_NO_PAD.encode(nonce_bytes),
@@ -83,22 +122,29 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
capabilities: hub.capabilities(),
};
if send(&mut socket, None, hello).await.is_err() {
info!(reason = "could not send", "websocket closed");
return;
}
let mut observer = hub.observer.subscribe();
let mut events = hub.subscribe();
'outer: loop {
let reason = 'outer: loop {
tokio::select! {
msg = socket.recv() => {
let Some(Ok(msg)) = msg else { break };
let text = match msg {
Message::Text(t) => t,
Message::Close(_) => break,
_ => continue,
Some(Ok(Message::Text(t))) => t,
Some(Ok(Message::Close(_))) => break "closed by the app".to_string(),
Some(Ok(_)) => continue,
Some(Err(e)) => break format!("connection failed: {e}"),
None => break "connection ended".to_string(),
};
let replies = match serde_json::from_str::<Envelope<ClientMsg>>(text.as_str()) {
Ok(env) => session.handle(env.msg).await.into_iter().map(|m| (env.id, m)).collect(),
Ok(env) => {
let started = Instant::now();
let replies = session.handle(env.msg).await;
log_request(text.as_str(), started.elapsed(), &replies);
replies.into_iter().map(|m| (env.id, m)).collect()
}
Err(e) => {
let id = serde_json::from_str::<RawEnvelope>(text.as_str()).ok().and_then(|r| r.id);
let code = if e.to_string().starts_with("unknown variant") {
@@ -111,18 +157,18 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
};
for (id, reply) in replies {
if send(&mut socket, id, reply).await.is_err() {
break 'outer;
break 'outer "could not send".to_string();
}
}
}
event = observer.recv(), if session.presence.is_some() => {
let resync = matches!(event, Err(RecvError::Lagged(_)) | Ok(ObserverEvent::Snapshot(_)));
if let Err(RecvError::Closed) = event {
break;
break "the gateway stopped".to_string();
}
for msg in session.presence_update(resync) {
if send(&mut socket, None, msg).await.is_err() {
break 'outer;
break 'outer "could not send".to_string();
}
}
}
@@ -130,19 +176,59 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
let event = match event {
Ok(event) => event,
Err(RecvError::Lagged(_)) => continue,
Err(RecvError::Closed) => break,
Err(RecvError::Closed) => break "the gateway stopped".to_string(),
};
for msg in session.push(&event).await {
if send(&mut socket, None, msg).await.is_err() {
break 'outer;
break 'outer "could not send".to_string();
}
}
}
// Turns true once, at shutdown.
_ = stop.changed() => {
// Apps connect again at once instead of finding out later.
let frame = CloseFrame { code: close_code::AWAY, reason: "the gateway is restarting".into() };
let _ = socket.send(Message::Close(Some(frame))).await;
break "the gateway is shutting down".to_string();
}
}
}
};
info!(
uid = session.user.as_ref().map(|u| u.uid.as_str()),
connected_s = connected.elapsed().as_secs(),
%reason,
open_chats = session.open_chats.len(),
"websocket closed"
);
session.close();
}
/// Log a request that failed on the gateway's side or took long, and every
/// request at debug level.
fn log_request(text: &str, elapsed: Duration, replies: &[ServerMsg]) {
let failure = replies.iter().find_map(|m| match m {
ServerMsg::Error {
code: code @ (ErrorCode::Unavailable | ErrorCode::Internal),
message,
} => Some((code, message.as_str())),
_ => None,
});
let slow = elapsed >= SLOW;
if !slow && failure.is_none() && !tracing::enabled!(Level::DEBUG) {
return;
}
let kind = serde_json::from_str::<RawEnvelope>(text).ok().and_then(|r| r.kind);
let request = kind.as_ref().and_then(serde_json::Value::as_str).unwrap_or("unknown");
let elapsed_ms = elapsed.as_millis() as u64;
match failure {
// Logged as a refused login.
Some(_) if matches!(request, "auth" | "resume") => {}
Some((code, error)) => warn!(request, ?code, error, elapsed_ms, "request failed"),
None if slow => warn!(request, elapsed_ms, "slow request"),
None => debug!(request, elapsed_ms, "request"),
}
}
async fn send(socket: &mut WebSocket, id: Option<u64>, msg: ServerMsg) -> Result<(), axum::Error> {
let env = Envelope { v: voelin_gateway_proto::VERSION, id, msg };
let text = serde_json::to_string(&env).expect("messages serialize");
@@ -175,9 +261,21 @@ fn is_action(msg: &ClientMsg) -> bool {
impl Session {
async fn handle(&mut self, msg: ClientMsg) -> Vec<ServerMsg> {
let login = match &msg {
ClientMsg::Auth { .. } => Some("signature"),
ClientMsg::Resume { .. } => Some("token"),
_ => None,
};
let started = Instant::now();
match self.handle_inner(msg).await {
Ok(msgs) => msgs,
Err(Denied(code, message)) => vec![error(code, &message)],
Err(Denied(code, message)) => {
if let Some(via) = login {
let elapsed_ms = started.elapsed().as_millis() as u64;
warn!(?code, %message, via, elapsed_ms, "login refused");
}
vec![error(code, &message)]
}
}
}
@@ -203,14 +301,15 @@ impl Session {
match msg {
ClientMsg::Ping => Ok(vec![ServerMsg::Pong]),
ClientMsg::Auth { omega, key_offset, ts, signature, .. } => {
let started = Instant::now();
let (user, token, token_expires) =
hub.authenticate(&omega, key_offset, ts, &signature, &self.nonce).await?;
info!(uid = %user.uid, nickname = %user.nickname, "user logged in");
self.logged_in(user, token, token_expires).await
self.logged_in(user, token, token_expires, "signature", started).await
}
ClientMsg::Resume { token, .. } => {
let started = Instant::now();
let (user, token, token_expires) = hub.resume(&token).await?;
self.logged_in(user, token, token_expires).await
self.logged_in(user, token, token_expires, "token", started).await
}
ClientMsg::SubscribePresence => {
self.user()?;
@@ -437,9 +536,13 @@ impl Session {
user: User,
token: String,
token_expires: i64,
via: &str,
started: Instant,
) -> Result<Vec<ServerMsg>, Denied> {
let capabilities = self.hub.user_capabilities(&user).await;
let uid = user.uid.clone();
let elapsed_ms = started.elapsed().as_millis() as u64;
info!(uid = %user.uid, nickname = %user.nickname, via, elapsed_ms, "user logged in");
self.user = Some(user);
Ok(vec![ServerMsg::AuthOk { uid, token, token_expires, capabilities }])
}
@@ -571,3 +674,16 @@ impl Session {
self.hub.session_streams_closed(&self.own_streams);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bad_request_keeps_its_id() {
let raw = |text: &str| serde_json::from_str::<RawEnvelope>(text).unwrap();
assert_eq!(raw(r#"{"id":7,"type":5}"#).id, Some(7));
assert_eq!(raw(r#"{"id":8,"type":"ping","extra":[]}"#).id, Some(8));
assert_eq!(raw(r#"{"type":"ping"}"#).id, None);
}
}
+7 -3
View File
@@ -81,8 +81,12 @@ pub async fn pump_relays(hub: Arc<Hub>, mut events: broadcast::Receiver<RelayEve
hub.publish_incoming(msg);
}
}
Ok(RelayEvent::Closed { channel, reason }) => {
warn!(channel, %reason, "relay closed");
// Logged by the pool.
Ok(RelayEvent::Closed { channel, .. }) => {
if hub.relay_wanted(channel) {
let hub = hub.clone();
tokio::spawn(async move { hub.reopen_relay(channel).await });
}
}
Err(RecvError::Lagged(_)) => {}
Err(RecvError::Closed) => return,
@@ -196,7 +200,7 @@ async fn apply_settings(hub: Arc<Hub>) {
hub.rebuild_relays(&new.relay.nickname).await;
}
if new.relay.pinned_channels != old.relay.pinned_channels {
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels).await;
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels);
}
let features_changed = Feature::ALL.iter().any(|f| f.enabled(&old) != f.enabled(&new));
if features_changed || new.perm.admin != old.perm.admin {
+48 -2
View File
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::sync::{broadcast, mpsc};
use voelin_query::{Command, escape};
/// Permission ids the fake server uses.
@@ -60,12 +60,18 @@ pub struct State {
/// Relay connections by channel.
relays: Vec<(u64, mpsc::UnboundedSender<String>)>,
next_clid: u16,
/// Permission lookups (`permsid`) to refuse for flooding, and how often.
refusals: HashMap<String, usize>,
/// The commands received, in order (`login` left out).
commands: Vec<String>,
}
#[derive(Clone)]
pub struct FakeServer {
pub addr: SocketAddr,
pub state: Arc<Mutex<State>>,
/// Ends every open connection, like a server restart.
kick: broadcast::Sender<()>,
}
impl FakeServer {
@@ -73,7 +79,7 @@ impl FakeServer {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let state = Arc::new(Mutex::new(State { next_clid: 100, ..Default::default() }));
let server = Self { addr, state };
let server = Self { addr, state, kick: broadcast::channel(1).0 };
let s = server.clone();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
@@ -120,6 +126,35 @@ impl FakeServer {
}
}
/// Answer looking up permission `permsid` with the flood protection's
/// refusal, the next `times` times.
pub fn refuse(&self, permsid: &str, times: usize) {
self.state.lock().unwrap().refusals.insert(permsid.to_string(), times);
}
/// The commands received so far, in order (`login` left out).
pub fn commands(&self) -> Vec<String> {
self.state.lock().unwrap().commands.clone()
}
/// An observer connection is registered for server events.
pub fn observed(&self) -> bool {
!self.state.lock().unwrap().observers.is_empty()
}
/// Channels with a relay listening.
pub fn relayed_channels(&self) -> Vec<u64> {
self.state.lock().unwrap().relays.iter().map(|(c, _)| *c).collect()
}
/// Drop every query connection, as a restarting server does.
pub fn drop_connections(&self) {
let mut s = self.state.lock().unwrap();
s.observers.clear();
s.relays.clear();
let _ = self.kick.send(());
}
pub fn posted(&self) -> Vec<(u8, u64, String)> {
self.state.lock().unwrap().posted.clone()
}
@@ -134,6 +169,7 @@ impl FakeServer {
let (r, mut w) = stream.into_split();
let mut lines = BufReader::new(r).lines();
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
let mut kicked = self.kick.subscribe();
let clid = {
let mut s = self.state.lock().unwrap();
s.next_clid += 1;
@@ -148,6 +184,9 @@ impl FakeServer {
line = lines.next_line() => {
let Ok(Some(line)) = line else { return };
let Some(cmd) = Command::parse(&line) else { continue };
if cmd.name != "login" {
self.state.lock().unwrap().commands.push(line.clone());
}
let reply = self.answer(&cmd, clid, &mut channel, &tx);
if w.write_all(reply.as_bytes()).await.is_err() {
return;
@@ -158,6 +197,7 @@ impl FakeServer {
return;
}
}
_ = kicked.recv() => return,
}
}
}
@@ -194,6 +234,12 @@ impl FakeServer {
]),
"permidgetbyname" => {
let name = arg("permsid").unwrap_or_default();
if let Some(left @ 1..) = s.refusals.get_mut(&name) {
*left -= 1;
return "error id=524 msg=client\\sis\\sflooding \
extra_msg=please\\swait\\s1\\sseconds\n\r"
.into();
}
match PERMS.iter().find(|(n, _)| *n == name) {
Some((_, id)) => data(vec![format!("permsid={name} permid={id}")]),
None => "error id=2 msg=invalid\\spermission\n\r".into(),
+102 -2
View File
@@ -26,6 +26,7 @@ const LOBBY: ChatTarget = ChatTarget::Channel(1);
struct Fixture {
fake: FakeServer,
boot: crate::config::Bootstrap,
hub: Arc<Hub>,
url: String,
dir: std::path::PathBuf,
@@ -80,6 +81,7 @@ impl Fixture {
});
}
let layers = Layers { file: file_values(&toml).unwrap(), ..Default::default() };
let boot = layers.bootstrap().unwrap();
let hub = Hub::start(layers).await.unwrap();
// Wait for the observer's first snapshot.
for _ in 0..100 {
@@ -90,9 +92,10 @@ impl Fixture {
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
let app = crate::router(hub.clone());
let app = crate::router(crate::App::started(boot.clone(), hub.clone()))
.into_make_service_with_connect_info::<std::net::SocketAddr>();
tokio::spawn(async move { axum::serve(listener, app).await });
Self { fake, hub, url, dir, people }
Self { fake, boot, hub, url, dir, people }
}
fn people(&self) -> (&Person, &Person, &Person) {
@@ -583,3 +586,100 @@ async fn tells_apps_where_it_is() {
let fx = Fixture::start("well-known-public", public).await;
assert_eq!(well_known(&fx).await, "wss://gw.example.test/v1");
}
/// The TeamSpeak server drops the gateway's query connections (a restart):
/// logins go on working, through a new lookup connection.
#[tokio::test(flavor = "multi_thread")]
async fn logins_work_after_the_server_dropped_the_gateway() {
let fx = Fixture::start("reconnect", "").await;
let (alice, bob, _) = fx.people();
let (b, mut b_rx) = bob.connect(&fx).await;
b.open_chat(LOBBY).await.unwrap();
b.open_chat(ChatTarget::Server).await.unwrap();
assert!(fx.hub.lookup.is_up());
let old_id = fx.hub.lookup.own_id().unwrap();
fx.fake.drop_connections();
// At once: the login waits for the new connection.
let (a, _a_rx) = alice.connect(&fx).await;
assert!(a.has(feature::ADMIN));
assert!(fx.hub.lookup.is_up());
a.post(ChatTarget::Server, "back again".into(), None).await.unwrap();
assert!(fx.fake.posted().contains(&(3, 1, "back again".into())));
// Bob still reads the lobby: its relay comes back.
for _ in 0..100 {
if fx.fake.relayed_channels().contains(&1) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
fx.fake.say_in_channel(1, "Dave", "dave", "after the restart");
expect(
&mut b_rx,
"relayed after the restart",
|p| matches!(p, Push::Chat { message, .. } if message.text == "after the restart"),
)
.await;
// A restarted server hands out client ids from 1 again: a user may get
// the one the gateway had. Their server chat is not the gateway's own.
assert_ne!(fx.hub.lookup.own_id(), Some(old_id));
for _ in 0..100 {
if fx.fake.observed() {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
fx.fake.notify_observers(&format!(
"notifytextmessage targetmode=3 msg=hi\\sall invokerid={old_id} invokername=Erin \
invokeruid=erin"
));
expect(
&mut b_rx,
"server chat from the gateway's old id",
|p| matches!(p, Push::Chat { message, .. } if message.text == "hi all"),
)
.await;
}
/// The server's flood protection refuses looking up an optional permission,
/// also when asked again after the wait: the gateway asks for no more, which
/// would get it banned for 10 minutes.
#[tokio::test(flavor = "multi_thread")]
async fn optional_permissions_stop_at_the_flood_protection() {
let fake = FakeServer::start().await;
fake.refuse("b_channel_modify_name", 2);
let connect = voelin_query::Connect {
transport: voelin_query::Transport::Raw,
addr: fake.addr.to_string(),
user: "serveradmin".into(),
secret: None,
server_port: None,
server_id: None,
// Taken to be on the allowlist.
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
};
let lookup = crate::lookup::Lookup::open(connect, "Gateway".into()).await;
let ids = crate::perms::PermIds::load(&lookup).await.unwrap();
assert_eq!(ids.subscribe_power, fake::SUBSCRIBE_POWER);
assert_eq!((ids.channel_modify_name, ids.server_modify_name), (0, 0));
let asked = fake.commands();
let count =
|name: &str| asked.iter().filter(|c| c.ends_with(&format!("permsid={name}"))).count();
assert_eq!(count("b_channel_modify_name"), 2, "{asked:?}");
assert_eq!(count("b_virtualserver_modify_name"), 0, "{asked:?}");
}
/// `/health` says what is missing until the gateway is logged in.
#[tokio::test(flavor = "multi_thread")]
async fn health_tells_whether_the_gateway_is_up() {
use axum::extract::State;
use axum::http::StatusCode;
let fx = Fixture::start("health", "").await;
let app = crate::App::started(fx.boot.clone(), fx.hub.clone());
assert_eq!(crate::health(State(app)).await, (StatusCode::OK, "ok".to_string()));
let starting = crate::App::new(fx.boot.clone());
let (status, text) = crate::health(State(starting)).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert!(text.starts_with("starting"), "{text}");
}
+8
View File
@@ -33,6 +33,14 @@ allowlisted = false
bind = "0.0.0.0:7788"
# public_url = "wss://gw.example.org/v1"
# BOOTSTRAP. The log goes to standard output (journalctl -u tsgw, docker logs).
# Uncomment to change it; tsgw versions before these keys refuse the section.
# [log]
# What to log (TSGW_LOG_LEVEL); default: RUST_LOG, else info.
# level = "info,voelin_query=trace"
# Also write it to this file: appended, moved aside at 20 MB, 5 files kept.
# file = "logs/tsgw.log"
[auth]
# Only these server groups may use the gateway (empty: everyone known to the server).
require_server_groups = []
+1 -1
View File
@@ -15,7 +15,7 @@ pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, s
pub use link::{Link, ServerLink, channel_path_id, join_channel_path, split_channel_path};
pub use presence::{
ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType,
Presence, PresenceDelta, PresenceSnapshot, parse_badges,
Presence, PresenceDelta, PresenceSnapshot, myts_avatar_url, parse_badges, shown_badges,
};
pub use server::{
BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion,
+93 -1
View File
@@ -98,6 +98,11 @@ pub struct ClientInfo {
/// no avatar. A new hash means a new avatar.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar: Option<String>,
/// The myTeamSpeak avatar's picture (TeamSpeak 6, an HTTPS link from
/// `client_myteamspeak_avatar`, [`myts_avatar_url`]): shown where the
/// server has no avatar for the client.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub myts_avatar: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "is_zero_i32")]
@@ -107,7 +112,7 @@ pub struct ClientInfo {
pub talker: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_group: Option<GroupId>,
/// Badge GUIDs (`client_badges`), in display order.
/// Badge GUIDs, in display order ([`shown_badges`]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub badges: Vec<String>,
/// Icon id (`client_icon_id`); 0: none.
@@ -136,6 +141,48 @@ pub fn parse_badges(value: &str) -> Vec<String> {
.collect()
}
/// The badges a client shows: those a TeamSpeak 6 server verified
/// (`client_signed_badges`, ids joined by `,`) first, then those of its
/// `client_badges` ([`parse_badges`]), each once.
pub fn shown_badges(badges: &str, signed: &str) -> Vec<String> {
let signed = signed.split(',').map(str::trim).filter(|g| !g.is_empty()).map(str::to_owned);
let mut shown: Vec<String> = Vec::new();
for guid in signed.chain(parse_badges(badges)) {
if !shown.iter().any(|g| g.eq_ignore_ascii_case(&guid)) {
shown.push(guid);
}
}
shown
}
/// The picture to show of a `client_myteamspeak_avatar` value (TeamSpeak
/// 6): `<state>,<url>;<state>,<url>…`, states as myTeamSpeak's
/// `AvatarState` (1 do not disturb, 2 online, 3 away, 4 offline). As the
/// official client reads it: an entry that is not `<number>,<url>` (an
/// empty one too, from a trailing `;`) makes the whole value no avatar;
/// the "online" picture is shown whatever the client's state (an unknown
/// state counts as online), else away, do not disturb, offline, the first
/// of a kind. Only an HTTPS link of at most 4 KiB.
pub fn myts_avatar_url(value: &str) -> Option<String> {
let mut best: Option<(u8, &str)> = None;
for entry in value.split(';') {
let mut parts = entry.split(',');
let state: u32 = parts.next()?.trim().parse().ok()?;
let url = parts.next()?.trim();
let rank = match state {
3 => 1,
1 => 2,
4 => 3,
_ => 0,
};
if best.is_none_or(|(r, _)| rank < r) {
best = Some((rank, url));
}
}
let url = best?.1;
(url.starts_with("https://") && url.len() <= 4096).then(|| url.to_owned())
}
/// How a group's name is shown next to its members.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -348,6 +395,38 @@ mod tests {
assert!(new.diff(&new).is_empty());
}
#[test]
fn myts_avatars_as_the_official_client_reads_them() {
let on = "https://a.example.test/on.png";
assert_eq!(myts_avatar_url(&format!("3,https://a/away;2,{on}")).as_deref(), Some(on));
// Away before do not disturb before offline; the first of a kind.
assert_eq!(
myts_avatar_url("4,https://a/off;1,https://a/dnd;3,https://a/away;3,https://a/b")
.as_deref(),
Some("https://a/away")
);
assert_eq!(
myts_avatar_url("1,https://a/dnd;4,https://a/off").as_deref(),
Some("https://a/dnd")
);
// An unknown state counts as online.
assert_eq!(
myts_avatar_url("3,https://a/away;9,https://a/x").as_deref(),
Some("https://a/x")
);
// One bad entry spoils the value.
for bad in ["", "2", "x,https://a/on", "2,https://a/on;", "2,https://a/on;;3,https://a/b"] {
assert_eq!(myts_avatar_url(bad), None, "{bad:?}");
}
// Only HTTPS, and not endless.
assert_eq!(myts_avatar_url("2,http://a/on"), None);
assert_eq!(myts_avatar_url(&format!("2,https://a/{}", "x".repeat(4096))), None);
// Older JSON without the field still loads.
let client: ClientInfo =
serde_json::from_str(r#"{"id":1,"nickname":"a","channel":1}"#).unwrap();
assert_eq!(client.myts_avatar, None);
}
#[test]
fn badges_and_groups() {
assert_eq!(
@@ -358,6 +437,19 @@ mod tests {
);
assert!(parse_badges("").is_empty());
assert!(parse_badges("Overwolf=1").is_empty());
// TeamSpeak 6's verified badges first, each once.
assert_eq!(
shown_badges(
"Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157",
"450F81C1-AB41-4211-A338-222FA94ED157,1cb07348-34a4-4741-b50f-c41e584370f7"
),
[
"450F81C1-AB41-4211-A338-222FA94ED157",
"1cb07348-34a4-4741-b50f-c41e584370f7",
"c9e97536-5a2d-4c8e-a135-af404587a472"
]
);
assert!(shown_badges("", "").is_empty());
let group = |id, sort_id| GroupInfo { id, sort_id, ..Default::default() };
let groups = BTreeMap::from([(1, group(1, 20)), (2, group(2, 10)), (3, group(3, 10))]);
let order: Vec<_> = Presence::sorted_groups(&groups).iter().map(|g| g.id).collect();
+12
View File
@@ -22,9 +22,21 @@ schema-api = { path = "../../third_party/schema-api", default-features = false }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "http2"] }
thiserror = "2.0.21"
tokio = { version = "1.53.1", features = ["rt", "time"] }
# Synthetic certificate chains and signatures for tests (both already in the
# graph through tsproto).
curve25519-dalek = { version = "4", optional = true }
sha2 = { version = "0.10", optional = true }
[features]
# `voelin_myts::testing`: certificates and what they sign from a synthetic
# root, for other crates' tests.
testing = ["dep:curve25519-dalek", "dep:sha2"]
[dev-dependencies]
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "net", "io-util"] }
# Synthetic certificate chains and signatures (both already in the graph).
curve25519-dalek = "4"
sha2 = "0.10"
[lints]
workspace = true
+100 -1
View File
@@ -3,11 +3,22 @@
//! Requests use the official client's method envelope and password derivation.
//! No requests or credentials are logged.
mod identity;
mod presentation;
mod profile;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
mod transport;
mod user_tag;
pub use identity::IdentityError;
pub use profile::{Badge, Device, Profile};
pub use presentation::{
OwnAvatar, SignedBadge, avatar_has_pictures, badge_list, choose_avatar, choose_avatar_from,
choose_badges_certificate, choose_badges_certificate_from,
};
pub use profile::{Badge, Device, Presentation, Profile};
/// The key myTeamSpeak's certificates lead to (TeamSpeak's root).
pub use tsproto::ROOT_KEY;
pub use tsproto::myts::Identity as ServerIdentity;
pub use user_tag::{UserTagError, check_user_tag, check_user_tag_from};
use zeroize::{Zeroize, Zeroizing};
use base64::{Engine as _, engine::general_purpose::STANDARD};
@@ -27,6 +38,9 @@ pub struct Login {
/// What the login response tells about the account (the avatar's file
/// names, the description); [`Client::profile`] tells more.
pub profile: Profile,
/// What voice servers are shown of the account (its avatar), as
/// signed by myTeamSpeak.
pub presentation: Presentation,
}
/// Server-provided alternative login material, stored only in a secret store.
@@ -74,6 +88,10 @@ pub enum Error {
MissingRenewalCredentials,
#[error("account service refused the request (code {0})")]
Refused(i32),
#[error("chat service refused the request (code {0})")]
ChatRefused(i32),
#[error("the chat service sent no token")]
NoToken,
#[error("the account's avatar is not an HTTPS link")]
AvatarUrl,
#[error("avatar download returned HTTP {0}")]
@@ -181,7 +199,17 @@ impl Client {
encryption_key: Option<Zeroizing<[u8; 32]>>,
) -> Result<Login, Error> {
let bytes = self.transport.call("authentication", method, body).await?;
// The avatar exactly as it came: its signature covers its bytes.
let avatar = profile::raw_field(&bytes, profile::USER_AVATAR).unwrap_or_default().to_vec();
let response: api::LoginSession = wire::decode(bytes)?;
let presentation = Presentation {
certificate: response
.mytsid_user_cert
.as_ref()
.map(|c| c.cert.clone())
.unwrap_or_default(),
avatar,
};
let token = SessionToken::try_from(&response)?;
let (response, identity) = tokio::task::spawn_blocking(move || {
let identity = match encryption_key {
@@ -197,6 +225,7 @@ impl Client {
token,
identity,
profile,
presentation,
uuid: response.uuid,
username: response.username,
renewal: response.alternative_login_info.map(|info| Renewal {
@@ -225,6 +254,76 @@ impl Client {
self.transport.download(url, profile::MAX_AVATAR_BYTES).await
}
/// The account's avatar as myTeamSpeak's avatar service hands it out
/// for the account's own myTS ID (`requestContactsAvatar` at `/user`),
/// with the certificate that came with it: what servers are shown,
/// without a password sign-in. `None` tells nothing: the service
/// answers an unknown session as it answers "nothing to show".
pub async fn own_avatar(
&self,
token: &SessionToken,
myts_id: &[u8],
) -> Result<Option<OwnAvatar>, Error> {
transport::check_input_size(&[token.as_str()])?;
let request = presentation::own_avatar_request(token, myts_id);
let bytes =
self.transport.call("user", "requestContactsAvatar", &wire::encode(&request)).await?;
presentation::own_avatar(&bytes, myts_id)
}
/// The account's badges, signed for its myTS ID (`getSignedBadges` at
/// `/user`). `None`: the answer has no list (nothing learned).
pub async fn signed_badges(
&self,
token: &SessionToken,
) -> Result<Option<Vec<SignedBadge>>, Error> {
transport::check_input_size(&[token.as_str()])?;
let request = api::user::Session { session: token.as_str().into() };
let bytes = self.transport.call("user", "getSignedBadges", &wire::encode(&request)).await?;
presentation::signed_badges(&bytes)
}
/// The account's primary User Tag, its primary chat identifier
/// (`getActiveIdentifierList` at `/tschat`; the account data's active
/// identifiers when that names none). `None`: the account has none.
pub async fn user_tag(&self, token: &SessionToken) -> Result<Option<String>, Error> {
transport::check_input_size(&[token.as_str()])?;
let request = wire::encode(&user_tag::request(token));
let listed = async {
let bytes = self.transport.call("tschat", "getActiveIdentifierList", &request).await?;
user_tag::primary(wire::decode(bytes)?)
}
.await;
match listed {
Ok(Some(tag)) => return Ok(Some(tag)),
Err(error) if error.is_invalid_session() => return Err(error),
_ => {}
}
let request = wire::encode(&user_tag::account_request(token));
let bytes = self.transport.call("user", "getAccountData", &request).await;
let data = bytes.and_then(|bytes| {
let data: api::user::UserAccountData = wire::decode(bytes)?;
profile::check(data.return_code.as_ref())?;
Ok(data)
});
match data {
Ok(data) => Ok(user_tag::account_primary(&data)),
// The chat service's answer tells more.
Err(error) => listed.and(Err(error)),
}
}
/// The token that proves the account's User Tags
/// (`requestSignedAllowedIdentifierList` at `/tschat`), exactly as it
/// came; check it with [`check_user_tag`].
pub async fn user_tag_token(&self, token: &SessionToken) -> Result<Vec<u8>, Error> {
transport::check_input_size(&[token.as_str()])?;
let request = wire::encode(&user_tag::request(token));
let bytes =
self.transport.call("tschat", "requestSignedAllowedIdentifierList", &request).await?;
user_tag::token(&bytes)
}
pub async fn validate_session(&self, token: &SessionToken) -> Result<(), Error> {
let response = self.session_call("session", token).await?;
Ok(session::validate_session_status(&response)?)
+411
View File
@@ -0,0 +1,411 @@
//! What voice servers are shown of the account besides its myTS ID
//! (TeamSpeak 6): its avatar and badges, as myTeamSpeak signed them for
//! the myTS ID. A server checks them with the one certificate of each
//! `updatemytsdata` and silently shows nothing of what does not verify, so
//! they are checked here first, the same way, to choose a certificate that
//! verifies them.
//!
//! All of it is public: certificates, signatures, the avatar's links,
//! badge ids.
use crate::{Error, profile};
use schema_api::api::{self, user};
use schema_api::{SessionToken, wire};
use tsproto::myts::Certificate;
/// `RequestContactsAvatarInfoResponse.data`, `AvatarInfoMap.info`.
const AVATAR_DATA: u32 = 1;
const AVATAR_INFO: u32 = 2;
/// `AvatarData.info`.
const INFO: u32 = 1;
/// `UserBadgesSignedResponse.list`, `UserBadgesSignedList.badges`.
const SIGNED_LIST: u32 = 1;
const SIGNED_BADGES: u32 = 1;
/// The account's avatar as myTeamSpeak's avatar service hands it out for
/// the account's own myTS ID (`requestContactsAvatar`), with the
/// certificate that came with it.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct OwnAvatar {
/// `OptionalAvatarDataContactInfo.user_cert`: a certificate like the
/// one a password sign-in brings.
pub certificate: Vec<u8>,
/// The `AvatarData` exactly as it came.
pub avatar: Vec<u8>,
}
impl std::fmt::Debug for OwnAvatar {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OwnAvatar")
.field("certificate", &self.certificate.len())
.field("avatar", &self.avatar.len())
.finish()
}
}
/// One of the account's badges, signed for its myTS ID (`getSignedBadges`).
#[derive(Clone, PartialEq, Eq)]
pub struct SignedBadge {
pub uuid: String,
pub name: String,
/// The badge's picture.
pub url: String,
/// The `SignedUserBadge` as it came.
raw: Vec<u8>,
}
impl SignedBadge {
/// A `SignedUserBadge` as it came (and as [`Self::raw`] keeps it).
pub fn parse(raw: &[u8]) -> Option<Self> {
let signed: user::SignedUserBadge = wire::decode(raw).ok()?;
let badge = signed.badge?;
Some(Self { uuid: badge.uuid, name: badge.name, url: badge.url, raw: raw.to_vec() })
}
pub fn raw(&self) -> &[u8] {
&self.raw
}
}
impl std::fmt::Debug for SignedBadge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SignedBadge").field("uuid", &self.uuid).field("name", &self.name).finish()
}
}
/// `badges` as a `UserBadgesSignedList` (`myts_signed_badge`), each badge
/// exactly as it came.
pub fn badge_list<'a>(badges: impl IntoIterator<Item = &'a SignedBadge>) -> Vec<u8> {
let mut list = Vec::new();
for badge in badges {
list.push(((SIGNED_BADGES << 3) | 2) as u8);
let mut length = badge.raw.len();
while length >= 0x80 {
list.push(length as u8 | 0x80);
length >>= 7;
}
list.push(length as u8);
list.extend_from_slice(&badge.raw);
}
list
}
pub(crate) fn own_avatar_request(
token: &SessionToken,
myts_id: &[u8],
) -> user::RequestContactsAvatarInfoRequest {
user::RequestContactsAvatarInfoRequest {
session: token.as_str().into(),
id: vec![user::AvatarRequestId {
key: Some(wire::pack_any(&user::avatar_request_id::MytsKey { id: myts_id.to_vec() })),
}],
}
}
/// The reply to [`own_avatar_request`]: the entry for `myts_id`, if it
/// came with a certificate. The service answers an unknown session as it
/// answers "nothing to show" (with nothing), so `None` tells nothing.
pub(crate) fn own_avatar(bytes: &[u8], myts_id: &[u8]) -> Result<Option<OwnAvatar>, Error> {
let response: user::RequestContactsAvatarInfoResponse = wire::decode(bytes)?;
if response.error_code != 0 {
return Err(Error::Refused(response.error_code));
}
for map in profile::raw_fields(bytes, AVATAR_DATA).unwrap_or_default() {
let Some(raw) = profile::raw_field(map, AVATAR_INFO) else { continue };
let Ok(avatar) = wire::decode::<api::AvatarData>(raw) else { continue };
let Some(contact) = avatar
.optional
.as_ref()
.and_then(|any| wire::unpack_any::<api::OptionalAvatarDataContactInfo>(any).ok())
else {
continue;
};
if contact.mytsid == myts_id && !contact.user_cert.is_empty() {
return Ok(Some(OwnAvatar { certificate: contact.user_cert, avatar: raw.to_vec() }));
}
}
Ok(None)
}
/// The reply to `getSignedBadges`: the badges as they came. `None`: the
/// reply has no list (nothing learned).
pub(crate) fn signed_badges(bytes: &[u8]) -> Result<Option<Vec<SignedBadge>>, Error> {
let response: user::UserBadgesSignedResponse = wire::decode(bytes)?;
if response.error_code != 0 {
return Err(Error::Refused(response.error_code));
}
let Some(list) = profile::raw_field(bytes, SIGNED_LIST) else { return Ok(None) };
let badges = profile::raw_fields(list, SIGNED_BADGES).unwrap_or_default();
Ok(Some(badges.into_iter().filter_map(SignedBadge::parse).collect()))
}
/// A certificate a TeamSpeak 6 server takes for an avatar or badges at
/// `now`: its chain from `root`, a leaf that signs for myTS IDs and is
/// valid then.
fn signing_certificate(bytes: &[u8], root: &[u8; 32], now: i64) -> Option<Certificate> {
Certificate::parse(bytes, root).ok().filter(|c| c.signs_myts_data() && c.valid_at(now))
}
/// The message signed, as a server builds it: a part serialized again
/// (C++ `SerializeAsString`), then what follows. Serialized again by this
/// version, a part can differ from the bytes that came (fields this version
/// does not know), so those count too.
fn messages(raw: &[u8], encoded: Vec<u8>, tail: &[u8]) -> Vec<Vec<u8>> {
let mut parts = vec![encoded];
if parts[0] != raw {
parts.push(raw.to_vec());
}
parts
.into_iter()
.map(|mut message| {
message.extend_from_slice(tail);
message
})
.collect()
}
/// Whether `certificate` verifies `avatar` (an `AvatarData`) for `myts_id`:
/// signed over the `AvatarInfo`, the myTS ID and the timestamp (8 bytes,
/// big-endian).
fn avatar_verifies(certificate: &Certificate, avatar: &[u8], myts_id: &[u8]) -> bool {
let Ok(data) = wire::decode::<api::AvatarData>(avatar) else { return false };
let mut tail = myts_id.to_vec();
tail.extend_from_slice(&data.timestamp.to_be_bytes());
let raw = profile::raw_field(avatar, INFO).unwrap_or_default();
let encoded = wire::encode(&data.info.unwrap_or_default());
messages(raw, encoded, &tail).iter().any(|message| certificate.verifies(message, &data.sign))
}
/// A badge id as a server reads it (16 bytes): only the 36-character form
/// with hyphens (Boost's `uuid` `operator>>`; anything else throws there).
/// `None` for one it would not read, which is never sent.
pub(crate) fn uuid_bytes(uuid: &str) -> Option<[u8; 16]> {
let text = uuid.as_bytes();
let hyphens = [8, 13, 18, 23];
let well_formed = text.len() == 36
&& text
.iter()
.enumerate()
.all(|(at, c)| if hyphens.contains(&at) { *c == b'-' } else { c.is_ascii_hexdigit() });
if !well_formed {
return None;
}
let digit = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
let hex: Vec<u8> = text.iter().copied().filter(|c| *c != b'-').collect();
let mut bytes = [0; 16];
for (byte, pair) in bytes.iter_mut().zip(hex.chunks_exact(2)) {
*byte = (digit(pair[0])? << 4) | digit(pair[1])?;
}
Some(bytes)
}
/// Whether `certificate` verifies `badge` for `myts_id`: signed over the
/// badge's id (16 bytes), its timestamp (8 bytes, big-endian) and the myTS
/// ID.
fn badge_verifies(certificate: &Certificate, badge: &SignedBadge, myts_id: &[u8]) -> bool {
let Ok(signed) = wire::decode::<user::SignedUserBadge>(badge.raw.as_slice()) else {
return false;
};
let Some(uuid) = signed.badge.as_ref().and_then(|b| uuid_bytes(&b.uuid)) else {
return false;
};
let mut message = uuid.to_vec();
message.extend_from_slice(&signed.sign_timestamp.to_be_bytes());
message.extend_from_slice(myts_id);
certificate.verifies(&message, &signed.sign)
}
/// Whether `avatar` (an `AvatarData`) has pictures: a server shows one
/// without any as no avatar.
pub fn avatar_has_pictures(avatar: &[u8]) -> bool {
wire::decode::<api::AvatarData>(avatar)
.is_ok_and(|data| data.info.is_some_and(|info| !info.map.is_empty()))
}
/// Which avatar a TeamSpeak 6 server shows for `myts_id` at `now` (Unix
/// seconds), and with which certificate: of `avatars` (`AvatarData`s as
/// they came), the newest (by its timestamp) that one of `certificates`
/// verifies. Indices into both.
pub fn choose_avatar(
avatars: &[&[u8]],
certificates: &[&[u8]],
myts_id: &[u8],
now: i64,
) -> Option<(usize, usize)> {
choose_avatar_from(&tsproto::ROOT_KEY, avatars, certificates, myts_id, now)
}
/// [`choose_avatar`] with chains from `root` instead of TeamSpeak's (tests).
pub fn choose_avatar_from(
root: &[u8; 32],
avatars: &[&[u8]],
certificates: &[&[u8]],
myts_id: &[u8],
now: i64,
) -> Option<(usize, usize)> {
let certificates: Vec<_> =
certificates.iter().map(|bytes| signing_certificate(bytes, root, now)).collect();
let mut chosen = None;
let mut newest = 0;
for (index, avatar) in avatars.iter().enumerate() {
let Ok(data) = wire::decode::<api::AvatarData>(*avatar) else { continue };
if chosen.is_some() && data.timestamp <= newest {
continue;
}
let verifying = certificates
.iter()
.position(|c| c.as_ref().is_some_and(|c| avatar_verifies(c, avatar, myts_id)));
if let Some(certificate) = verifying {
chosen = Some((index, certificate));
newest = data.timestamp;
}
}
chosen
}
/// Which of `certificates` a TeamSpeak 6 server verifies every one of
/// `badges` with for `myts_id` at `now` (Unix seconds); an index.
pub fn choose_badges_certificate(
badges: &[&SignedBadge],
certificates: &[&[u8]],
myts_id: &[u8],
now: i64,
) -> Option<usize> {
choose_badges_certificate_from(&tsproto::ROOT_KEY, badges, certificates, myts_id, now)
}
/// [`choose_badges_certificate`] with chains from `root` instead of
/// TeamSpeak's (tests).
pub fn choose_badges_certificate_from(
root: &[u8; 32],
badges: &[&SignedBadge],
certificates: &[&[u8]],
myts_id: &[u8],
now: i64,
) -> Option<usize> {
certificates.iter().position(|bytes| {
signing_certificate(bytes, root, now)
.is_some_and(|c| badges.iter().all(|badge| badge_verifies(&c, badge, myts_id)))
})
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::testing::{Chain, NOW};
pub(crate) const ID: [u8; 33] = [4; 33];
const BADGE_A: &str = "a2a2a2a2-0000-4000-8000-000000000001";
const BADGE_B: &str = "B3B3B3B3-0000-4000-8000-0000000000B2";
fn badge(raw: &[u8]) -> SignedBadge {
SignedBadge::parse(raw).unwrap()
}
#[test]
fn the_avatar_goes_with_a_certificate_that_verifies_it() {
let (login, service) = (Chain::signing(1), Chain::signing(2));
let old = login.avatar(&ID, 100);
let new = service.avatar(&ID, 200);
let certificates = [login.certificate.as_slice(), service.certificate.as_slice()];
let choose = |avatars: &[&[u8]], certificates: &[&[u8]], id: &[u8], now| {
choose_avatar_from(&login.root, avatars, certificates, id, now)
};
// The newest that verifies, each with its own certificate.
assert_eq!(choose(&[&old, &new], &certificates, &ID, NOW), Some((1, 1)));
assert_eq!(choose(&[&new, &old], &certificates, &ID, NOW), Some((0, 1)));
assert_eq!(choose(&[&old], &certificates, &ID, NOW), Some((0, 0)));
assert!(avatar_has_pictures(&old));
assert!(!avatar_has_pictures(&wire::encode(&api::AvatarData::default())));
// Without the newer one's certificate: the older one.
assert_eq!(choose(&[&old, &new], &certificates[..1], &ID, NOW), Some((0, 0)));
// Another myTS ID, another time, another root: nothing.
assert_eq!(choose(&[&old, &new], &certificates, &[5; 33], NOW), None);
assert_eq!(choose(&[&old], &certificates, &ID, NOW + 31 * 86_400), None);
assert_eq!(choose(&[&old], &certificates, &ID, NOW - 7200), None);
assert_eq!(choose_avatar(&[&old], &certificates, &ID, NOW), None);
// A field this version does not know, after the signed part: still
// the same avatar.
let mut unknown = old.clone();
unknown.extend_from_slice(&[0x78, 0x01]);
assert_eq!(choose(&[&unknown], &certificates, &ID, NOW), Some((0, 0)));
// Changed after signing.
let mut changed: api::AvatarData = wire::decode(old.as_slice()).unwrap();
changed.timestamp = 101;
assert_eq!(choose(&[&wire::encode(&changed)], &certificates, &ID, NOW), None);
// Only a key that signs for myTS IDs.
let other = Chain::new(1, 5, NOW - 3600, NOW + 3600);
assert_eq!(choose(&[&old], &[&other.certificate], &ID, NOW), None);
assert_eq!(choose(&[b"\xff"], &certificates, &ID, NOW), None);
}
#[test]
fn badges_go_with_a_certificate_that_verifies_all_of_them() {
let (one, two) = (Chain::signing(1), Chain::signing(2));
let a = badge(&one.badge(&ID, BADGE_A, "A"));
let b = badge(&two.badge(&ID, BADGE_B, "B"));
let certificates = [one.certificate.as_slice(), two.certificate.as_slice()];
let choose = |badges: &[&SignedBadge], id: &[u8]| {
choose_badges_certificate_from(&one.root, badges, &certificates, id, NOW)
};
assert_eq!(choose(&[&a], &ID), Some(0));
assert_eq!(choose(&[&b], &ID), Some(1));
assert_eq!(choose(&[&a, &b], &ID), None, "no one certificate verifies both");
assert_eq!(choose(&[&a], &[5; 33]), None);
let both = badge(&two.badge(&ID, BADGE_A, "A"));
assert_eq!(choose(&[&both, &b], &ID), Some(1));
// An id a server would not read is never sent, though the signature
// is over the same 16 bytes.
for odd in ["{a2a2a2a2-0000-4000-8000-000000000001}", "a2a2a2a2000040008000000000000001"] {
let mut signed: user::SignedUserBadge = wire::decode(a.raw()).unwrap();
signed.badge.as_mut().unwrap().uuid = odd.into();
assert_eq!(choose(&[&badge(&wire::encode(&signed))], &ID), None, "{odd}");
}
}
#[test]
fn badge_ids_are_read_as_a_server_reads_them() {
assert_eq!(uuid_bytes(BADGE_A).unwrap()[..4], [0xa2; 4]);
assert_eq!(uuid_bytes(BADGE_B).unwrap()[15], 0xb2);
for bad in [
"",
"a2a2a2a2",
"a2a2a2a2-0000-4000-8000-00000000000g",
"a2a2a2a2+0000-4000-8000-000000000001",
// Without hyphens, braced, or a sign where a digit belongs: the
// server throws on them.
"a2a2a2a2000040008000000000000001",
"{a2a2a2a2-0000-4000-8000-000000000001}",
"a2a2a2a2-0000-4000-8000-0000000000+1",
"+2a2a2a2-0000-4000-8000-000000000001",
"a2a2a2a2-0000-4000-8000-0000000000\u{e9}",
" 2a2a2a2-0000-4000-8000-000000000001",
] {
assert_eq!(uuid_bytes(bad), None, "{bad}");
}
}
#[test]
fn the_badge_list_keeps_each_badge_as_it_came() {
let chain = Chain::signing(1);
let a = chain.badge(&ID, BADGE_A, "A");
let b = chain.badge(&ID, BADGE_B, "B");
let (a_badge, b_badge) = (badge(&a), badge(&b));
let decoded = |raw: &[u8]| wire::decode::<user::SignedUserBadge>(raw).unwrap();
assert_eq!(
badge_list([&b_badge, &a_badge]),
wire::encode(&user::UserBadgesSignedList { badges: vec![decoded(&b), decoded(&a)] })
);
// A field this version does not know stays.
let mut raw = a.clone();
raw.extend_from_slice(&[0x78, 0x01]);
let odd = SignedBadge::parse(&raw).unwrap();
assert_eq!(odd.raw(), raw);
let list = badge_list([&odd]);
assert_eq!(profile::raw_fields(&list, 1).unwrap(), [raw.as_slice()]);
// Long ones get a longer length.
let long = SignedBadge { raw: vec![0; 300], ..odd };
assert_eq!(&badge_list([&long])[..3], [0x0a, 0xac, 0x02]);
assert!(badge_list([]).is_empty());
}
}
+113 -1
View File
@@ -5,6 +5,88 @@ use crate::Error;
use schema_api::SessionToken;
use schema_api::api::{self, user};
/// `LoginSession.user_avatar`, the account's avatar as myTeamSpeak signed
/// it.
pub(crate) const USER_AVATAR: u32 = 11;
/// What voice servers show of the account (TeamSpeak 6): sent to each
/// server once connected (`updatemytsdata`), as the official client does.
/// Public data, as myTeamSpeak signed it; empty without it.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Presentation {
/// The account's certificate (`LoginSession.mytsid_user_cert.cert`).
pub certificate: Vec<u8>,
/// The avatar (`LoginSession.user_avatar`, an `AvatarData`: its
/// pictures' links, a timestamp and myTeamSpeak's signature), the bytes
/// exactly as they came: the signature covers them, and fields this
/// version does not know would be lost by encoding them again.
pub avatar: Vec<u8>,
}
impl Presentation {
/// Whether there is anything to show (a certificate, without which a
/// server takes nothing).
pub fn is_empty(&self) -> bool {
self.certificate.is_empty()
}
}
impl std::fmt::Debug for Presentation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Presentation")
.field("certificate", &self.certificate.len())
.field("avatar", &self.avatar.len())
.finish()
}
}
/// The bytes of the last length-delimited field `number` at the top level
/// of a protobuf message, as they are; `None` without one or for a message
/// that does not parse.
pub(crate) fn raw_field(message: &[u8], number: u32) -> Option<&[u8]> {
raw_fields(message, number)?.pop()
}
/// The bytes of every length-delimited field `number` at the top level of
/// a protobuf message (a repeated field), as they are; `None` for a message
/// that does not parse.
pub(crate) fn raw_fields(message: &[u8], number: u32) -> Option<Vec<&[u8]>> {
fn varint(data: &[u8], at: &mut usize) -> Option<u64> {
let mut value = 0u64;
for shift in (0..64).step_by(7) {
let byte = *data.get(*at)?;
*at += 1;
value |= u64::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
return Some(value);
}
}
None
}
let mut at = 0;
let mut found = Vec::new();
while at < message.len() {
let key = varint(message, &mut at)?;
let skip = match key & 7 {
0 => {
varint(message, &mut at)?;
0
}
1 => 8,
2 => usize::try_from(varint(message, &mut at)?).ok()?,
5 => 4,
// Groups are not used by myTeamSpeak.
_ => return None,
};
let end = at.checked_add(skip).filter(|end| *end <= message.len())?;
if key & 7 == 2 && key >> 3 == u64::from(number) {
found.push(&message[at..end]);
}
at = end;
}
Some(found)
}
/// `ERROR_SESSION_EXPIRED` of the `/user` service.
pub(crate) const SESSION_EXPIRED: i32 = user::ErrorReturnCode::ErrorSessionExpired as i32;
/// Avatars are small pictures; anything larger is not one.
@@ -112,7 +194,7 @@ pub(crate) fn avatar_link(name: &str) -> Result<&str, Error> {
/// A refusal: `success` unset with an error code. (A reply without a return
/// code is taken as it is: the service sets one when it refuses.)
fn check(code: Option<&user::ReturnCode>) -> Result<(), Error> {
pub(crate) fn check(code: Option<&user::ReturnCode>) -> Result<(), Error> {
match code {
Some(code) if !code.success && code.error_code != 0 => Err(Error::Refused(code.error_code)),
_ => Ok(()),
@@ -141,6 +223,36 @@ fn unix_seconds(value: i64) -> i64 {
mod tests {
use super::*;
#[test]
fn the_avatar_is_kept_as_it_came() {
let avatar = api::AvatarData {
info: Some(api::AvatarInfo { map: vec![map(api::AvatarState::Online, "https://a/o")] }),
timestamp: 1_760_000_000,
sign: vec![7; 64],
..Default::default()
};
// A field this version does not know, inside the avatar.
let mut raw = schema_api::wire::encode(&avatar);
raw.extend_from_slice(&[0x78, 0x01]);
let mut message = schema_api::wire::encode(&api::LoginSession {
session: "s".into(),
username: "u".into(),
..Default::default()
});
message.push(((USER_AVATAR << 3) | 2) as u8);
message.push(raw.len() as u8);
message.extend_from_slice(&raw);
message.extend_from_slice(&schema_api::wire::encode(&api::LoginSession {
push_token: "after".into(),
..Default::default()
}));
assert_eq!(raw_field(&message, USER_AVATAR), Some(raw.as_slice()));
assert_eq!(raw_field(&message, 13), None);
// Cut short: nothing rather than a part.
assert_eq!(raw_field(&message[..message.len() - 3], USER_AVATAR), None);
assert!(Presentation::default().is_empty());
}
fn map(state: api::AvatarState, name: &str) -> api::avatar_info::AvatarMap {
api::avatar_info::AvatarMap { state: state as i32, name: name.into() }
}
+130
View File
@@ -0,0 +1,130 @@
//! Certificates and what they sign, from a synthetic root, for tests here
//! and in the crates using this one (feature `testing`): TeamSpeak's root
//! signs nothing a test can make, so tests pass the synthetic root to the
//! checks (`*_from`).
use crate::presentation::uuid_bytes;
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar};
use schema_api::api::{self, tschat, user};
use schema_api::wire;
use sha2::{Digest, Sha512};
/// When the chains of [`Chain::signing`] are valid, Unix seconds.
pub const NOW: i64 = 1_790_000_000;
/// `tsproto::license::TIMESTAMP_OFFSET`.
const OFFSET: i64 = 0x50e2_2700;
/// A synthetic root and a chain from it, and how to sign as its leaf.
pub struct Chain {
pub root: [u8; 32],
pub certificate: Vec<u8>,
secret: Scalar,
}
impl Chain {
/// A leaf of `kind` with key `seed`, valid from `from` to `to` (Unix
/// seconds). Every chain has the same root.
pub fn new(seed: u8, kind: u8, from: i64, to: i64) -> Self {
let root = Scalar::from_bytes_mod_order([0x11; 32]);
let leaf = Scalar::from_bytes_mod_order([seed; 32]);
let mut block = vec![0];
block.extend_from_slice((ED25519_BASEPOINT_TABLE * &leaf).compress().as_bytes());
block.push(kind);
for time in [from, to] {
block.extend_from_slice(&u32::try_from(time - OFFSET).unwrap().to_be_bytes());
}
let mut hash: [u8; 64] = Sha512::digest(&block[1..]).into();
hash[0] &= 248;
hash[31] &= 63;
hash[31] |= 64;
let hash = Scalar::from_bytes_mod_order(hash[..32].try_into().unwrap());
let mut certificate = vec![1];
certificate.extend_from_slice(&block);
Self {
root: (ED25519_BASEPOINT_TABLE * &root).compress().to_bytes(),
certificate,
secret: leaf * hash + root,
}
}
/// A `MYTSID_SIGN` leaf valid at [`NOW`].
pub fn signing(seed: u8) -> Self {
Self::new(seed, 6, NOW - 3600, NOW + 30 * 86_400)
}
pub fn sign(&self, message: &[u8]) -> Vec<u8> {
let public = (ED25519_BASEPOINT_TABLE * &self.secret).compress().to_bytes();
let nonce = Scalar::from_bytes_mod_order_wide(
&Sha512::new()
.chain_update(self.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 * self.secret + nonce).as_bytes());
signature
}
/// An `AvatarData` with one picture, signed for `myts_id` at
/// `timestamp`.
pub fn avatar(&self, myts_id: &[u8], timestamp: u64) -> Vec<u8> {
let info = api::AvatarInfo {
map: vec![api::avatar_info::AvatarMap {
state: api::AvatarState::Online as i32,
name: format!("https://avatars.example.test/{timestamp}.png"),
}],
};
let mut message = wire::encode(&info);
message.extend_from_slice(myts_id);
message.extend_from_slice(&timestamp.to_be_bytes());
wire::encode(&api::AvatarData {
info: Some(info),
timestamp,
sign: self.sign(&message),
..Default::default()
})
}
/// A `SignedUserBadge` for `myts_id`; `uuid` in the 36-character form.
pub fn badge(&self, myts_id: &[u8], uuid: &str, name: &str) -> Vec<u8> {
let mut message = uuid_bytes(uuid).expect("a badge id a server reads").to_vec();
message.extend_from_slice(&7u64.to_be_bytes());
message.extend_from_slice(myts_id);
wire::encode(&user::SignedUserBadge {
badge: Some(user::UserBadge {
uuid: uuid.into(),
name: name.into(),
url: format!("https://badges.example.test/{name}.svg"),
..Default::default()
}),
sign: self.sign(&message),
sign_timestamp: 7,
})
}
/// A User Tag's token (`MatrixIdentifierToken`) for `tags`, signed for
/// `myts_id`.
pub fn user_tag_token(&self, tags: &[&str], myts_id: &[u8]) -> Vec<u8> {
let tags =
tschat::TschatIdentifierTagList { tag: tags.iter().map(|t| t.to_string()).collect() };
let mut message = wire::encode(&tags);
message.extend_from_slice(&1_760_000_000_000u64.to_be_bytes());
message.extend_from_slice(myts_id);
wire::encode(&tschat::MatrixIdentifierToken {
signature: self.sign(&message),
sign_certificate: self.certificate.clone(),
timestamp: 1_760_000_000_000,
tags: Some(tags),
})
}
}
+315
View File
@@ -145,6 +145,26 @@ async fn login_roundtrip_keeps_credentials_in_body_and_redacts_results() {
assert!(!data.skip_session);
}
/// What servers are shown of the account comes with the login: the
/// certificate, and the avatar as it came.
#[tokio::test]
async fn the_login_brings_the_accounts_presentation() {
let avatar = api::AvatarData { timestamp: 42, sign: vec![1; 64], ..Default::default() };
let response = api::LoginSession {
mytsid_user_cert: Some(api::MyTsUserCertificate { cert: vec![9, 8, 7] }),
user_avatar: Some(avatar.clone()),
..success()
};
let (client, _server) = mock(200, "", wire::encode(&response)).await;
let login = client.login("mail", "password", None, "device").await.unwrap();
assert_eq!(login.presentation.certificate, [9, 8, 7]);
assert_eq!(login.presentation.avatar, wire::encode(&avatar));
// Without them: nothing to show.
let (client, _server) = mock(200, "", wire::encode(&success())).await;
let login = client.login("mail", "password", None, "device").await.unwrap();
assert!(login.presentation.is_empty() && login.presentation.avatar.is_empty());
}
#[tokio::test]
async fn login_requires_explicit_success_nonempty_token_and_preserves_status() {
for code in [0, 202, 208, 98765] {
@@ -337,6 +357,76 @@ async fn owner_live_login_validate_logout() {
let login =
client.login(&email, &password, otp.as_deref(), &device).await.expect("live login failed");
let validation = client.validate_session(&login.token).await;
// What servers can be shown without a password, next to what the
// sign-in brought: which certificate is of which kind, valid until
// when, and verifies what. Public data only (certificates, ids, links
// are not secret); never the session.
if let Ok(identity) = &login.identity {
let id = identity.id_bytes();
let now =
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()
as i64;
let own = client.own_avatar(&login.token, id).await;
let badges = client.signed_badges(&login.token).await;
let tag = client.user_tag(&login.token).await;
let tag_token = client.user_tag_token(&login.token).await;
let service = own.as_ref().ok().and_then(Option::as_ref);
// The candidates, in the order the UI tries them: the sign-in's, the
// avatar service's, the myTS ID's (pubSignCert).
let certificates: [&[u8]; 3] = [
&login.presentation.certificate,
service.map_or(&[][..], |o| o.certificate.as_slice()),
identity.public_signature_certificate(),
];
for (name, certificate) in
["sign-in", "avatar service", "pubSignCert"].iter().zip(certificates)
{
// Leaf block type, validity window (Unix seconds) and public key.
let parsed = tsproto::myts::Certificate::parse(certificate, &ROOT_KEY);
println!(
"{name} certificate: {} bytes, {:?}, valid now: {:?}",
certificate.len(),
parsed,
parsed.as_ref().map(|c| (c.signs_myts_data(), c.valid_at(now)))
);
}
println!(
"pubSignCert equals the sign-in's: {}, the avatar service's: {}",
certificates[2] == certificates[0],
certificates[2] == certificates[1]
);
println!(
"avatar service: {:?}, the sign-in's certificate: {:?}",
own.as_ref().map(|o| o.is_some()),
service.map(|o| o.certificate == login.presentation.certificate)
);
let avatars =
[login.presentation.avatar.as_slice(), service.map_or(&[][..], |o| &o.avatar)];
println!(
"avatar (avatar, certificate): {:?}",
choose_avatar(&avatars, &certificates, id, now)
);
println!(
"badges: {:?}",
badges.as_ref().map(|b| b.as_ref().map(|b| (
b.iter().map(|b| b.uuid.as_str()).collect::<Vec<_>>(),
choose_badges_certificate(&b.iter().collect::<Vec<_>>(), &certificates, id, now),
)))
);
println!("tag: {:?}", tag.as_ref().map(|t| t.is_some()));
match (&tag, &tag_token) {
(Ok(Some(tag)), Ok(token)) => {
let decoded = wire::decode::<api::tschat::MatrixIdentifierToken>(token.as_slice());
let parsed = decoded
.as_ref()
.map(|d| tsproto::myts::Certificate::parse(&d.sign_certificate, &ROOT_KEY));
println!("tag token certificate: {parsed:?}");
println!("tag token: {:?}", check_user_tag(token, tag, id, now));
}
(_, Err(error)) => println!("tag token: {error}"),
_ => {}
}
}
let logout = client.logout(&login.token).await;
validation.expect("live validation failed");
logout.expect("live logout failed");
@@ -399,3 +489,228 @@ async fn an_avatar_is_fetched_from_its_own_link() {
// A name that is not a link is never fetched.
assert!(matches!(client.avatar("online.png").await, Err(Error::AvatarUrl)));
}
/// Several requests in turn, each answered with the next body; their heads
/// and bodies come back.
async fn mock_each(
bodies: Vec<Vec<u8>>,
) -> (Client, tokio::task::JoinHandle<Vec<(String, Vec<u8>)>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let client = Client {
transport: transport::Transport::mock(
format!("http://{}", listener.local_addr().unwrap()),
Duration::from_secs(2),
),
};
let task = tokio::spawn(async move {
let mut requests = Vec::new();
for body in bodies {
let (mut stream, _) = listener.accept().await.unwrap();
let mut head = Vec::new();
while !head.ends_with(b"\r\n\r\n") {
let mut byte = [0];
stream.read_exact(&mut byte).await.unwrap();
head.push(byte[0]);
}
let head = String::from_utf8(head).unwrap();
let length: usize = head
.lines()
.find_map(|line| {
line.to_ascii_lowercase().strip_prefix("content-length: ").map(str::to_owned)
})
.unwrap()
.parse()
.unwrap();
let mut request = vec![0; length];
stream.read_exact(&mut request).await.unwrap();
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
let _ = stream.write_all(&body).await;
requests.push((head, request));
}
requests
});
(client, task)
}
const MYTS_ID: [u8; 33] = [4; 33];
fn session_body(method: &str) -> Vec<u8> {
let mut body = vec![method.len() as u8];
body.extend_from_slice(method.as_bytes());
body.extend_from_slice(b"\x0a\x0esession-secret");
body
}
/// The account's own avatar from the avatar service: the request as the
/// official client builds it, the entry for the account's myTS ID with
/// its certificate, as it came.
#[tokio::test]
async fn the_own_avatar_comes_from_the_avatar_service() {
use schema_api::api::user;
let token = SessionToken::new("session-secret").unwrap();
let avatar = |mytsid: &[u8], cert: &[u8]| api::AvatarData {
info: Some(api::AvatarInfo {
map: vec![api::avatar_info::AvatarMap {
state: api::AvatarState::Online as i32,
name: "https://avatars.example.test/o.png".into(),
}],
}),
timestamp: 42,
sign: vec![1; 64],
optional: Some(wire::pack_any(&api::OptionalAvatarDataContactInfo {
mytsid: mytsid.to_vec(),
user_cert: cert.to_vec(),
})),
};
let map =
|avatar: &api::AvatarData| user::request_contacts_avatar_info_response::AvatarInfoMap {
id: None,
info: Some(avatar.clone()),
};
let (other, own) = (avatar(&[5; 33], &[8; 112]), avatar(&MYTS_ID, &[9; 112]));
let response = user::RequestContactsAvatarInfoResponse {
data: vec![map(&other), map(&own)],
error_code: 0,
};
let (client, server) = mock_each(vec![wire::encode(&response)]).await;
let fetched = client.own_avatar(&token, &MYTS_ID).await.unwrap().unwrap();
assert_eq!(fetched.certificate, [9; 112]);
assert_eq!(fetched.avatar, wire::encode(&own), "as it came");
let (head, body) = server.await.unwrap().remove(0);
assert!(head.starts_with("POST /user HTTP/1.1"), "{head}");
let type_url =
b"type.googleapis.com/com.teamspeak.myteamspeak.proto.user.AvatarRequestID.MYTSKey";
assert_eq!(type_url.len(), 0x50);
let mut expected = session_body("requestContactsAvatar");
expected.extend_from_slice(&[0x12, 0x79, 0x0a, 0x77, 0x0a, 0x50]);
expected.extend_from_slice(type_url);
expected.extend_from_slice(&[0x12, 0x23, 0x0a, 0x21]);
expected.extend_from_slice(&MYTS_ID);
assert_eq!(body, expected);
// What the live service answers an unknown session (and an account
// without an avatar): nothing, so nothing learned.
let (client, _server) = mock_each(vec![Vec::new()]).await;
assert_eq!(client.own_avatar(&token, &MYTS_ID).await.unwrap(), None);
// Another account's entry, or one without a certificate: nothing.
for entry in [avatar(&[5; 33], &[9; 112]), avatar(&MYTS_ID, &[]), api::AvatarData::default()] {
let response =
user::RequestContactsAvatarInfoResponse { data: vec![map(&entry)], error_code: 0 };
let (client, _server) = mock_each(vec![wire::encode(&response)]).await;
assert_eq!(client.own_avatar(&token, &MYTS_ID).await.unwrap(), None);
}
let expired = user::RequestContactsAvatarInfoResponse { data: vec![], error_code: 109 };
let (client, _server) = mock_each(vec![wire::encode(&expired)]).await;
assert!(client.own_avatar(&token, &MYTS_ID).await.unwrap_err().is_invalid_session());
}
#[tokio::test]
async fn signed_badges_keep_their_bytes() {
use schema_api::api::user;
let token = SessionToken::new("session-secret").unwrap();
let badge = |uuid: &str, name: &str| user::SignedUserBadge {
badge: Some(user::UserBadge { uuid: uuid.into(), name: name.into(), ..Default::default() }),
sign: vec![3; 64],
sign_timestamp: 9,
};
let mut odd = wire::encode(&badge("b", "B"));
odd.extend_from_slice(&[0x78, 0x01]);
let mut list = wire::encode(&user::UserBadgesSignedList { badges: vec![badge("a", "A")] });
list.push(0x0a);
list.push(odd.len() as u8);
list.extend_from_slice(&odd);
assert!((0x80..0x4000).contains(&list.len()));
let mut response = vec![0x0a, 0x80 | (list.len() as u8 & 0x7f), (list.len() >> 7) as u8];
response.extend_from_slice(&list);
let (client, server) = mock_each(vec![response]).await;
let badges = client.signed_badges(&token).await.unwrap().unwrap();
assert_eq!(
badges.iter().map(|b| (b.uuid.as_str(), b.name.as_str())).collect::<Vec<_>>(),
[("a", "A"), ("b", "B")]
);
assert_eq!(badges[1].raw(), odd);
assert_eq!(badge_list(&badges), list, "the list as it came");
let (head, body) = server.await.unwrap().remove(0);
assert!(head.starts_with("POST /user HTTP/1.1"), "{head}");
assert_eq!(body, session_body("getSignedBadges"));
assert_eq!(&body[..16], b"\x0fgetSignedBadges");
// No list: nothing learned. An empty one: no badges.
let (client, _server) = mock_each(vec![Vec::new()]).await;
assert_eq!(client.signed_badges(&token).await.unwrap(), None);
let (client, _server) = mock_each(vec![vec![0x0a, 0x00]]).await;
assert_eq!(client.signed_badges(&token).await.unwrap(), Some(Vec::new()));
// What the live service answers an unknown session.
let (client, _server) = mock_each(vec![vec![0x10, 0x6d]]).await;
assert!(client.signed_badges(&token).await.unwrap_err().is_invalid_session());
}
/// The User Tag comes from the chat service with the session alone.
#[tokio::test]
async fn the_user_tag_and_its_token_come_from_the_chat_service() {
use schema_api::api::{tschat, user};
let token = SessionToken::new("session-secret").unwrap();
let list = tschat::TschatIdentifierList {
ts_chat_identifier_mapping: vec![tschat::TschatIdentifierMapping {
ts_chat_identifier: "alex@myteamspeak.com".into(),
matrix_id: "@x:tschat".into(),
primary: true,
}],
error_handling: Some(tschat::ErrorHandling { return_code: 1, ..Default::default() }),
};
let (client, server) = mock_each(vec![wire::encode(&list)]).await;
assert_eq!(client.user_tag(&token).await.unwrap().as_deref(), Some("alex@myteamspeak.com"));
let (head, body) = server.await.unwrap().remove(0);
assert!(head.starts_with("POST /tschat HTTP/1.1"), "{head}");
assert_eq!(body, session_body("getActiveIdentifierList"));
assert_eq!(body[0], 0x17);
// No primary one: the account data's active identifiers.
let data = user::UserAccountData {
ts_chat_identifier_list_active: Some(list.clone()),
..Default::default()
};
let none = tschat::TschatIdentifierList::default();
let (client, server) = mock_each(vec![wire::encode(&none), wire::encode(&data)]).await;
assert_eq!(client.user_tag(&token).await.unwrap().as_deref(), Some("alex@myteamspeak.com"));
let requests = server.await.unwrap();
assert!(requests[1].0.starts_with("POST /user HTTP/1.1"));
assert!(requests[1].1.starts_with(b"\x0egetAccountData"));
let request: user::AccountDataRequest = wire::decode(&requests[1].1[15..]).unwrap();
assert_eq!(request.selector, [user::UserAccountDataSelector::TsChat as i32]);
// An expired session is the account service's expired session.
let expired = tschat::TschatIdentifierList {
error_handling: Some(tschat::ErrorHandling { return_code: 5, ..Default::default() }),
..Default::default()
};
let (client, _server) = mock_each(vec![wire::encode(&expired)]).await;
assert!(client.user_tag(&token).await.unwrap_err().is_invalid_session());
// The token, exactly as it came.
let mut raw = wire::encode(&tschat::MatrixIdentifierToken {
signature: vec![1; 64],
sign_certificate: vec![2; 112],
timestamp: 5,
tags: Some(tschat::TschatIdentifierTagList { tag: vec!["alex@myteamspeak.com".into()] }),
});
raw.extend_from_slice(&[0x78, 0x01]);
assert!((0x80..0x4000).contains(&raw.len()));
let mut answer = vec![0x0a, 0x80 | (raw.len() as u8 & 0x7f), (raw.len() >> 7) as u8];
answer.extend_from_slice(&raw);
answer.extend_from_slice(&wire::encode(&tschat::SignedAllowedIdentifier {
token: None,
error: Some(tschat::ErrorHandling { return_code: 1, ..Default::default() }),
}));
let (client, server) = mock_each(vec![answer]).await;
assert_eq!(client.user_tag_token(&token).await.unwrap(), raw);
let (head, body) = server.await.unwrap().remove(0);
assert!(head.starts_with("POST /tschat HTTP/1.1"), "{head}");
assert_eq!(body, session_body("requestSignedAllowedIdentifierList"));
assert_eq!(body[0], 0x22);
// The live answer to an unknown session: SESSION_EXPIRED (5).
let mut live = vec![0x12, 0x44, 0x08, 0x05, 0x12, 0x40];
live.extend_from_slice(b"Could not resolve session '00000000-0000-0000-0000-000000000000'");
assert_eq!(live.len(), 6 + 0x40);
let (client, _server) = mock_each(vec![live]).await;
assert!(client.user_tag_token(&token).await.unwrap_err().is_invalid_session());
}
+208
View File
@@ -0,0 +1,208 @@
//! The account's User Tag (TeamSpeak 6): its primary TeamSpeak chat
//! identifier ("name@myteamspeak.com"), and the token that proves it is
//! the account's, from the chat service (`/tschat`). Viewers check the
//! token against the myTS ID the account shows the server; nothing else
//! of the account is needed (no chat sign-in).
use crate::{Error, profile};
use schema_api::api::{tschat, user};
use schema_api::{SessionToken, wire};
use tsproto::myts::Certificate;
/// `ChatRequestReturnCode`: SUCCESS and SESSION_EXPIRED.
const SUCCESS: i32 = 1;
const SESSION_EXPIRED: i32 = 5;
/// `SignedAllowedIdentifier.token`, `MatrixIdentifierToken.tags`.
const TOKEN: u32 = 1;
const TAGS: u32 = 4;
/// Why a User Tag's token is not shown: viewers would not accept it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum UserTagError {
#[error("the User Tag's token does not parse")]
Format,
#[error("the User Tag's certificate is not valid")]
Certificate,
#[error("the User Tag's token is not signed for the account's myTS ID")]
Signature,
#[error("the User Tag's token does not name the tag")]
Tag,
}
/// The chat service's requests carry the session only (no chat account).
pub(crate) fn request(token: &SessionToken) -> tschat::AuthenticatedUser {
tschat::AuthenticatedUser { session: token.as_str().into(), ..Default::default() }
}
/// A chat service answer: SUCCESS, or why not. An expired session is the
/// same refusal as the account service's.
fn check(error: Option<&tschat::ErrorHandling>, required: bool) -> Result<(), Error> {
match error.map(|e| e.return_code) {
Some(SUCCESS) => Ok(()),
None if !required => Ok(()),
Some(SESSION_EXPIRED) => Err(Error::Refused(profile::SESSION_EXPIRED)),
code => Err(Error::ChatRefused(code.unwrap_or_default())),
}
}
/// The primary identifier of `getActiveIdentifierList`'s answer; `None`:
/// the account has none.
pub(crate) fn primary(list: tschat::TschatIdentifierList) -> Result<Option<String>, Error> {
check(list.error_handling.as_ref(), false)?;
Ok(primary_of(&list))
}
fn primary_of(list: &tschat::TschatIdentifierList) -> Option<String> {
list.ts_chat_identifier_mapping
.iter()
.find(|m| m.primary && !m.ts_chat_identifier.is_empty())
.map(|m| m.ts_chat_identifier.clone())
}
/// The account data's active identifiers (`getAccountData`), for when the
/// chat service names no primary one.
pub(crate) fn account_request(token: &SessionToken) -> user::AccountDataRequest {
user::AccountDataRequest {
session: token.as_str().into(),
selector: vec![user::UserAccountDataSelector::TsChat as i32],
..Default::default()
}
}
pub(crate) fn account_primary(data: &user::UserAccountData) -> Option<String> {
data.ts_chat_identifier_list_active.as_ref().and_then(primary_of)
}
/// The token of `requestSignedAllowedIdentifierList`'s answer, exactly as
/// it came: viewers check its signature over parts of it.
pub(crate) fn token(bytes: &[u8]) -> Result<Vec<u8>, Error> {
let answer: tschat::SignedAllowedIdentifier = wire::decode(bytes)?;
check(answer.error.as_ref(), true)?;
match profile::raw_field(bytes, TOKEN) {
Some(token) if !token.is_empty() => Ok(token.to_vec()),
_ => Err(Error::NoToken),
}
}
/// Check a User Tag's token as viewers check it (the official client's
/// `verifyIdentifierToken`): its certificate's chain and leaf valid at
/// `at` (Unix seconds), its signature over the tags, its timestamp (8
/// bytes, big-endian) and the myTS ID, and the tag among the tags. Until
/// when its certificate is valid, Unix seconds.
pub fn check_user_tag(
token: &[u8],
tag: &str,
myts_id: &[u8],
at: i64,
) -> Result<i64, UserTagError> {
check_user_tag_from(&tsproto::ROOT_KEY, token, tag, myts_id, at)
}
/// [`check_user_tag`] with chains from `root` instead of TeamSpeak's
/// (tests).
pub fn check_user_tag_from(
root: &[u8; 32],
token: &[u8],
tag: &str,
myts_id: &[u8],
at: i64,
) -> Result<i64, UserTagError> {
let decoded: tschat::MatrixIdentifierToken =
wire::decode(token).map_err(|_| UserTagError::Format)?;
let certificate = Certificate::parse(&decoded.sign_certificate, root)
.ok()
.filter(|c| c.valid_at(at))
.ok_or(UserTagError::Certificate)?;
let tags = decoded.tags.unwrap_or_default();
let raw = profile::raw_field(token, TAGS).unwrap_or_default();
let mut tail = decoded.timestamp.to_be_bytes().to_vec();
tail.extend_from_slice(myts_id);
let mut parts = vec![wire::encode(&tags)];
if parts[0] != raw {
parts.push(raw.to_vec());
}
let signed = parts.into_iter().any(|mut message| {
message.extend_from_slice(&tail);
certificate.verifies(&message, &decoded.signature)
});
if !signed {
return Err(UserTagError::Signature);
}
if !tags.tag.iter().any(|t| t == tag) {
return Err(UserTagError::Tag);
}
Ok(certificate.not_valid_after())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presentation::tests::ID;
use crate::testing::{Chain, NOW};
#[test]
fn the_token_is_checked_as_viewers_check_it() {
let chain = Chain::new(3, 4, NOW - 3600, NOW + 86_400);
let tag = "alex@myteamspeak.com";
let good = chain.user_tag_token(&["alex@tschat-1.teamspeak.com", tag], &ID);
let check = |token: &[u8], tag: &str, id: &[u8], at| {
check_user_tag_from(&chain.root, token, tag, id, at)
};
// Any leaf: viewers do not ask which kind.
assert_eq!(check(&good, tag, &ID, NOW), Ok(NOW + 86_400));
assert_eq!(check(&good, "alex@tschat-1.teamspeak.com", &ID, NOW), Ok(NOW + 86_400));
assert_eq!(check(&good, "bob@myteamspeak.com", &ID, NOW), Err(UserTagError::Tag));
assert_eq!(check(&good, tag, &[5; 33], NOW), Err(UserTagError::Signature));
assert_eq!(check(&good, tag, &ID, NOW + 86_400), Err(UserTagError::Certificate));
assert_eq!(check(&good, tag, &ID, NOW - 7200), Err(UserTagError::Certificate));
// TeamSpeak's root: another key.
assert_eq!(check_user_tag(&good, tag, &ID, NOW), Err(UserTagError::Signature));
assert_eq!(check(b"\xff", tag, &ID, NOW), Err(UserTagError::Format));
let mut decoded: tschat::MatrixIdentifierToken = wire::decode(good.as_slice()).unwrap();
decoded.timestamp += 1;
assert_eq!(check(&wire::encode(&decoded), tag, &ID, NOW), Err(UserTagError::Signature));
}
#[test]
fn answers_are_required_to_succeed() {
let ok = |code| Some(tschat::ErrorHandling { return_code: code, message: "m".into() });
let list = |error| tschat::TschatIdentifierList {
ts_chat_identifier_mapping: vec![
tschat::TschatIdentifierMapping {
ts_chat_identifier: "old@tschat-1.teamspeak.com".into(),
..Default::default()
},
tschat::TschatIdentifierMapping {
ts_chat_identifier: "alex@myteamspeak.com".into(),
primary: true,
..Default::default()
},
],
error_handling: error,
};
assert_eq!(primary(list(ok(1))).unwrap().as_deref(), Some("alex@myteamspeak.com"));
assert_eq!(primary(list(None)).unwrap().as_deref(), Some("alex@myteamspeak.com"));
assert!(primary(list(ok(5))).unwrap_err().is_invalid_session());
assert!(matches!(primary(list(ok(3))), Err(Error::ChatRefused(3))));
assert_eq!(primary(tschat::TschatIdentifierList::default()).unwrap(), None);
// The token's answer must say SUCCESS.
let answer = |error| {
wire::encode(&tschat::SignedAllowedIdentifier {
token: Some(tschat::MatrixIdentifierToken {
signature: vec![1; 64],
..Default::default()
}),
error,
})
};
assert!(super::token(&answer(ok(1))).is_ok());
assert!(matches!(super::token(&answer(None)), Err(Error::ChatRefused(0))));
assert!(matches!(super::token(&answer(ok(4))), Err(Error::ChatRefused(4))));
// What the live service answers an unknown session.
let mut live = vec![0x12, 0x44, 0x08, 0x05, 0x12, 0x40];
live.extend_from_slice(&[b'x'; 0x40]);
assert!(super::token(&live).unwrap_err().is_invalid_session());
let none = wire::encode(&tschat::SignedAllowedIdentifier { token: None, error: ok(1) });
assert!(matches!(super::token(&none), Err(Error::NoToken)));
}
}
+1
View File
@@ -89,6 +89,7 @@ pub fn client_from_row(row: &Row) -> Option<ClientInfo> {
// What the row carries (`notifycliententerview` all of it,
// `clientlist -voice -groups -icon` some).
avatar: row.get("client_flag_avatar").filter(|a| !a.is_empty()).map(str::to_string),
myts_avatar: row.get("client_myteamspeak_avatar").and_then(voelin_model::myts_avatar_url),
description: row.get("client_description").filter(|d| !d.is_empty()).map(str::to_string),
talk_power: row.parse("client_talk_power").unwrap_or(0),
talker: row.flag("client_is_talker").unwrap_or(false),
+117 -29
View File
@@ -1,5 +1,6 @@
//! Keep a server's presence up to date from one query session.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
use std::time::Duration;
@@ -7,7 +8,7 @@ use tokio::sync::{broadcast, watch};
use tokio::time::{Instant, sleep, sleep_until};
use tracing::{debug, info, warn};
use voelin_model::{ChatMessage, Presence, PresenceDelta, PresenceSnapshot};
use voelin_query::{Command, Connect, Notification, QueryClient};
use voelin_query::{Command, Connect, Notification, QueryClient, attempt_worth_a_warning};
use crate::convert::{
channel_from_row, client_from_row, delta_from_notification, is_text_message, update_channel,
@@ -15,24 +16,18 @@ use crate::convert::{
#[derive(Clone, Debug)]
pub struct ObserverConfig {
/// Reconnects wait [`Connect::retry_delay`].
pub connect: Connect,
/// Full resync interval. Query sessions receive no `notifyclientupdated`,
/// so mute/away changes are only noticed by re-reading the client list.
pub poll_interval: Duration,
/// Also deliver server chat (`event=textserver`).
pub server_chat: bool,
/// Wait between reconnect attempts.
pub reconnect_delay: Duration,
}
impl ObserverConfig {
pub fn new(connect: Connect) -> Self {
Self {
connect,
poll_interval: Duration::from_secs(10),
server_chat: true,
reconnect_delay: Duration::from_secs(5),
}
Self { connect, poll_interval: Duration::from_secs(10), server_chat: true }
}
}
@@ -50,6 +45,7 @@ pub enum ObserverEvent {
pub struct Observer {
presence: Arc<RwLock<Presence>>,
events: broadcast::Sender<ObserverEvent>,
connected: Arc<AtomicBool>,
_stop: watch::Sender<()>,
}
@@ -58,8 +54,19 @@ impl Observer {
let presence = Arc::new(RwLock::new(Presence::default()));
let (events, _) = broadcast::channel(1024);
let (stop, stopped) = watch::channel(());
tokio::spawn(run(config, presence.clone(), events.clone(), stopped));
Self { presence, events, _stop: stop }
let connected = Arc::new(AtomicBool::new(false));
let state = State {
presence: presence.clone(),
events: events.clone(),
connected: connected.clone(),
};
tokio::spawn(run(config, state, stopped));
Self { presence, events, connected, _stop: stop }
}
/// Connected and in sync with the server.
pub fn is_connected(&self) -> bool {
self.connected.load(Ordering::Relaxed)
}
/// Receive events. Call [`Observer::snapshot`] after subscribing to get
@@ -77,25 +84,48 @@ impl Observer {
}
}
async fn run(
config: ObserverConfig,
/// What the observer task shares with its handle.
struct State {
presence: Arc<RwLock<Presence>>,
events: broadcast::Sender<ObserverEvent>,
mut stopped: watch::Receiver<()>,
) {
connected: Arc<AtomicBool>,
}
async fn run(config: ObserverConfig, state: State, mut stopped: watch::Receiver<()>) {
let mut connect = config.connect.clone();
connect.line.label = "observer".into();
// Attempts since the last connection that worked.
let mut attempt = 0u32;
loop {
attempt += 1;
let started = Instant::now();
let result = tokio::select! {
r = session(&config, &presence, &events) => r,
r = session(&config, &connect, &state, attempt, started) => r,
_ = stopped.changed() => return,
};
let reason = match result {
Ok(()) => "connection closed".to_string(),
Err(e) => e.to_string(),
};
warn!(%reason, addr = %config.connect.addr, "observer disconnected");
let _ = events.send(ObserverEvent::Disconnected(reason));
let lost = state.connected.swap(false, Ordering::Relaxed);
if lost {
attempt = 0;
}
// Longer after each failure, or as long as the server asked.
let retry_in = connect.retry_delay(attempt.max(1));
let retry_in_s = retry_in.as_secs_f32();
let elapsed_ms = started.elapsed().as_millis() as u64;
if lost {
let connected_for_s = started.elapsed().as_secs();
warn!(%reason, addr = %connect.addr, connected_for_s, retry_in_s, "observer disconnected");
} else if attempt_worth_a_warning(attempt) {
warn!(%reason, addr = %connect.addr, attempt, elapsed_ms, retry_in_s, "observer could not connect");
} else {
debug!(%reason, addr = %connect.addr, attempt, elapsed_ms, retry_in_s, "observer could not connect");
}
let _ = state.events.send(ObserverEvent::Disconnected(reason));
tokio::select! {
_ = sleep(config.reconnect_delay) => {}
_ = sleep(retry_in) => {}
_ = stopped.changed() => return,
}
}
@@ -145,10 +175,13 @@ fn now_ms() -> i64 {
async fn session(
config: &ObserverConfig,
presence: &RwLock<Presence>,
events: &broadcast::Sender<ObserverEvent>,
connect: &Connect,
state: &State,
attempt: u32,
started: Instant,
) -> voelin_query::Result<()> {
let (client, mut notifications) = QueryClient::connect(&config.connect).await?;
let (presence, events) = (&*state.presence, &state.events);
let (client, mut notifications) = QueryClient::connect(connect).await?;
if notifications.is_some() {
for event in ["server", "channel"] {
let mut cmd = Command::new("servernotifyregister").arg("event", event);
@@ -161,16 +194,19 @@ async fn session(
client.send(&Command::new("servernotifyregister").arg("event", "textserver")).await?;
}
}
let state = load(&client).await?;
let loaded = load(&client).await?;
info!(
server = %state.server_name,
channels = state.channels.len(),
clients = state.clients.len(),
server = %loaded.server_name,
channels = loaded.channels.len(),
clients = loaded.clients.len(),
events = notifications.is_some(),
attempt,
elapsed_ms = started.elapsed().as_millis() as u64,
"observer connected"
);
*presence.write().unwrap() = state.clone();
let _ = events.send(ObserverEvent::Snapshot(state.snapshot()));
*presence.write().unwrap() = loaded.clone();
state.connected.store(true, Ordering::Relaxed);
let _ = events.send(ObserverEvent::Snapshot(loaded.snapshot()));
let mut next_poll = Instant::now() + config.poll_interval;
loop {
@@ -191,7 +227,8 @@ async fn session(
Some(n) => handle_notification(&n, presence, events),
None => {
// Resync and publish only what changed.
let fresh = load(&client).await?;
let listed = load(&client).await?;
let fresh = keep_unlisted(&presence.read().unwrap(), listed);
let deltas = presence.read().unwrap().diff(&fresh);
if !deltas.is_empty() {
debug!(changes = deltas.len(), "observer resync");
@@ -206,6 +243,24 @@ async fn session(
}
}
/// What `clientlist` does not tell (the avatars, which come with
/// `notifycliententerview` and `notifyclientupdated`), kept from what was
/// known of the same client: a resync must not take them away.
fn keep_unlisted(old: &Presence, mut fresh: Presence) -> Presence {
for (id, client) in &mut fresh.clients {
let Some(known) = old.clients.get(id).filter(|known| known.uid == client.uid) else {
continue;
};
if client.avatar.is_none() {
client.avatar.clone_from(&known.avatar);
}
if client.myts_avatar.is_none() {
client.myts_avatar.clone_from(&known.myts_avatar);
}
}
fresh
}
fn handle_notification(
n: &Notification,
presence: &RwLock<Presence>,
@@ -240,3 +295,36 @@ fn handle_notification(
let _ = events.send(ObserverEvent::Delta(d));
}
}
#[cfg(test)]
mod resync_tests {
use super::*;
use voelin_model::ClientInfo;
#[test]
fn a_resync_keeps_the_avatars_the_list_does_not_tell() {
let client = |uid: &str, myts: Option<&str>| ClientInfo {
id: 5,
uid: Some(uid.into()),
nickname: "a".into(),
avatar: myts.map(|_| "0123456789abcdef0123456789abcdef".into()),
myts_avatar: myts.map(Into::into),
..Default::default()
};
let mut old = Presence::default();
old.clients.insert(5, client("u=", Some("https://a.example.test/on.png")));
let mut listed = Presence::default();
listed.clients.insert(5, client("u=", None));
let fresh = keep_unlisted(&old, listed.clone());
assert_eq!(fresh.clients[&5], old.clients[&5]);
assert!(old.diff(&fresh).is_empty());
// Another client in the same slot starts without them.
let mut other = Presence::default();
other.clients.insert(5, client("v=", None));
let fresh = keep_unlisted(&old, other);
assert_eq!(
(fresh.clients[&5].avatar.clone(), fresh.clients[&5].myts_avatar.clone()),
(None, None)
);
}
}
+101 -17
View File
@@ -7,6 +7,8 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use tokio::sync::{Mutex, broadcast, mpsc};
use tokio::task::JoinHandle;
@@ -53,6 +55,7 @@ pub enum RelayEvent {
struct Session {
client: QueryClient,
opened: Instant,
/// The relay's own nickname, taken back after each post.
nickname: String,
/// One post at a time: each borrows the author's nickname.
@@ -71,13 +74,29 @@ impl Drop for Session {
pub struct RelayPool {
config: Arc<RelayConfig>,
sessions: Arc<Mutex<HashMap<ChannelId, Session>>>,
/// Held while a channel's relay opens or closes, so opening one channel
/// (a login and a few commands) holds up nobody in other channels.
gates: Arc<std::sync::Mutex<HashMap<ChannelId, Arc<Mutex<()>>>>>,
/// Set by [`RelayPool::close_all`]: the pool opens no more relays.
closed: Arc<AtomicBool>,
events: broadcast::Sender<RelayEvent>,
}
impl RelayPool {
pub fn new(config: RelayConfig) -> Self {
let (events, _) = broadcast::channel(1024);
Self { config: Arc::new(config), sessions: Default::default(), events }
Self {
config: Arc::new(config),
sessions: Default::default(),
gates: Default::default(),
closed: Default::default(),
events,
}
}
fn gate(&self, channel: ChannelId) -> Arc<Mutex<()>> {
let mut gates = self.gates.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
gates.entry(channel).or_default().clone()
}
pub fn subscribe(&self) -> broadcast::Receiver<RelayEvent> {
@@ -89,13 +108,38 @@ impl RelayPool {
self.sessions.lock().await.keys().copied().collect()
}
/// [`RelayPool::close_all`] was called: opening fails with
/// [`voelin_query::Error::Closed`].
pub fn is_closed(&self) -> bool {
self.closed.load(Ordering::Relaxed)
}
/// Start relaying a channel (no-op if already open).
pub async fn open(&self, channel: ChannelId) -> voelin_query::Result<()> {
let mut sessions = self.sessions.lock().await;
let gate = self.gate(channel);
let _opening = gate.lock().await;
if self.is_closed() {
return Err(voelin_query::Error::Closed);
}
let sessions = self.sessions.lock().await;
if sessions.get(&channel).is_some_and(|s| !s.task.is_finished()) {
return Ok(());
}
let (client, notifications) = QueryClient::connect(&self.config.connect).await?;
drop(sessions);
let started = Instant::now();
let session = self.connect(channel).await.inspect_err(|error| {
let elapsed_ms = started.elapsed().as_millis() as u64;
warn!(channel, elapsed_ms, %error, "relay could not be opened");
})?;
self.sessions.lock().await.insert(channel, session);
Ok(())
}
async fn connect(&self, channel: ChannelId) -> voelin_query::Result<Session> {
let started = Instant::now();
let mut connect = self.config.connect.clone();
connect.line.label = format!("relay {channel}");
let (client, notifications) = QueryClient::connect(&connect).await?;
let Some(notifications) = notifications else {
return Err(voelin_query::Error::Unsupported("relays need a transport with events"));
};
@@ -110,28 +154,46 @@ impl RelayPool {
}
}
client.send(&Command::new("servernotifyregister").arg("event", "textchannel")).await?;
info!(channel, own_id, "relay opened");
let elapsed_ms = started.elapsed().as_millis() as u64;
info!(channel, own_id, elapsed_ms, "relay opened");
let task = tokio::spawn(forward(channel, own_id, notifications, self.events.clone()));
sessions.insert(channel, Session { client, nickname, posting: Default::default(), task });
Ok(())
Ok(Session { client, opened: Instant::now(), nickname, posting: Default::default(), task })
}
/// Stop relaying a channel.
pub async fn close(&self, channel: ChannelId) {
let session = self.sessions.lock().await.remove(&channel);
if let Some(session) = session {
session.client.quit().await;
info!(channel, "relay closed");
}
self.close_one(channel).await;
}
/// Stop all relays.
pub async fn close_all(&self) {
let sessions: Vec<_> = self.sessions.lock().await.drain().collect();
for (channel, session) in sessions {
session.client.quit().await;
info!(channel, "relay closed");
/// Stop relaying a channel; whether it was relayed.
async fn close_one(&self, channel: ChannelId) -> bool {
// After an open in progress, which would otherwise come back with it.
let gate = self.gate(channel);
let _closing = gate.lock().await;
let Some(session) = self.sessions.lock().await.remove(&channel) else { return false };
// Not a lost connection: no `Closed` event for it.
session.task.abort();
session.client.quit().await;
info!(channel, open_for_s = session.opened.elapsed().as_secs(), "relay closed");
true
}
/// Stop all relays, after any opens in progress, and open no more.
/// Returns the channels that were relayed.
pub async fn close_all(&self) -> Vec<ChannelId> {
self.closed.store(true, Ordering::Relaxed);
// Every channel that has a relay or is opening one has a gate.
let channels: Vec<ChannelId> = {
let gates = self.gates.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
gates.keys().copied().collect()
};
let mut closed = Vec::new();
for channel in channels {
if self.close_one(channel).await {
closed.push(channel);
}
}
closed
}
/// Post `text` in `channel` as `nick` wrote it ([`post_as`]), opening a
@@ -254,6 +316,7 @@ async fn forward(
mut notifications: mpsc::UnboundedReceiver<Notification>,
events: broadcast::Sender<RelayEvent>,
) {
let opened = Instant::now();
while let Some(n) = notifications.recv().await {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -269,6 +332,8 @@ async fn forward(
debug!(channel, author = %msg.author_name, "relayed message");
let _ = events.send(RelayEvent::Message(msg));
}
// Closing a relay stops this task before it quits, so this is a loss.
warn!(channel, open_for_s = opened.elapsed().as_secs(), "relay connection lost");
let _ = events.send(RelayEvent::Closed { channel, reason: "connection closed".into() });
}
@@ -276,6 +341,25 @@ async fn forward(
mod tests {
use super::*;
#[tokio::test]
async fn a_closed_pool_opens_no_relays() {
let connect = Connect {
transport: voelin_query::Transport::Raw,
addr: "127.0.0.1:9".into(),
user: "serveradmin".into(),
secret: None,
server_port: None,
server_id: None,
line: Default::default(),
};
let pool = RelayPool::new(RelayConfig::new(connect));
assert!(!pool.is_closed());
assert!(pool.close_all().await.is_empty());
assert!(pool.is_closed());
// Without trying to connect.
assert!(matches!(pool.open(1).await, Err(voelin_query::Error::Closed)));
}
#[test]
fn posts_go_out_under_the_authors_name_then_numbered_variants() {
assert_eq!(author_nicknames(" Alice "), ["Alice", "Alice1", "Alice2", "Alice3"]);
+7 -4
View File
@@ -10,8 +10,8 @@ publish.workspace = true
[features]
default = ["portal", "x11"]
# Wayland global shortcuts and the file chooser through xdg-desktop-portal
# (Linux).
# Wayland global shortcuts, the file chooser and the desktop's proxy settings
# through xdg-desktop-portal (Linux).
portal = ["dep:ashpd", "dep:futures-util"]
# X11 global hotkeys through XInput2 raw events (Linux).
x11 = ["dep:x11rb"]
@@ -20,11 +20,11 @@ x11 = ["dep:x11rb"]
dirs = "6"
serde = { version = "1.0.228", features = ["derive"] }
thiserror = "2"
tokio = { version = "1", features = ["rt", "sync"] }
tokio = { version = "1", features = ["rt", "sync", "time"] }
tracing = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser"], optional = true }
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
futures-util = { version = "0.3", optional = true }
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
x11rb = { version = "0.13", features = ["xinput"], optional = true }
@@ -45,6 +45,9 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies]
x11rb = { version = "0.13", features = ["xinput", "xtest"] }
# A stand-in desktop portal on a private session bus (tests/proxy.rs); the
# zbus ashpd uses.
zbus = { version = "5", default-features = false, features = ["tokio"] }
[lints]
workspace = true
+3
View File
@@ -9,6 +9,8 @@
//! - [`crash`]: opt-in local crash reports (panic hook)
//! - [`logs`]: the log file, with the previous runs' kept
//! - [`notices`]: third-party notices for the About page
//! - [`proxy`]: the proxy the desktop's network settings name for an address
//! (xdg-desktop-portal)
pub mod crash;
pub mod files;
@@ -17,6 +19,7 @@ pub mod logs;
pub mod notices;
pub mod notify;
pub mod paths;
pub mod proxy;
pub use hotkey::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager, Key, Modifiers};
pub use notify::{Notification, notify};
+359
View File
@@ -0,0 +1,359 @@
//! The proxy the desktop's network settings name for an address.
//!
//! Linux asks xdg-desktop-portal's ProxyResolver (feature `portal`), which
//! answers from GNOME's or KDE's settings (a PAC script too), as browsers
//! follow them. It is given a second; answers are kept a minute per
//! scheme, host and port, no answer too (no portal, too slow, an error), so
//! a desktop without the portal costs one try a minute. An answer that
//! comes late (a portal the first call starts) replaces the "none" kept
//! meanwhile. Other platforms answer none: there the HTTP client reads the
//! system's settings itself.
/// How long the desktop may take to answer.
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
/// How long an answer is kept.
#[cfg(any(test, all(unix, not(target_os = "macos"), feature = "portal")))]
const KEEP: std::time::Duration = std::time::Duration::from_secs(60);
/// The proxy for `url` as an HTTP client takes it (`http://host:port`,
/// `socks5h://host:port`, with the user and password the settings have),
/// or `None`: none (`direct://`), or no answer. Call it within a Tokio
/// runtime.
pub async fn proxy_for(url: &str) -> Option<String> {
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
return portal::proxy_for(url).await;
#[cfg(not(all(unix, not(target_os = "macos"), feature = "portal")))]
{
let _ = url;
None
}
}
/// The proxy to use of a resolver's answer (GLib's form, in the order to
/// try): the first an HTTP client can use, `None` when that is
/// `direct://`. SOCKS names the host to the proxy (`socks5h`,
/// `socks4a`), as browsers do: the proxy resolves it.
pub fn usable_proxy<S: AsRef<str>>(answer: &[S]) -> Option<String> {
for uri in answer {
let uri = uri.as_ref().trim();
let Some((scheme, rest)) = uri.split_once("://") else { continue };
let scheme = match scheme.to_ascii_lowercase().as_str() {
"direct" => return None,
"http" => "http",
"https" => "https",
"socks" | "socks5" | "socks5h" => "socks5h",
"socks4" | "socks4a" => "socks4a",
// rtsp, ftp, …: not for HTTP.
_ => continue,
};
let rest = rest.trim_end_matches('/');
if !rest.is_empty() {
return Some(format!("{scheme}://{rest}"));
}
}
None
}
/// A resolver's answer for the log: without the user and password GLib
/// puts in a proxy's address (`http://user:password@host:port`).
#[cfg(any(test, all(unix, not(target_os = "macos"), feature = "portal")))]
fn for_log<S: AsRef<str>>(answer: &[S]) -> Vec<String> {
let without_userinfo = |uri: &str| match uri.split_once("://") {
Some((scheme, rest)) => {
format!("{scheme}://{}", rest.rsplit_once('@').map_or(rest, |(_, host)| host))
}
None => uri.rsplit_once('@').map_or(uri, |(_, host)| host).to_owned(),
};
answer.iter().map(|uri| without_userinfo(uri.as_ref())).collect()
}
/// What answers are kept by: `scheme://host:port` of `url`, lowercase, the
/// port told when it is the scheme's own; `None` for no host.
#[cfg(any(test, all(unix, not(target_os = "macos"), feature = "portal")))]
fn origin(url: &str) -> Option<String> {
let (scheme, rest) = url.trim().split_once("://")?;
let scheme = scheme.to_ascii_lowercase();
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
// Without the user and password.
let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h).to_ascii_lowercase();
if host_port.is_empty() {
return None;
}
let has_port = match host_port.rfind(':') {
// An IPv6 address without a port ends in `]`.
Some(at) => !host_port[at..].contains(']'),
None => false,
};
if has_port {
return Some(format!("{scheme}://{host_port}"));
}
let port = match scheme.as_str() {
"http" | "ws" => 80,
"https" | "wss" => 443,
_ => 0,
};
Some(format!("{scheme}://{host_port}:{port}"))
}
/// Answers kept for [`KEEP`].
#[cfg(any(test, all(unix, not(target_os = "macos"), feature = "portal")))]
#[derive(Default)]
struct Answers(std::collections::HashMap<String, (std::time::Instant, Option<String>)>);
#[cfg(any(test, all(unix, not(target_os = "macos"), feature = "portal")))]
impl Answers {
/// The answer for `origin` if it is still fresh at `now`.
fn get(&self, origin: &str, now: std::time::Instant) -> Option<Option<String>> {
let (at, answer) = self.0.get(origin)?;
(now.saturating_duration_since(*at) < KEEP).then(|| answer.clone())
}
/// Keep `answer` for `origin`, as it was at `now`, unless a newer one
/// is kept (the stale ones go).
fn put(&mut self, origin: String, now: std::time::Instant, answer: Option<String>) {
self.0.retain(|_, (at, _)| now.saturating_duration_since(*at) < KEEP);
if self.0.get(&origin).is_some_and(|(at, _)| *at > now) {
return;
}
self.0.insert(origin, (now, answer));
}
}
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
mod portal {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{LazyLock, Mutex, PoisonError};
use std::time::Instant;
use ashpd::desktop::proxy_resolver::ProxyResolver;
use tracing::{debug, info};
use super::{Answers, KEEP, TIMEOUT, for_log, origin, usable_proxy};
/// How long a lookup no longer waited for may still take: its answer is
/// kept when it comes (a portal the first call starts often takes
/// longer than [`TIMEOUT`]).
const LATE: std::time::Duration = std::time::Duration::from_secs(25);
static RESOLVER: tokio::sync::OnceCell<ProxyResolver> = tokio::sync::OnceCell::const_new();
static ANSWERS: LazyLock<Mutex<Answers>> = LazyLock::new(Mutex::default);
/// Until when the portal is taken as missing (it could not be reached).
static MISSING_UNTIL: Mutex<Option<Instant>> = Mutex::new(None);
/// Whether a missing portal was logged (once a run).
static MISSING_LOGGED: AtomicBool = AtomicBool::new(false);
fn answers() -> std::sync::MutexGuard<'static, Answers> {
ANSWERS.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(super) async fn proxy_for(url: &str) -> Option<String> {
let key = origin(url)?;
let now = Instant::now();
if let Some(answer) = answers().get(&key, now) {
return answer;
}
let missing = *MISSING_UNTIL.lock().unwrap_or_else(PoisonError::into_inner);
if missing.is_some_and(|until| now < until) {
answers().put(key, now, None);
return None;
}
let asked = tokio::spawn(ask(url.to_owned(), key.clone()));
match tokio::time::timeout(TIMEOUT, asked).await {
Ok(answer) => answer.unwrap_or_default(),
Err(_) => {
debug!(origin = %key, "the desktop's proxy resolver did not answer within a second");
// None until its answer comes.
answers().put(key, now, None);
None
}
}
}
/// Ask the portal for `url`'s proxy and keep the answer as `key`'s,
/// late too (within [`LATE`]).
async fn ask(url: String, key: String) -> Option<String> {
let answer = match tokio::time::timeout(LATE, lookup(&url)).await {
Ok(Ok(answer)) => {
debug!(origin = %key, answer = ?for_log(&answer), "the desktop's proxy");
usable_proxy(&answer)
}
Ok(Err(Unreachable(e))) => {
*MISSING_UNTIL.lock().unwrap_or_else(PoisonError::into_inner) =
Some(Instant::now() + KEEP);
if !MISSING_LOGGED.swap(true, Ordering::Relaxed) {
info!(error = %e, "no desktop proxy settings (xdg-desktop-portal's ProxyResolver)");
}
None
}
Ok(Err(Failed(e))) => {
debug!(origin = %key, error = %e, "the desktop's proxy resolver failed");
None
}
Err(_) => {
debug!(origin = %key, "the desktop's proxy resolver did not answer");
None
}
};
answers().put(key, Instant::now(), answer.clone());
answer
}
/// Why there is no answer.
enum Error {
/// The portal cannot be reached (no session bus, no portal, no
/// ProxyResolver in it).
Unreachable(ashpd::Error),
/// It failed for this address.
Failed(ashpd::Error),
}
use Error::{Failed, Unreachable};
async fn lookup(url: &str) -> Result<Vec<String>, Error> {
let resolver = RESOLVER.get_or_try_init(ProxyResolver::new).await.map_err(Unreachable)?;
let uri = ashpd::Uri::parse(url).map_err(|e| Failed(e.into()))?;
// A portal not on the bus shows only now: making the resolver
// does not ask it anything it must answer.
let answer = resolver
.lookup(&uri)
.await
.map_err(|e| if not_there(&e) { Unreachable(e) } else { Failed(e) })?;
Ok(answer.iter().map(|uri| uri.as_str().to_owned()).collect())
}
/// Whether `error` says no portal answers on the bus (none running nor
/// startable, or one without ProxyResolver), not that a lookup failed.
pub(super) fn not_there(error: &ashpd::Error) -> bool {
use ashpd::zbus::{self, fdo};
let bus = match error {
ashpd::Error::PortalNotFound(_) => return true,
ashpd::Error::Zbus(e) | ashpd::Error::Portal(ashpd::PortalError::ZBus(e)) => e,
_ => return false,
};
match bus {
zbus::Error::MethodError(name, ..) => matches!(
name.as_str(),
"org.freedesktop.DBus.Error.ServiceUnknown"
| "org.freedesktop.DBus.Error.NameHasNoOwner"
| "org.freedesktop.DBus.Error.UnknownObject"
| "org.freedesktop.DBus.Error.UnknownInterface"
| "org.freedesktop.DBus.Error.UnknownMethod"
),
zbus::Error::FDO(e) => matches!(
**e,
fdo::Error::ServiceUnknown(_)
| fdo::Error::NameHasNoOwner(_)
| fdo::Error::UnknownObject(_)
| fdo::Error::UnknownInterface(_)
| fdo::Error::UnknownMethod(_)
),
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use super::*;
#[test]
fn proxies_of_answers() {
assert_eq!(usable_proxy(&["direct://"]), None);
assert_eq!(usable_proxy::<&str>(&[]), None);
assert_eq!(
usable_proxy(&["http://127.0.0.1:2080", "direct://"]).as_deref(),
Some("http://127.0.0.1:2080")
);
assert_eq!(
usable_proxy(&["https://proxy.example:443/"]).as_deref(),
Some("https://proxy.example:443")
);
// SOCKS: the proxy resolves the host.
assert_eq!(
usable_proxy(&["socks://127.0.0.1:2080"]).as_deref(),
Some("socks5h://127.0.0.1:2080")
);
assert_eq!(usable_proxy(&["SOCKS5://u:p@h:1"]).as_deref(), Some("socks5h://u:p@h:1"));
assert_eq!(usable_proxy(&["socks4://h:1080"]).as_deref(), Some("socks4a://h:1080"));
assert_eq!(usable_proxy(&["socks5h://h:1080"]).as_deref(), Some("socks5h://h:1080"));
// What HTTP cannot use is skipped; direct ends the list.
assert_eq!(
usable_proxy(&["rtsp://h:554", "http://h:3128"]).as_deref(),
Some("http://h:3128")
);
assert_eq!(usable_proxy(&["direct://", "http://h:3128"]), None);
assert_eq!(usable_proxy(&["nonsense", "http://"]), None);
}
/// The answer in the log has no passwords, which GLib puts in it.
#[test]
fn answers_are_logged_without_passwords() {
let answer = ["http://u:secret@h:1", "socks://u:p/w@rd#x@127.0.0.1:2080", "direct://"];
let logged = format!("{:?}", for_log(&answer));
assert_eq!(logged, r#"["http://h:1", "socks://127.0.0.1:2080", "direct://"]"#);
assert_eq!(for_log(&["u:secret@h:1"]), ["h:1"]);
}
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
#[test]
fn a_portal_not_on_the_bus_is_missing() {
use ashpd::zbus::{self, fdo};
let fdo = |e: fdo::Error| zbus::Error::FDO(Box::new(e));
let not_there = |e: &ashpd::Error| portal::not_there(e);
let unknown = fdo(fdo::Error::ServiceUnknown("not activatable".into()));
assert!(not_there(&ashpd::Error::Portal(ashpd::PortalError::ZBus(unknown))));
let no_owner = fdo(fdo::Error::NameHasNoOwner("gone".into()));
assert!(not_there(&ashpd::Error::Zbus(no_owner)));
assert!(!not_there(&ashpd::Error::Zbus(fdo(fdo::Error::Failed("PAC".into())))));
assert!(!not_there(&ashpd::Error::Portal(ashpd::PortalError::Failed("PAC".into()))));
}
#[test]
fn answers_are_kept_by_scheme_host_and_port() {
assert_eq!(
origin("https://Upload.Wikimedia.org/a/b.png?x#y").as_deref(),
Some("https://upload.wikimedia.org:443")
);
assert_eq!(origin("http://u:p@h.test:8080/").as_deref(), Some("http://h.test:8080"));
assert_eq!(origin("http://[::1]/x").as_deref(), Some("http://[::1]:80"));
assert_eq!(origin("http://[::1]:81").as_deref(), Some("http://[::1]:81"));
assert_eq!(origin("https:///x"), None);
assert_eq!(origin("no scheme"), None);
let mut answers = Answers::default();
let now = Instant::now();
assert_eq!(answers.get("https://h:443", now), None);
answers.put("https://h:443".into(), now, Some("http://p:1".into()));
// No answer is kept too.
answers.put("https://n:443".into(), now, None);
let soon = now + Duration::from_secs(59);
assert_eq!(answers.get("https://h:443", soon), Some(Some("http://p:1".into())));
assert_eq!(answers.get("https://n:443", soon), Some(None));
assert_eq!(answers.get("http://h:80", soon), None);
let later = now + KEEP;
assert_eq!(answers.get("https://h:443", later), None);
answers.put("https://other:443".into(), later, None);
assert_eq!(answers.0.len(), 1, "stale answers go");
// A late answer stays: the "none" kept while it was awaited is older.
let mut answers = Answers::default();
answers.put(
"https://h:443".into(),
now + Duration::from_secs(3),
Some("http://p:1".into()),
);
answers.put("https://h:443".into(), now, None);
assert_eq!(answers.get("https://h:443", soon), Some(Some("http://p:1".into())));
}
/// Without a portal (or off Linux): no proxy, at once.
#[tokio::test]
async fn no_answer_is_no_proxy() {
let started = Instant::now();
let _ = proxy_for("https://example.com/").await;
assert!(started.elapsed() < Duration::from_secs(5));
assert_eq!(proxy_for("not an address").await, None);
}
}
+68
View File
@@ -0,0 +1,68 @@
//! The desktop's proxy through a stand-in xdg-desktop-portal on the
//! session bus. Run it on a private bus:
//! `dbus-run-session -- cargo test -p voelin-platform --test proxy`;
//! without a session bus it checks nothing. Its own test binary: answers
//! are kept process-wide.
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use voelin_platform::proxy::proxy_for;
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
/// others.
struct Resolver {
lookups: Arc<AtomicU32>,
}
#[zbus::interface(name = "org.freedesktop.portal.ProxyResolver")]
impl Resolver {
fn lookup(&self, uri: &str) -> Vec<String> {
self.lookups.fetch_add(1, Ordering::SeqCst);
if uri.starts_with("https://capped.example") {
vec!["socks://127.0.0.1:2080".into()]
} else {
vec!["direct://".into()]
}
}
#[zbus(property)]
fn version(&self) -> u32 {
1
}
}
#[tokio::test]
async fn the_portal_names_the_proxy() {
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
eprintln!("no session bus: run under dbus-run-session");
return;
}
let lookups = Arc::new(AtomicU32::new(0));
let portal = zbus::connection::Builder::session()
.unwrap()
.name("org.freedesktop.portal.Desktop")
.unwrap()
.serve_at("/org/freedesktop/portal/desktop", Resolver { lookups: lookups.clone() })
.unwrap()
.build()
.await
.unwrap();
let proxy = proxy_for("https://capped.example:443/").await;
assert_eq!(proxy.as_deref(), Some("socks5h://127.0.0.1:2080"));
assert_eq!(proxy_for("https://other.example/").await, None);
assert_eq!(lookups.load(Ordering::SeqCst), 2);
// Kept: the same scheme, host and port are not asked again.
let proxy = proxy_for("https://capped.example/a/b.png").await;
assert_eq!(proxy.as_deref(), Some("socks5h://127.0.0.1:2080"));
assert_eq!(lookups.load(Ordering::SeqCst), 2);
// The portal leaves the bus: missing for a minute, not asked meanwhile.
const PORTAL: &str = "org.freedesktop.portal.Desktop";
assert!(portal.release_name(PORTAL).await.unwrap());
assert_eq!(proxy_for("https://gone.example/").await, None);
portal.request_name(PORTAL).await.unwrap();
assert_eq!(proxy_for("https://capped.example:8443/").await, None);
assert_eq!(lookups.load(Ordering::SeqCst), 2);
}
+4
View File
@@ -17,6 +17,10 @@ thiserror = "2.0.21"
tokio = { version = "1.53.1", features = ["net", "io-util", "sync", "time", "rt", "macros"] }
tracing = "0.1.44"
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
# TCP_QUICKACK on query connections (src/tcp.rs).
socket2 = { version = "0.6", features = ["all"] }
[lints]
workspace = true
+175 -10
View File
@@ -1,14 +1,25 @@
//! Transport-independent query client.
use std::time::Duration;
use tokio::io::split;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::time::{Instant, timeout_at};
use tracing::debug;
use crate::codec::{Command, Notification, Row};
use crate::http::HttpClient;
use crate::line::{LineClient, LineOptions};
use crate::tcp::QuickAck;
use crate::{Error, Result};
/// How long to send nothing after the server dropped an SSH login: its flood
/// protection counts per 3 seconds.
const SSH_DROP_WAIT: Duration = Duration::from_secs(3);
/// Seconds between attempts to open a query connection, the last repeating.
const RETRY_SECS: [u64; 6] = [1, 2, 3, 5, 10, 30];
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Transport {
@@ -34,6 +45,39 @@ pub struct Connect {
pub line: LineOptions,
}
impl Connect {
/// How long to wait after failed attempt `attempt` (counted from 1) to
/// open a connection: the next step of [`RETRY_SECS`], or longer if the
/// server's flood protection asked for it.
pub fn retry_delay(&self, attempt: u32) -> Duration {
let step = RETRY_SECS[(attempt.max(1) as usize - 1).min(RETRY_SECS.len() - 1)];
Duration::from_secs(step).max(self.line.flood.held_for().unwrap_or_default())
}
}
/// Whether failed attempt `attempt` to open a connection is worth a
/// warning: the first few are, then every tenth (about every 5 minutes at
/// the longest wait). Log the others at debug level.
pub fn attempt_worth_a_warning(attempt: u32) -> bool {
attempt <= 3 || attempt.is_multiple_of(10)
}
/// Fails at once when the server's flood protection asked to wait past
/// `deadline`: the connection could not log in in time anyway.
fn flood_wait_fits(options: &LineOptions, addr: &str, deadline: Instant) -> Result<()> {
match options.flood.held_for() {
Some(held) if Instant::now() + held > deadline => Err(io_timeout(format!(
"the server's flood protection asks to wait {} s; not connecting to {addr} now",
held.as_secs()
))),
_ => Ok(()),
}
}
fn io_timeout(message: String) -> Error {
Error::Io(std::io::Error::new(std::io::ErrorKind::TimedOut, message))
}
/// A logged-in query connection with a selected virtual server.
#[derive(Clone)]
pub enum QueryClient {
@@ -47,26 +91,61 @@ impl QueryClient {
pub async fn connect(
cfg: &Connect,
) -> Result<(Self, Option<mpsc::UnboundedReceiver<Notification>>)> {
let options = &cfg.line;
// Connecting, logging in and selecting the server, all of it.
let deadline = Instant::now() + options.connect_timeout;
let timed_out = |what: &str| {
let wait_s = options.connect_timeout.as_secs_f32();
io_timeout(format!("{what} at {} within {wait_s} s", cfg.addr))
};
match cfg.transport {
Transport::Raw => {
let stream = TcpStream::connect(&cfg.addr).await?;
stream.set_nodelay(true)?;
let (r, w) = stream.into_split();
let (client, events) = LineClient::spawn(r, w, cfg.line.clone());
flood_wait_fits(options, &cfg.addr, deadline)?;
let stream = QuickAck::connect(&cfg.addr, options.connect_timeout).await?;
let (r, w) = split(stream);
let (client, events) = LineClient::spawn(r, w, options.clone());
let client = Self::Line(client);
client.login_and_use(cfg).await?;
timeout_at(deadline, client.login_and_use(cfg))
.await
.map_err(|_| timed_out("no query login"))??;
Ok((client, Some(events)))
}
Transport::Ssh => {
// The server counts the SSH login as a command.
flood_wait_fits(options, &cfg.addr, deadline)?;
timeout_at(deadline, options.flood.acquire(options.rate_limit))
.await
.map_err(|_| timed_out("the flood protection allowed no login"))?;
let password = cfg.secret.as_deref().unwrap_or_default();
let shell = crate::ssh::connect(&cfg.addr, &cfg.user, password).await?;
tracing::debug!(fingerprint = ?shell.fingerprint, addr = %cfg.addr, "ssh query connected");
let wait = deadline.saturating_duration_since(Instant::now());
let login = crate::ssh::connect(&cfg.addr, &cfg.user, password, wait);
let shell = match timeout_at(deadline, login).await {
Ok(shell) => shell,
Err(_) => Err(timed_out("no SSH login")),
};
// A server at its flood limit drops new connections during the
// login, without saying why.
if options.flood.limit(options.rate_limit).is_some()
&& matches!(shell, Err(Error::Ssh(russh::Error::Disconnect)))
{
debug!(addr = %cfg.addr, "SSH login dropped, maybe by the flood protection; waiting");
options.flood.hold(SSH_DROP_WAIT);
}
let shell = shell?;
debug!(
fingerprint = ?shell.fingerprint,
addr = %cfg.addr,
conn = %options.label,
"ssh query connected"
);
let (r, w) = split(shell.stream);
let (client, events) =
LineClient::spawn_with_guard(r, w, cfg.line.clone(), shell.session);
LineClient::spawn_with_guard(r, w, options.clone(), shell.session);
let client = Self::Line(client);
// SSH already authenticated; only select the server.
client.use_server(cfg).await?;
timeout_at(deadline, client.use_server(cfg))
.await
.map_err(|_| timed_out("no answer to selecting the server"))??;
Ok((client, Some(events)))
}
Transport::Http => {
@@ -134,6 +213,22 @@ impl QueryClient {
}
}
/// The connection is gone (HTTP has none).
pub fn is_closed(&self) -> bool {
match self {
QueryClient::Line(c) => c.is_closed(),
QueryClient::Http(_) => false,
}
}
/// Resolves when the connection is gone (never for HTTP).
pub async fn closed(&self) {
match self {
QueryClient::Line(c) => c.closed().await,
QueryClient::Http(_) => std::future::pending().await,
}
}
/// Whether the transport delivers `notify*` events.
pub fn has_events(&self) -> bool {
matches!(self, QueryClient::Line(_))
@@ -147,3 +242,73 @@ impl QueryClient {
.ok_or_else(|| Error::Protocol("whoami without client_id".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A server that accepts connections and never says anything.
async fn silent_server() -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
tokio::spawn(async move {
let mut open = Vec::new();
while let Ok((stream, _)) = listener.accept().await {
open.push(stream);
}
});
addr
}
fn connect(transport: Transport, addr: &str) -> Connect {
Connect {
transport,
addr: addr.into(),
user: "serveradmin".into(),
secret: Some("pw".into()),
server_port: None,
server_id: None,
line: LineOptions { connect_timeout: Duration::from_millis(300), ..Default::default() },
}
}
async fn assert_times_out(cfg: &Connect) {
let started = std::time::Instant::now();
match QueryClient::connect(cfg).await {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::TimedOut),
Err(e) => panic!("{e}"),
Ok(_) => panic!("connected to a silent server"),
}
assert!(started.elapsed() < Duration::from_secs(5));
}
#[tokio::test]
async fn a_silent_server_does_not_hold_up_the_login() {
let addr = silent_server().await;
// In the SSH handshake.
assert_times_out(&connect(Transport::Ssh, &addr)).await;
// At `login` and `use`, which have a longer timeout of their own.
assert_times_out(&connect(Transport::Raw, &addr)).await;
}
#[tokio::test]
async fn a_long_flood_wait_fails_the_connect_at_once() {
let addr = silent_server().await;
let cfg = connect(Transport::Ssh, &addr);
cfg.line.flood.hold(Duration::from_secs(600));
let started = std::time::Instant::now();
assert!(matches!(QueryClient::connect(&cfg).await, Err(Error::Io(_))));
assert!(started.elapsed() < Duration::from_millis(100));
}
#[test]
fn waits_grow_and_follow_the_server() {
let cfg = connect(Transport::Raw, "h:1");
let secs = |attempt| cfg.retry_delay(attempt).as_secs();
assert_eq!([secs(1), secs(3), secs(5), secs(6), secs(60)], [1, 3, 10, 30, 30]);
cfg.line.flood.hold(Duration::from_secs(600));
assert!(cfg.retry_delay(1) > Duration::from_secs(590));
let warned: Vec<u32> = (1..=30).filter(|a| attempt_worth_a_warning(*a)).collect();
assert_eq!(warned, [1, 2, 3, 10, 20, 30]);
}
}
+6
View File
@@ -139,6 +139,12 @@ impl QueryError {
self.id == 1281
}
/// The server's flood protection refused the command; `extra_msg` says
/// how long to wait (`please wait 1 seconds`).
pub fn is_flood(&self) -> bool {
self.id == 524
}
pub(crate) fn from_row(row: &Row) -> Self {
QueryError {
id: row.parse("id").unwrap_or(u32::MAX),
+3 -2
View File
@@ -17,13 +17,14 @@ mod codec;
mod http;
mod line;
mod ssh;
mod tcp;
pub use client::{Connect, QueryClient, Transport};
pub use client::{Connect, QueryClient, Transport, attempt_worth_a_warning};
pub use codec::{
Command, Line, Notification, QueryError, Row, escape, parse_line, parse_rows, unescape,
};
pub use http::HttpClient;
pub use line::{LineClient, LineOptions};
pub use line::{FloodGuard, LineClient, LineOptions};
#[derive(Debug, thiserror::Error)]
pub enum Error {
+501 -79
View File
@@ -5,39 +5,163 @@
//! event channel whenever they arrive.
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::sync::{mpsc, oneshot};
use tokio::time::{Instant, sleep_until};
use tracing::{debug, trace};
use tracing::{Instrument, debug, info_span, trace, warn};
use crate::codec::{Command, Line, Notification, Row, parse_line};
use crate::codec::{Command, Line, Notification, QueryError, Row, parse_line};
use crate::{Error, Result};
/// Waited on top of what the server asks for: its clock is not ours.
const FLOOD_MARGIN: Duration = Duration::from_millis(100);
/// TeamSpeak refuses the 10th command within 3 seconds from one address,
/// the SSH login included.
const SERVER_LIMIT: (u32, Duration) = (9, Duration::from_secs(3));
#[derive(Clone, Debug)]
pub struct LineOptions {
/// Send `whoami` after this long without traffic (servers drop idle
/// query connections after 300 s by default).
pub keepalive: Duration,
/// Flood protection: at most `rate_commands` per `rate_window`. `None`
/// when the client IP is on the server's query allowlist.
/// Flood protection: at most this many commands per window, counted in
/// `flood`. `None` when the client IP is on the server's query
/// allowlist (until the server refuses a command for flooding: then
/// the default applies).
pub rate_limit: Option<(u32, Duration)>,
/// Give up on a command after this long.
/// Give up on a command after this long, time in the queue included.
/// A connection whose server leaves a command unanswered for twice as
/// long is closed.
pub timeout: Duration,
/// Give up opening a connection after this long: connecting, logging in
/// and selecting the server, waits for the flood protection included.
pub connect_timeout: Duration,
/// What the connection is for (`lookup`, `observer`, `relay 5`), in
/// its log lines.
pub label: String,
/// Commands sent and waits the server asked for. The server counts
/// commands per source address, so clones of these options (and the
/// connections opened with them) share one count.
pub flood: FloodGuard,
}
impl Default for LineOptions {
fn default() -> Self {
Self {
keepalive: Duration::from_secs(180),
// TeamSpeak's default: 10 commands per 3 seconds.
rate_limit: Some((10, Duration::from_secs(3))),
rate_limit: Some(SERVER_LIMIT),
timeout: Duration::from_secs(15),
connect_timeout: Duration::from_secs(10),
label: "query".into(),
flood: FloodGuard::default(),
}
}
}
/// The flood protection's state, shared by every connection to one server:
/// when recent commands went out, and until when the server asked to wait.
#[derive(Clone, Debug, Default)]
pub struct FloodGuard(Arc<Mutex<FloodState>>);
#[derive(Debug, Default)]
struct FloodState {
sent: VecDeque<Instant>,
hold_until: Option<Instant>,
/// The server refused a command although no limit was set: the address
/// is not on its allowlist after all.
limited: bool,
}
impl FloodState {
/// `limit`, or the server's own when it turned out to apply.
fn limit(&self, limit: Option<(u32, Duration)>) -> Option<(u32, Duration)> {
limit.or(self.limited.then_some(SERVER_LIMIT))
}
/// When the next command may be sent.
fn next_slot(&mut self, limit: Option<(u32, Duration)>, now: Instant) -> Instant {
let held = self.hold_until.filter(|t| *t > now);
self.hold_until = held;
let Some((count, window)) = limit else { return held.unwrap_or(now) };
while self.sent.front().is_some_and(|t| now.duration_since(*t) >= window) {
self.sent.pop_front();
}
let slot = match self.sent.len().checked_sub(count as usize) {
None => now,
// Leave a little margin: the server's clock is not ours.
Some(oldest) => self.sent[oldest] + window + Duration::from_millis(50),
};
held.map_or(slot, |held| held.max(slot))
}
}
impl FloodGuard {
fn lock(&self) -> std::sync::MutexGuard<'_, FloodState> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Wait until a command may be sent under `limit`, and count it. Safe to
/// cancel: the command is only counted when this returns.
pub async fn acquire(&self, limit: Option<(u32, Duration)>) {
loop {
let slot = {
let mut state = self.lock();
let now = Instant::now();
let limit = state.limit(limit);
let slot = state.next_slot(limit, now);
if slot <= now {
if limit.is_some() {
state.sent.push_back(now);
}
return;
}
slot
};
sleep_until(slot).await;
}
}
/// The limit that applies: `limit`, or the server's own once it refused
/// a command although `limit` was `None`.
pub fn limit(&self, limit: Option<(u32, Duration)>) -> Option<(u32, Duration)> {
self.lock().limit(limit)
}
/// Send nothing for `wait`, on any connection sharing this guard.
pub fn hold(&self, wait: Duration) {
let until = Instant::now() + wait;
let mut state = self.lock();
state.hold_until = Some(state.hold_until.map_or(until, |held| held.max(until)));
}
/// Keep to the server's limit from now on, also where none was set.
/// Whether that is new.
fn limit_from_now_on(&self) -> bool {
!std::mem::replace(&mut self.lock().limited, true)
}
/// How long sending is still held, if it is.
pub fn held_for(&self) -> Option<Duration> {
let until = self.lock().hold_until?;
until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero())
}
}
/// How long the server's flood protection asks to wait
/// (`extra_msg=please\swait\s1\sseconds`).
fn flood_wait(error: &QueryError) -> Duration {
let seconds = error
.extra_msg
.as_deref()
.and_then(|m| m.split(' ').find_map(|word| word.parse::<u64>().ok()))
.unwrap_or(3);
Duration::from_secs(seconds)
}
type Reply = oneshot::Sender<Result<Vec<Row>>>;
struct Request {
@@ -50,6 +174,8 @@ struct Request {
pub struct LineClient {
requests: mpsc::Sender<Request>,
timeout: Duration,
/// [`LineOptions::label`].
label: Arc<str>,
}
impl LineClient {
@@ -82,11 +208,17 @@ impl LineClient {
let (requests, rx) = mpsc::channel(64);
let (events_tx, events) = mpsc::unbounded_channel();
let timeout = options.timeout;
tokio::spawn(async move {
run(BufReader::new(reader), writer, rx, events_tx, options).await;
drop(guard);
});
(Self { requests, timeout }, events)
let label = Arc::from(options.label.as_str());
// Not a child of whatever opened the connection: it outlives that.
let span = info_span!(parent: None, "query", conn = %options.label);
tokio::spawn(
async move {
run(BufReader::new(reader), writer, rx, events_tx, options).await;
drop(guard);
}
.instrument(span),
);
(Self { requests, timeout, label }, events)
}
/// Send a command and collect its data rows.
@@ -97,44 +229,78 @@ impl LineClient {
/// Send an already formatted command line.
pub async fn send_line(&self, line: String) -> Result<Vec<Row>> {
let (reply, rx) = oneshot::channel();
let name = command_name(&line).to_owned();
self.requests.send(Request { line, reply }).await.map_err(|_| Error::Closed)?;
match tokio::time::timeout(self.timeout, rx).await {
Ok(Ok(result)) => result,
Ok(Err(_)) => Err(Error::Closed),
Err(_) => Err(Error::Timeout),
Err(_) => {
let timeout_s = self.timeout.as_secs();
debug!(conn = %self.label, command = name, timeout_s, "no answer in time");
Err(Error::Timeout)
}
}
}
pub fn is_closed(&self) -> bool {
self.requests.is_closed()
}
/// Resolves when the connection is gone.
pub async fn closed(&self) {
self.requests.closed().await;
}
}
/// Token bucket for the query flood protection.
struct RateLimiter {
limit: Option<(u32, Duration)>,
sent: VecDeque<Instant>,
/// The command of a line (`clientlist` of `clientlist -uid`).
fn command_name(line: &str) -> &str {
line.split(' ').next().unwrap_or_default()
}
impl RateLimiter {
/// When the next command may be sent.
fn next_slot(&mut self, now: Instant) -> Instant {
let Some((count, window)) = self.limit else { return now };
while self.sent.front().is_some_and(|t| now.duration_since(*t) >= window) {
self.sent.pop_front();
}
if self.sent.len() < count as usize {
now
} else {
// Leave a little margin: the server's clock is not ours.
self.sent[0] + window + Duration::from_millis(50)
}
/// A line as it may appear in the log: never a login's password.
fn loggable(line: &str) -> &str {
if command_name(line) == "login" { "login (credentials not logged)" } else { line }
}
/// A command on its way out.
struct Outgoing {
line: String,
/// `None` for the keepalive.
reply: Option<Reply>,
/// Already sent once and refused by the flood protection.
retried: bool,
}
impl Outgoing {
fn name(&self) -> &str {
command_name(&self.line)
}
fn record(&mut self, t: Instant) {
if self.limit.is_some() {
self.sent.push_back(t);
}
/// The caller gave up waiting.
fn abandoned(&self) -> bool {
self.reply.as_ref().is_some_and(oneshot::Sender::is_closed)
}
}
/// A command sent and not answered yet.
struct Sent {
command: Outgoing,
at: Instant,
rows: Vec<Row>,
}
/// Resolves when the caller of the queued command gives up.
async fn given_up(queued: &mut Option<Outgoing>) {
match queued.as_mut().and_then(|c| c.reply.as_mut()) {
Some(reply) => reply.closed().await,
None => std::future::pending().await,
}
}
async fn sleep_until_some(at: Option<Instant>) {
match at {
Some(at) => sleep_until(at).await,
None => std::future::pending().await,
}
}
@@ -148,21 +314,28 @@ async fn run<R, W>(
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
let mut limiter = RateLimiter { limit: options.rate_limit, sent: VecDeque::new() };
// The request being answered and the rows collected for it so far.
let mut pending: Option<(Reply, Vec<Row>)> = None;
let mut keepalive_pending = false;
let flood = options.flood.clone();
let limit = options.rate_limit;
// Taken from the queue, waiting for the flood protection.
let mut queued: Option<Outgoing> = None;
// Sent, waiting for the answer.
let mut sent: Option<Sent> = None;
let mut last_activity = Instant::now();
let mut buf = Vec::new();
loop {
let can_send = pending.is_none() && !keepalive_pending;
let idle = queued.is_none() && sent.is_none();
let keepalive_at = last_activity + options.keepalive;
let stalled_at = sent.as_ref().map(|s| s.at + options.timeout * 2);
tokio::select! {
read = reader.read_until(b'\n', &mut buf) => {
match read {
Ok(0) | Err(_) => {
debug!("query connection closed");
Ok(0) => {
debug!("query connection closed by the server");
break;
}
Err(error) => {
debug!(%error, "query connection failed");
break;
}
Ok(_) => {}
@@ -179,59 +352,113 @@ async fn run<R, W>(
// any `=` are the welcome banner, which may arrive after the
// first command was sent.
Line::Data(rows) if text.contains('=') => {
if let Some((_, collected)) = &mut pending {
collected.extend(rows);
if let Some(sent) = &mut sent {
sent.rows.extend(rows);
}
}
Line::Data(_) => {}
Line::Error(e) => {
if keepalive_pending && pending.is_none() {
keepalive_pending = false;
} else if let Some((reply, rows)) = pending.take() {
let result = if e.is_ok() || e.is_empty_result() {
Ok(rows)
} else {
Err(e.into())
};
let _ = reply.send(result);
let Some(Sent { command, at, rows }) = sent.take() else { continue };
let elapsed_ms = (at.elapsed().as_secs_f64() * 10_000.0).round() / 10.0;
trace!(command = command.name(), id = e.id, rows = rows.len(), elapsed_ms, "query answered");
if e.is_flood() {
// Every connection waits: the server counts them together,
// and two more commands now would get the address banned.
// What the server asks for is too short: it still counts
// the commands of the last 3 s, the refused ones too.
let wait = flood_wait(&e).max(SERVER_LIMIT.1);
flood.hold(wait + FLOOD_MARGIN);
if limit.is_none() && flood.limit_from_now_on() {
warn!(
"the server limits this address although it was taken to be on its query allowlist; keeping to 9 commands per 3 s from now on"
);
}
// The keepalive did its job: the server answered.
let resend = !command.retried && command.reply.is_some();
warn!(
command = command.name(),
wait_ms = wait.as_millis() as u64,
resend,
"the server's flood protection refused a command; sending nothing until the wait is over"
);
if resend {
queued = Some(Outgoing { retried: true, ..command });
continue;
}
}
let name = command.name().to_owned();
let Some(reply) = command.reply else { continue };
let result = if e.is_ok() || e.is_empty_result() {
Ok(rows)
} else {
debug!(
command = name,
error = %e,
elapsed_ms = at.elapsed().as_millis() as u64,
"query command failed"
);
Err(e.into())
};
let _ = reply.send(result);
}
}
}
req = requests.recv(), if can_send => {
req = requests.recv(), if idle => {
let Some(req) = req else { break };
let slot = limiter.next_slot(Instant::now());
if slot > Instant::now() {
sleep_until(slot).await;
let command = Outgoing { line: req.line, reply: Some(req.reply), retried: false };
if command.abandoned() {
debug!(command = command.name(), "dropping a command its caller gave up on");
} else {
queued = Some(command);
}
limiter.record(Instant::now());
trace!(line = %req.line, "query >");
if let Err(e) = write_line(&mut writer, &req.line).await {
let _ = req.reply.send(Err(e.into()));
break;
}
last_activity = Instant::now();
pending = Some((req.reply, Vec::new()));
}
_ = sleep_until(keepalive_at), if can_send => {
limiter.record(Instant::now());
if write_line(&mut writer, "whoami").await.is_err() {
() = given_up(&mut queued) => {
if let Some(command) = queued.take() {
debug!(command = command.name(), "dropping a command its caller gave up on");
}
}
() = flood.acquire(limit), if queued.is_some() && sent.is_none() => {
let Some(command) = queued.take() else { continue };
if command.abandoned() {
debug!(command = command.name(), "dropping a command its caller gave up on");
continue;
}
trace!(line = %loggable(&command.line), "query >");
if let Err(e) = write_line(&mut writer, &command.line).await {
if let Some(reply) = command.reply {
let _ = reply.send(Err(e.into()));
}
break;
}
last_activity = Instant::now();
keepalive_pending = true;
sent = Some(Sent { command, at: last_activity, rows: Vec::new() });
}
_ = sleep_until(keepalive_at), if idle => {
queued = Some(Outgoing { line: "whoami".into(), reply: None, retried: false });
}
() = sleep_until_some(stalled_at) => {
let command = sent.as_ref().map(|s| s.command.name().to_owned()).unwrap_or_default();
warn!(
command,
waited_s = (options.timeout * 2).as_secs(),
"the server did not answer; closing the query connection"
);
break;
}
}
}
if let Some((reply, _)) = pending {
if let Some(Sent { command: Outgoing { reply: Some(reply), .. }, .. }) = sent {
let _ = reply.send(Err(Error::Closed));
}
debug!("query connection task ended");
}
/// Write one command in one write: over SSH each write is a packet.
async fn write_line<W: AsyncWrite + Unpin>(writer: &mut W, line: &str) -> std::io::Result<()> {
writer.write_all(line.as_bytes()).await?;
writer.write_all(b"\n").await?;
let mut bytes = Vec::with_capacity(line.len() + 1);
bytes.extend_from_slice(line.as_bytes());
bytes.push(b'\n');
writer.write_all(&bytes).await?;
writer.flush().await
}
@@ -300,15 +527,210 @@ mod tests {
}
#[tokio::test(start_paused = true)]
async fn rate_limiter_spaces_commands() {
let mut limiter =
RateLimiter { limit: Some((2, Duration::from_secs(3))), sent: VecDeque::new() };
async fn the_flood_guard_spaces_commands() {
let limit = Some((2, Duration::from_secs(3)));
let mut state = FloodState::default();
let t0 = Instant::now();
assert_eq!(limiter.next_slot(t0), t0);
limiter.record(t0);
limiter.record(t0);
assert!(limiter.next_slot(t0) >= t0 + Duration::from_secs(3));
assert_eq!(state.next_slot(limit, t0), t0);
state.sent.extend([t0, t0]);
assert!(state.next_slot(limit, t0) >= t0 + Duration::from_secs(3));
let later = t0 + Duration::from_secs(4);
assert_eq!(limiter.next_slot(later), later);
assert_eq!(state.next_slot(limit, later), later);
// A wait the server asked for applies with and without a limit.
state.hold_until = Some(later + Duration::from_secs(2));
assert_eq!(state.next_slot(limit, later), later + Duration::from_secs(2));
assert_eq!(state.next_slot(None, later), later + Duration::from_secs(2));
}
/// The commands a fake server got, and when.
type Seen = Arc<Mutex<Vec<(String, Instant)>>>;
/// A fake server that answers every command with `error id=0`, and
/// with `refusals` (in order) for the first ones; records when each
/// command arrived.
fn answering_server(stream: tokio::io::DuplexStream, refusals: Vec<&'static str>) -> Seen {
let seen = Arc::new(Mutex::new(Vec::new()));
let log = seen.clone();
tokio::spawn(async move {
let (r, mut w) = tokio::io::split(stream);
let mut lines = BufReader::new(r).lines();
let mut refusals = refusals.into_iter();
while let Ok(Some(line)) = lines.next_line().await {
log.lock().unwrap().push((line, Instant::now()));
let answer = refusals.next().unwrap_or("error id=0 msg=ok");
if w.write_all(format!("{answer}\n\r").as_bytes()).await.is_err() {
return;
}
}
});
seen
}
fn client(options: &LineOptions) -> (LineClient, Seen) {
client_refused(options, Vec::new())
}
fn client_refused(options: &LineOptions, refusals: Vec<&'static str>) -> (LineClient, Seen) {
let (client_io, server_io) = duplex(4096);
let seen = answering_server(server_io, refusals);
let (r, w) = tokio::io::split(client_io);
let (client, _events) = LineClient::spawn(r, w, options.clone());
(client, seen)
}
const FLOOD: &str =
"error id=524 msg=client\\sis\\sflooding extra_msg=please\\swait\\s2\\sseconds";
#[tokio::test(start_paused = true)]
async fn connections_share_the_flood_limit() {
// TeamSpeak counts the commands of all connections from one address.
let options =
LineOptions { rate_limit: Some((2, Duration::from_secs(3))), ..Default::default() };
let (a, seen_a) = client(&options);
let (b, seen_b) = client(&options.clone());
let t0 = Instant::now();
a.send(&Command::new("whoami")).await.unwrap();
a.send(&Command::new("whoami")).await.unwrap();
b.send(&Command::new("version")).await.unwrap();
let at = |seen: &Seen, i: usize| seen.lock().unwrap()[i].1;
assert_eq!(at(&seen_a, 1), t0);
assert!(at(&seen_b, 0) >= t0 + Duration::from_secs(3), "the third command waited");
// Options built separately count separately.
let (c, seen_c) = client(&LineOptions {
rate_limit: Some((2, Duration::from_secs(3))),
..Default::default()
});
let t1 = Instant::now();
c.send(&Command::new("whoami")).await.unwrap();
assert_eq!(at(&seen_c, 0), t1);
}
#[tokio::test(start_paused = true)]
async fn a_flood_refusal_holds_every_connection_then_resends_once() {
let options = LineOptions { rate_limit: None, ..Default::default() };
let (a, seen_a) = client_refused(&options, vec![FLOOD]);
let (b, seen_b) = client(&options);
let t0 = Instant::now();
let first = tokio::spawn(async move { a.send(&Command::new("clientlist")).await });
// While the server's wait lasts, the other connection sends nothing.
tokio::time::sleep(Duration::from_millis(100)).await;
b.send(&Command::new("whoami")).await.unwrap();
assert!(first.await.unwrap().is_ok(), "resent after the wait");
// At least the server's 3 s window, longer than it asked for.
let wait = Duration::from_millis(3100);
let seen_a = seen_a.lock().unwrap().clone();
assert_eq!(seen_a.len(), 2);
assert_eq!(seen_a[0].0, "clientlist");
assert!(seen_a[1].1 >= t0 + wait);
assert!(seen_b.lock().unwrap()[0].1 >= t0 + wait);
// Refused again: the caller gets the error, and sending still waits.
let (c, seen_c) = client_refused(&options, vec![FLOOD, FLOOD]);
match c.send(&Command::new("clientlist")).await {
Err(Error::Query(e)) => assert!(e.is_flood()),
other => panic!("{other:?}"),
}
assert_eq!(seen_c.lock().unwrap().len(), 2);
assert!(options.flood.held_for().is_some_and(|d| d > Duration::from_secs(2)));
}
#[tokio::test(start_paused = true)]
async fn a_refusal_without_a_limit_brings_the_servers_limit() {
// Taken to be on the allowlist, and it is not.
let options = LineOptions { rate_limit: None, ..Default::default() };
let (a, seen) = client_refused(&options, vec![FLOOD]);
for _ in 0..10 {
a.send(&Command::new("whoami")).await.unwrap();
}
let seen = seen.lock().unwrap().clone();
// Refused, resent, then 8 more at once and the 9th after 3 s.
assert_eq!(seen.len(), 11);
let resent = seen[1].1;
assert!(seen[9].1 - resent < Duration::from_secs(1));
assert!(seen[10].1 - resent >= Duration::from_secs(3));
}
#[tokio::test(start_paused = true)]
async fn commands_whose_caller_gave_up_are_not_sent() {
let options =
LineOptions { rate_limit: None, timeout: Duration::from_secs(1), ..Default::default() };
let (a, seen) = client(&options);
options.flood.hold(Duration::from_secs(5));
assert!(matches!(a.send(&Command::new("clientlist")).await, Err(Error::Timeout)));
tokio::time::sleep(Duration::from_secs(5)).await;
a.send(&Command::new("whoami")).await.unwrap();
let sent: Vec<String> = seen.lock().unwrap().iter().map(|(l, _)| l.clone()).collect();
assert_eq!(sent, ["whoami"]);
}
#[tokio::test(start_paused = true)]
async fn a_server_that_stops_answering_is_left() {
let (client_io, server_io) = duplex(4096);
// Reads commands and never answers.
tokio::spawn(async move {
let mut lines = BufReader::new(server_io).lines();
while let Ok(Some(_)) = lines.next_line().await {}
});
let (r, w) = tokio::io::split(client_io);
let options =
LineOptions { rate_limit: None, timeout: Duration::from_secs(1), ..Default::default() };
let (client, _events) = LineClient::spawn(r, w, options);
assert!(matches!(client.send(&Command::new("whoami")).await, Err(Error::Timeout)));
assert!(!client.is_closed());
tokio::time::sleep(Duration::from_secs(2)).await;
assert!(client.is_closed());
assert!(matches!(client.send(&Command::new("whoami")).await, Err(Error::Closed)));
}
#[test]
fn the_wait_comes_from_the_refusal() {
let refusal = |extra: Option<&str>| QueryError {
id: 524,
msg: "client is flooding".into(),
extra_msg: extra.map(Into::into),
failed_permid: None,
};
assert_eq!(flood_wait(&refusal(Some("please wait 600 seconds"))).as_secs(), 600);
assert_eq!(flood_wait(&refusal(None)).as_secs(), 3);
assert_eq!(
loggable("login client_login_name=a client_login_password=secret").find("secret"),
None
);
assert_eq!(loggable("whoami"), "whoami");
}
/// Records each write it gets.
struct Writes(Vec<Vec<u8>>);
impl AsyncWrite for Writes {
fn poll_write(
mut self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.0.push(buf.to_vec());
std::task::Poll::Ready(Ok(buf.len()))
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
}
#[tokio::test]
async fn a_command_goes_out_in_one_write() {
let mut writes = Writes(Vec::new());
write_line(&mut writes, "clientlist -uid").await.unwrap();
assert_eq!(writes.0, [b"clientlist -uid\n".to_vec()]);
}
}
+12 -3
View File
@@ -6,6 +6,7 @@ use std::time::Duration;
use russh::client;
use russh::keys::PublicKeyOrCertificate;
use crate::tcp::QuickAck;
use crate::{Error, Result};
/// Accepts any host key. ServerQuery hosts generate their key on first start
@@ -38,16 +39,24 @@ pub(crate) struct Shell {
pub fingerprint: Option<String>,
}
/// Open an SSH session and start the query shell.
pub(crate) async fn connect(addr: &str, user: &str, password: &str) -> Result<Shell> {
/// Open an SSH session and start the query shell, giving up on the TCP
/// connection after `timeout`.
pub(crate) async fn connect(
addr: &str,
user: &str,
password: &str,
timeout: Duration,
) -> Result<Shell> {
let config = Arc::new(client::Config {
inactivity_timeout: None,
keepalive_interval: Some(Duration::from_secs(60)),
nodelay: true,
..Default::default()
});
let fingerprint = Arc::new(std::sync::Mutex::new(None));
let handler = AcceptAny { fingerprint: fingerprint.clone() };
let mut session = client::connect(config, addr, handler).await?;
let stream = QuickAck::connect(addr, timeout).await?;
let mut session = client::connect_stream(config, stream, handler).await?;
let auth = session.authenticate_password(user, password).await?;
if !auth.success() {
return Err(Error::SshAuth);
+85
View File
@@ -0,0 +1,85 @@
//! TCP for the line-based transports.
//!
//! TeamSpeak sends a reply in more than one segment and waits for the
//! client's ACK of the first before it sends the rest. Linux delays that ACK
//! by about 40 ms, so every query command took about 45 ms. Re-arming
//! `TCP_QUICKACK` after each read that returned data (the kernel clears it
//! by itself) makes the ACK go out at once: a command then takes under 1 ms.
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::TcpStream;
/// A TCP connection that acknowledges what it receives at once.
pub(crate) struct QuickAck(TcpStream);
impl QuickAck {
/// Connect to `addr`, giving up after `timeout`.
pub(crate) async fn connect(addr: &str, timeout: Duration) -> io::Result<Self> {
let stream =
tokio::time::timeout(timeout, TcpStream::connect(addr)).await.map_err(|_| {
io::Error::new(
io::ErrorKind::TimedOut,
format!("no connection to {addr} within {} s", timeout.as_secs()),
)
})??;
stream.set_nodelay(true)?;
let stream = Self(stream);
stream.rearm();
Ok(stream)
}
fn rearm(&self) {
#[cfg(any(target_os = "linux", target_os = "android"))]
let _ = socket2::SockRef::from(&self.0).set_tcp_quickack(true);
}
}
impl AsyncRead for QuickAck {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let before = buf.filled().len();
let poll = Pin::new(&mut self.0).poll_read(cx, buf);
if matches!(poll, Poll::Ready(Ok(()))) && buf.filled().len() > before {
self.rearm();
}
poll
}
}
impl AsyncWrite for QuickAck {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.0).poll_write(cx, buf)
}
fn poll_write_vectored(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[io::IoSlice<'_>],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.0).poll_write_vectored(cx, bufs)
}
fn is_write_vectored(&self) -> bool {
self.0.is_write_vectored()
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_shutdown(cx)
}
}
+68 -1
View File
@@ -148,8 +148,14 @@ pub struct Bookmark {
/// Identity to connect with (`IdentityEntry::id`).
pub identity: Option<i64>,
pub default_channel: Option<String>,
/// `wss://` URL of a companion gateway, for invisible presence and relay chat.
/// The companion gateway in use (`wss://` or `ws://`), for invisible
/// presence and relay chat: the one that last logged in, else the best
/// published one, else one typed into an older version.
pub gateway_url: Option<String>,
/// Every URL the server publishes for its gateway, best first: tried in
/// this order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub gateway_urls: Vec<String>,
/// Own ServerQuery credentials (the password is kept in [`crate::Secrets`]).
pub query: Option<QueryConfig>,
/// Signed client version to present (`voelinctl versions` spec), `None` for the default.
@@ -168,6 +174,37 @@ pub struct CachedServerIcon {
}
impl Bookmark {
/// The gateways to try, best first: those published, else the one kept.
pub fn gateways(&self) -> Vec<String> {
if self.gateway_urls.is_empty() {
self.gateway_url.iter().cloned().collect()
} else {
self.gateway_urls.clone()
}
}
/// Discovery found `urls` (best first, not empty); true if what is tried
/// changed. The one in use stays if it is still published.
pub fn set_gateways(&mut self, urls: Vec<String>) -> bool {
if self.gateway_urls == urls {
return false;
}
if !self.gateway_url.as_ref().is_some_and(|url| urls.contains(url)) {
self.gateway_url = urls.first().cloned();
}
self.gateway_urls = urls;
true
}
/// The gateway logged in at `url`; true if the one in use changed.
pub fn gateway_in_use(&mut self, url: &str) -> bool {
if self.gateway_url.as_deref() == Some(url) || !self.gateways().iter().any(|u| u == url) {
return false;
}
self.gateway_url = Some(url.to_owned());
true
}
pub fn server_icon_id(&self) -> Option<u32> {
self.cached_server_icon
.as_ref()
@@ -605,6 +642,36 @@ mod tests {
assert_eq!(b.server_password_key(), format!("bookmark/{}/server-password", b.id));
}
#[test]
fn published_gateways_are_kept_with_the_one_in_use() {
let store = Store::open_in_memory().unwrap();
// From an older version: one URL, no list.
let mut b = Bookmark {
address: "ts.example.org".into(),
gateway_url: Some("ws://127.0.0.1:7788/v1".into()),
..Default::default()
};
b.id = store.add_bookmark(&b).unwrap();
assert_eq!(b.gateways(), ["ws://127.0.0.1:7788/v1"]);
let published =
vec!["wss://gw.example.org/v1".to_owned(), "ws://ts.example.org:7788/v1".into()];
assert!(b.set_gateways(published.clone()));
assert!(!b.set_gateways(published.clone()), "unchanged");
// The old one is not published: the best published one is in use.
assert_eq!(b.gateway_url.as_deref(), Some("wss://gw.example.org/v1"));
assert_eq!(b.gateways(), published);
// The plain one logged in; one that is not published never counts.
assert!(b.gateway_in_use("ws://ts.example.org:7788/v1"));
assert!(!b.gateway_in_use("ws://ts.example.org:7788/v1"));
assert!(!b.gateway_in_use("ws://elsewhere.test/v1"));
store.update_bookmark(&b).unwrap();
let reloaded = store.bookmarks().unwrap().remove(0);
assert_eq!(reloaded, b);
// Still published: the one in use stays.
b.set_gateways(vec!["ws://ts.example.org:7788/v1".into()]);
assert_eq!(b.gateway_url.as_deref(), Some("ws://ts.example.org:7788/v1"));
}
#[test]
fn bookmark_icons_survive_reload_and_are_bound_to_the_server_address() {
let store = Store::open_in_memory().unwrap();
+5 -1
View File
@@ -23,7 +23,7 @@ dirs = "6"
# Slint decodes pictures with `image`, which it builds with PNG and JPEG only;
# avatars, icons and banners on TeamSpeak servers are GIF and WebP too (the
# decoders are in the tree already, for SVG pictures).
image = { version = "0.25", default-features = false, features = ["gif", "webp"] }
image = { version = "0.25", default-features = false, features = ["gif", "webp", "bmp", "ico"] }
# Twemoji archive blocks (raw deflate); already used by png.
miniz_oxide = "0.8"
png = "0.18"
@@ -69,5 +69,9 @@ voelin-core = { path = "../voelin-core", default-features = false, features = ["
[build-dependencies]
slint-build = "1.18"
[dev-dependencies]
# Certificates and signatures from a synthetic root for the account tests.
voelin-myts = { path = "../voelin-myts", features = ["testing"] }
[lints]
workspace = true
+7 -4
View File
@@ -1227,6 +1227,9 @@ impl App {
self.history_batch(session as i64, &target, messages, source, complete);
}
Event::Gateway { session, update } => {
if let voelin_core::gateway::GatewayUpdate::Connected { url, .. } = &update {
self.gateway_in_use(session as i64, url);
}
self.gateway_extra(session as i64, &update);
self.gateway_update(session as i64, update);
}
@@ -1248,8 +1251,8 @@ impl App {
// Pictures can arrive after the rows were built: draw them again.
Event::AvatarReady { session, client_uid, path, .. } => {
let view = self.sessions.entry(session as i64).or_default();
// A file that arrives again is decoded again.
crate::images::forget(&path);
// A file that arrives again is decoded again if it changed.
crate::images::reloaded(&path);
view.avatars.insert(client_uid, path);
if self.current == Some(session as i64) {
self.refresh_tree();
@@ -1261,7 +1264,7 @@ impl App {
}
Event::IconReady { session, icon, path } => {
let view = self.sessions.entry(session as i64).or_default();
crate::images::forget(&path);
crate::images::reloaded(&path);
view.icons.insert(icon, path);
self.refresh_servers();
if self.current == Some(session as i64) {
@@ -1272,7 +1275,7 @@ impl App {
Event::PictureReady { session, url, path } => {
let view = self.sessions.entry(session as i64).or_default();
// The host banner reloads into the same file.
crate::images::forget(&path);
crate::images::reloaded(&path);
view.pictures.insert(url, path);
if self.current == Some(session as i64) {
self.refresh_toolbar();
+3
View File
@@ -25,6 +25,9 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_myts_portal(|action| {
with_app(|app| app.myts_portal(action));
});
bridge.on_myts_badge(|index, on| {
with_app(|app| app.myts_badge(index, on));
});
}
bridge.on_open_settings(|| {
with_app(|app| app.open_settings());
+15 -1
View File
@@ -79,7 +79,8 @@ use voelin_model::{
use voelin_store::{Bookmark, MessageSource};
use crate::app::{
App, Bridge, MainWindow, MobileTab, Nav, Page, RecordingItem, SettingsSection, with_app,
App, Bridge, MainWindow, MobileTab, MytsBadge, Nav, Page, RecordingItem, SettingsSection,
with_app,
};
use crate::settings::LastVoice;
@@ -212,6 +213,17 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
))
};
account.badges = strings(&["TeamSpeak 6 Beta", "Early supporter"]);
// Signed for servers: the first shown, the second not.
let badge = |name: &str, shown| MytsBadge {
name: name.into(),
shown,
can_change: true,
};
account.badge_choice = slint::ModelRc::new(slint::VecModel::from(vec![
badge("TeamSpeak 6 Beta", 1),
badge("Early supporter", 0),
]));
account.user_tag = "alex@myteamspeak.com".into();
account.devices =
strings(&["Voelin · EU · 2026-10-03", "TeamSpeak · EU · 2026-09-28"]);
nav.invoke_open_settings(SettingsSection::Account);
@@ -520,6 +532,7 @@ fn demo_ui(app: &mut App) {
identity: None,
default_channel: None,
gateway_url: None,
gateway_urls: Vec::new(),
query: None,
client_version: None,
cached_server_icon: None,
@@ -667,6 +680,7 @@ fn demo_ui(app: &mut App) {
Event::Gateway {
session,
update: GatewayUpdate::Connected {
url: "wss://gw.nightfall.example/v1".into(),
gateway_id: "demo".into(),
server_uid: "demo-server".into(),
server_name: "Nightfall Guild".into(),
+131 -42
View File
@@ -93,7 +93,17 @@ fn svg_cost(svg_len: usize) -> usize {
}
thread_local! {
static CACHE: RefCell<Lru<Image>> = RefCell::new(Lru::new(64 << 20));
static CACHE: RefCell<Lru<Image>> = RefCell::new(Lru::new(256 << 20));
/// What each file decoded held (its length and a hash of its bytes), so
/// one that arrives again unchanged is not decoded again.
static DECODED: RefCell<HashMap<String, (usize, u64)>> = RefCell::new(HashMap::new());
}
fn fingerprint(bytes: &[u8]) -> (usize, u64) {
use std::hash::{DefaultHasher, Hasher};
let mut hasher = DefaultHasher::new();
hasher.write(bytes);
(bytes.len(), hasher.finish())
}
/// Set the budget in megabytes.
@@ -124,56 +134,110 @@ pub fn file(path: &std::path::Path) -> Image {
// (`avatars/<md5>`, `icons/<id>`), and servers keep PNG, JPEG
// and SVG icons alike.
let bytes = std::fs::read(path).ok()?;
DECODED.with(|d| d.borrow_mut().insert(key.to_string(), fingerprint(&bytes)));
// One that cannot be shown (too large, not a picture) is
// remembered as such, not read again on every refresh; a
// changed file is forgotten first (`forget`).
// changed file is forgotten first (`reloaded`).
Some(decode(&bytes).unwrap_or((Image::default(), UNDECODABLE_COST)))
})
})
.unwrap_or_default()
}
/// Forget the decoded picture of a file that changed (a reloaded banner).
pub fn forget(path: &std::path::Path) {
CACHE.with(|c| c.borrow_mut().remove(&path.to_string_lossy()));
/// A file that arrived again (a reloaded banner, an avatar fetched again):
/// its decoded picture is forgotten if it changed, so it is decoded again.
pub fn reloaded(path: &std::path::Path) {
let key = path.to_string_lossy();
let now = std::fs::read(path).ok().map(|bytes| fingerprint(&bytes));
let decoded = DECODED.with(|d| d.borrow().get(key.as_ref()).copied());
if now.is_none() || now != decoded {
DECODED.with(|d| d.borrow_mut().remove(key.as_ref()));
CACHE.with(|c| c.borrow_mut().remove(&key));
}
}
/// The largest side a raster picture keeps: larger ones (a banner made for
/// print) are scaled down when decoded, as nothing shows them larger.
const MAX_SIDE: u32 = 4096;
/// A picture with more pixels than this (RGBA bytes) is not decoded at all:
/// it is decoded and scaled down on the UI thread.
const MAX_DECODED_BYTES: u64 = 128 << 20;
/// Compressed pictures can be small on disk but huge when decoded. Check
/// raster dimensions before Slint allocates pixels on the UI thread. SVGs
/// keep Slint's native vector loader and are rasterized at the displayed size.
fn decode(bytes: &[u8]) -> Option<(Image, usize)> {
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let cost = if reader.format().is_some() {
let (width, height) = reader.into_dimensions().ok()?;
// At most the default decoded-image cache (64 MiB of RGBA).
if width == 0
|| height == 0
|| width > 16_384
|| height > 16_384
|| u64::from(width) * u64::from(height) * 4 > 64 << 20
{
tracing::debug!(width, height, "image exceeds the decoded raster size limit");
if reader.format().is_none() {
// As the engine tells one when it downloads it.
if !voelin_core::is_svg(bytes) {
return None;
}
width as usize * height as usize * 4
} else {
let start = bytes.trim_ascii_start();
if !start.starts_with(b"<svg") && !start.starts_with(b"<?xml") {
return None;
}
// Intrinsic SVG dimensions describe coordinates, not an allocated
// pixel buffer. Use the same vector cost as the emoji cache.
return Image::load_from_svg_data(start).ok().map(|image| (image, svg_cost(bytes.len())));
}
let format = reader.format();
let (width, height) = match reader.into_dimensions() {
Ok(size) => size,
Err(error) => {
tracing::warn!(?format, %error, "picture not shown: unreadable");
return None;
}
};
Image::load_from_data(bytes, None).ok().map(|image| (image, cost))
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
tracing::warn!(width, height, "picture not shown: too large to decode");
return None;
}
if width <= MAX_SIDE && height <= MAX_SIDE {
let cost = width as usize * height as usize * 4;
return match Image::load_from_data(bytes, None) {
Ok(image) => Some((image, cost)),
Err(error) => {
tracing::warn!(?format, %error, "picture not shown: not decoded");
None
}
};
}
// Scaled down (the first frame of an animation). 16 bits a channel
// take twice the bytes.
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20));
reader.limits(limits);
let full = match reader.decode() {
Ok(full) => full,
Err(error) => {
tracing::warn!(?format, width, height, %error, "picture not shown: not decoded");
return None;
}
};
let small = full.thumbnail(MAX_SIDE, MAX_SIDE);
drop(full);
let small = small.into_rgba8();
let (width, height) = small.dimensions();
let pixels = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(
small.as_raw(),
width,
height,
);
Some((Image::from_rgba8(pixels), width as usize * height as usize * 4))
}
/// A picture from encoded bytes (PNG, JPEG, GIF, WebP), decoded once and
/// kept by `key`; an empty image if it cannot be decoded.
/// kept by `key`; an empty image if it cannot be decoded (remembered too,
/// until [`forget_picture`]).
pub fn picture(key: &str, bytes: &[u8]) -> Image {
let cache_key = format!("picture:{key}");
CACHE.with(|c| c.borrow_mut().get_or_load(&cache_key, || decode(bytes))).unwrap_or_default()
CACHE
.with(|c| {
c.borrow_mut().get_or_load(&cache_key, || {
Some(decode(bytes).unwrap_or((Image::default(), UNDECODABLE_COST)))
})
})
.unwrap_or_default()
}
/// Forget the decoded picture kept by `key` (a changed account avatar).
@@ -246,6 +310,10 @@ mod tests {
encoder.write_header().unwrap().write_image_data(&[200; 32]).unwrap();
assert_eq!(picture("test:4x2", &png).size().width, 4);
assert_eq!(picture("test:junk", b"not a picture").size().width, 0);
// Remembered: not decoded (and warned about) on every refresh.
assert_eq!(picture("test:junk", &png).size().width, 0);
forget_picture("test:junk");
assert_eq!(picture("test:junk", &png).size().width, 4);
}
#[test]
@@ -264,9 +332,29 @@ mod tests {
}
#[test]
fn oversized_rasters_are_refused_before_pixels_are_read() {
fn svg_after_a_comment_or_doctype_decodes() {
let svg = b"<!-- tool --><!DOCTYPE svg><svg xmlns='http://www.w3.org/2000/svg' width='8' height='4'><rect width='8' height='4'/></svg>";
assert_eq!(picture("test:svg-prolog", svg).size().width, 8);
assert!(decode(b"<!-- a page --><html></html>").is_none());
// A page with an SVG in it is a page (told so by the engine).
assert!(decode(b"<!DOCTYPE html><html><svg/></html>").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"));
}
}
+6
View File
@@ -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()
+3 -6
View File
@@ -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);
+757 -3
View File
@@ -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<u8>,
avatar: Vec<u8>,
/// What myTeamSpeak's avatar service hands out for the account's myTS
/// ID ([`OwnAvatar`]): no password needed.
#[serde(default)]
service_certificate: Vec<u8>,
#[serde(default)]
service_avatar: Vec<u8>,
/// The account's badges as signed for its myTS ID (`SignedUserBadge`s).
#[serde(default)]
badges: Vec<Vec<u8>>,
/// The primary User Tag, and the token that proves it.
#[serde(default)]
user_tag: String,
#[serde(default)]
user_tag_token: Vec<u8>,
}
/// What asking myTeamSpeak again learned; `None`: nothing (an empty or
/// failed answer), and what was known stays.
#[derive(Default)]
struct Fetched {
avatar: Option<OwnAvatar>,
badges: Option<Vec<SignedBadge>>,
user_tag: Option<String>,
/// Checked for the tag before it is taken.
user_tag_token: Option<Vec<u8>>,
}
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<SignedBadge> {
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<Saved>,
/// What servers can be shown of the account: from a password sign-in,
/// and from myTeamSpeak with the session alone.
presentation: Option<SavedPresentation>,
/// The ids of the badges chosen to show on servers, in order.
shown_badges: Vec<String>,
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<PathBuf> {
self.dir.as_ref().map(|dir| dir.join(PRESENTATION_FILE))
}
fn badges_path(&self) -> Option<PathBuf> {
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::<SavedPresentation>(&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<String, Vec<String>> {
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<String> = 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<SignedBadge> {
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<tsclientlib::MytsData> {
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<tsclientlib::MytsData> {
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::<Vec<_>>(),
))
};
let signed = self.presentation.as_ref().map(SavedPresentation::signed_badges);
let chosen: Vec<String> = 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::<Vec<_>>();
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<u8> {
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::<Vec<_>>()
};
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::<Vec<_>>()
};
assert_eq!(names(&account), ["b0", "b2"]);
let choice = |account: &Account| {
account.form().badge_choice.iter().map(|b| (b.shown, b.can_change)).collect::<Vec<_>>()
};
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<SignedBadge> = 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]
+107 -23
View File
@@ -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<String>, 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::<Vec<_>>();
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));
}
}
+2 -2
View File
@@ -87,8 +87,8 @@ pub static UI_NARROW_BREAKPOINT: Key<u32> = Key::new(
pub static UI_IMAGE_CACHE_MB: Key<u32> = 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
+14
View File
@@ -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;
+46 -2
View File
@@ -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 {