Merge PR #10: UI review, and the fixes from its section 1

Brings the UI review (docs/research/ui-review.md), the fixes from its
section 1 and PR #11 (myTeamSpeak avatar, badges and User Tag; banners;
gateway speed and logs) into main before the repository split.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5.1 committed 2026-10-13 18:27:57 +03:00
commit 2d375fd6e4
165 files changed
+21350 -3254

No files matched your search

+13 -3
View File
@@ -3,13 +3,23 @@ name: CI
# Linux checks for Gitea act_runner; runner setup and scope: docs/ci.md.
# Off for pushes and pull requests: run by hand only.
on:
push:
branches: ["main"]
paths:
- "**"
- "!docs/**"
- "!**/*.md"
- "THIRD_PARTY_NOTICES.md"
pull_request:
paths:
- "**"
- "!docs/**"
- "!**/*.md"
- "THIRD_PARTY_NOTICES.md"
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
CARGO_BUILD_JOBS: "1"
CARGO_INCREMENTAL: "0"
RUST_BACKTRACE: "0"
jobs:
linux:
+1 -1
View File
@@ -84,7 +84,7 @@ jobs:
run: |
set -euo pipefail
mkdir -p dist/release
for file in dist/{linux,windows,android,flatpak,gateway}/*; do
for file in dist/{linux,windows,android,gateway}/*; do
[[ -f "$file" && ! -L "$file" ]] || { echo "Missing package: $file" >&2; exit 1; }
name=$(basename "$file")
[[ "$name" != SHA256SUMS* ]] || continue
+13
View File
@@ -20,6 +20,12 @@ permissions:
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: "0"
# GitHub's runners have 16 GB: the generated UI library does not fit
# in that next to other crates, and the runner is killed. The Gitea
# workflow keeps Cargo's default job count. The Flatpak job sets it in
# the manifest too.
CARGO_BUILD_JOBS: "1"
CARGO_INCREMENTAL: "0"
jobs:
package-linux:
@@ -108,6 +114,13 @@ jobs:
python3 -m venv /tmp/venv
/tmp/venv/bin/pip install --quiet "aiohttp>=3.9.5,<4" "tomlkit>=0.13.3,<1" "PyYAML>=6.0.2,<7"
/tmp/venv/bin/python /tmp/flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json
# flatpak-builder does not pass the job's environment into its sandbox,
# and the manifest keeps Cargo's default job count for Gitea: one job
# here, as for the other packages.
- name: One Cargo job
run: |
sed -i 's/^ CARGO_NET_OFFLINE: "true"$/&\n CARGO_BUILD_JOBS: "1"/' packaging/flatpak/io.github.faumaray.Voelin.yml
grep -q '^ CARGO_BUILD_JOBS: "1"$' packaging/flatpak/io.github.faumaray.Voelin.yml
- uses: flatpak/flatpak-github-actions/flatpak-builder@v6
with:
bundle: voelin.flatpak
+168
View File
@@ -21,6 +21,66 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
decoders work without installing FFmpeg.
- AV1 decoding through dav1d in every desktop build.
- 122 more signed client versions (`Versions.csv`).
- Icon buttons show their name on hover (desktop), also while they are
disabled.
- The voice channel view on desktop can copy an invite link to the channel,
as the phone's Invite button does.
- Other people's myTeamSpeak badges: up to three pictures after their name
in the channel tree and the members panel, and their names on the member
card (what each is for on hover). On TeamSpeak 6 the badges the server
verified come first, the ones you chose in Settings → My Account
included.
- Links in chat open in the browser; one whose text is not its address
first shows where it goes. A right-click on a link opens or copies it.
- `ts3server://` and `teamspeak://` links in chat (and `tmspk.gg/s/…`)
open the server dialog filled in from the link, its channel and key
included, or move you into the link's channel when you are in voice on
that server. Nothing connects before Connect, and a saved server keeps
its nickname. `tmspk.gg` invite codes can't be opened yet.
- Every message can be quoted into the composer (`> ` lines) and its text
copied, from the actions on hover or a right-click menu, also on servers
without a gateway.
- A "New" line above the first unread message of a chat, and a bar that
counts the new messages with a jump to the first; unread counts survive
restarts. Messages count as read only while their chat is on screen in
the focused window.
- Other users' myTeamSpeak avatars (TeamSpeak 6), as the official client
shows them: where the server has no avatar of them, its avatar could not
be downloaded, or the server is only observed.
- Voice connections show servers the account's avatar, the badges chosen
in Settings → My Account (up to three) and its User Tag, as the official
client does, so other TeamSpeak 6 users see them; again after a
reconnect or an account change, and cleared on sign-out. A saved session
is enough: the avatar, its certificate, the signed badges and the User
Tag's token come from myTeamSpeak's services, and Voelin checks each
signature as the server does before sending it. The log says what the
server published.
- Settings → My Account shows the account's User Tag and lets you choose the
badges servers show.
- Pictures (banners, avatars) go through the desktop's proxy where the
desktop portal names one (Linux), and through the system proxy on
Windows and macOS; SOCKS proxies work too.
- tsgw logs what it does: a startup summary, the address the TeamSpeak
server sees for its queries (with a hint when that address is not
allowlisted), every app connection with its logins and how long they
took, refused logins, slow requests, ServerQuery failures, relays and the
observer. `log.level` (`TSGW_LOG_LEVEL`) sets what is logged, `log.file`
(`TSGW_LOG_FILE`) also writes to a file that is rotated at 20 MB (five
kept); colour only on a terminal.
- Every gateway a server publishes is tried in turn (TLS first, 20 seconds
each) before waiting to try again, so a TLS proxy that fails falls back to
the plain gateway published next to it.
- A call bar on the desktop's voice channel page: mute, deafen, share, the
voice settings and Leave, under the people and streams (Voice Settings
and Leave left the header). A smaller stage, one row of people and the
streams as rows, leaves about 200 px more for the chat; it is remembered,
and windows under 800 px tall always have it.
- A theatre mode for streams: the stream viewer's new button fills the
window with the stream and its chat, without the servers, the channels
and the members. Escape leaves it, and full screen too.
- Streams pop out into a window of their own on the desktop, optionally
kept on top of other windows, while the main window goes on; closing it
brings the stream back.
### Changed
@@ -48,11 +108,119 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
- A server's published gateway replaces one stored before (found or typed
into an older version), so a gateway that moved is followed.
- zbus's warnings about desktop portal requests are left out of the logs.
- Pop-ups, menus and tooltips have a clearer edge, and the member card, the
emoji picker and the notifications panel dim the window behind them.
- Double-clicking a channel of a server without voice connects into it
(it said "not connected with voice").
- Older chat messages load when scrolling up, above the messages on screen,
which stay in place; the Older messages button remains for a chat that
fits on the screen.
- One dialog adds a server, with Save and Connect (Enter connects).
Connect connects only a server it saved (Join connected the server shown
before when saving failed).
- A slimmer top bar on desktop: only the search and the bell. The bell's
panel opens under the bell and is as tall as its notices; the members
button is in the voice channel's header (as in the chat's), About in
Settings. The user card has no settings gear (the rail's stays); its
avatar and name open your account.
- Home shows where you left off (the last voice channel, joined in one
click) and your unread mentions; the welcome banner shows only before the
first server. Friends show once, the quick actions are gone, and the
sidebar lists your recent private chats.
- Each server has a colour of its own (two often shared a blue), and small
server icons are drawn sharp at twice their size instead of stretched.
Small avatars, as in the channel tree, show one letter.
- Channels have one icon everywhere, the speaker, and are named without a
`#` in tabs and elsewhere.
- The members panel shows a hand on those who need talk power to speak,
instead of everyone's talk power as a bare number (the member card still
has it).
- The chat header's pinned messages and topics are icon buttons with a
count, so the channel's topic has room.
- Private chats live on the Direct Messages page, not in the server's chat
tabs, and their unread messages count there (on the phone, on the Home
tab) instead of on the server rail.
- Stream cards show the streamer: their avatar on a painted scene in their
colour, with what they share, instead of a bare screen icon (TeamSpeak
streams have no preview pictures). Your own stream from the Stream Studio
shows its picture.
- The stream viewer's controls hide while you watch, 2.5 s after the
pointer last moved over the picture (in full screen the cursor too; on a
touch screen a tap shows or hides them), and the streamer, the title and
LIVE are in the header above the picture instead of over it.
- The phone's voice screen has one header: the top bar shows the channel on
its banner, the server below it instead of the channel's topic, and Back;
Leave is only in the bottom bar. Pinned messages and topics are in the
More menu and the row of people is smaller, so the chat has about 130 px
more room. With push-to-talk, Hold to talk is the bottom bar's middle
button instead of the microphone button by the composer; Go Live and
Share are one Share button that opens the share menu (a screen, or the
Stream Studio) as on desktop. The microphone button says Mic on or Mic
off.
- The phone's Servers tab is titled Servers; the server's name and counts
are only in the server card below the server icons, no longer in the top
bar too. The voice card shows only your channel, on desktop too.
- Banners: up to 128 MiB, more time on slow hosts, BMP and ICO too, and
SVG after a comment or DOCTYPE; pictures larger than 4096 pixels on a
side are scaled down. A banner that fails is tried again for as long as
it is shown (every 15 minutes at most), and the log says why it is
missing (HTTP status, an HTML page, a video, too large). The picture
cache defaults to 1 GiB, the decoded images to 256 MB.
- Banners that fail: the log names the URL (without its query) the first
time, says when a connection stalled and after how much data, and when it
could not connect at all. A banner that is not there (HTTP 400, 404, 410)
is tried again after 15 minutes and then hourly; a host that asks to wait
(429, 503) is waited for. A banner shown again is only checked for
changes (ETag, Last-Modified), not downloaded again. At most 6 downloads
run per host, so a slow host cannot hold up the others.
- The gateway: only a refused login stops observing; anything else is tried
again after 1, 2, 5, 10, 20, then every 30 seconds, and at once when voice
connects. A connection that stops answering is noticed within 90 seconds.
Finding a server's gateway asks DNS and the gateway at once instead of one
after the other. The log says what was found, which gateway was tried,
how long each step took and why one failed.
- tsgw answers faster: each ServerQuery command takes under 2 ms instead of
about 45 ms (TCP_QUICKACK), so logins and startup take milliseconds.
TeamSpeak's flood protection is shared by all of tsgw's query
connections, so tsgw no longer earns a 600 second ban. It starts while
the TeamSpeak server is still down and connects once it is up, its
`/health` says what is missing, and it stops cleanly on SIGTERM.
### Fixed
- The account's avatar is downloaded from its own link; it was asked for
as an upload link and refused with HTTP 403.
- Hover help in the Stream Studio (a source's error, the status details)
shows each time and closes when the pointer leaves; it showed only once,
and stayed open until a click.
- Spacer channels: `[spacer]`, `[lspacer]`, `[rspacer]` and `[*spacer]` lines
are drawn as TeamSpeak draws them, like `[cspacer]` was, and chats, search
results, notifications and the other screens show a spacer's text instead
of its raw name.
- Locked channels ask for their password (kept until voice disconnects, and
asked again when it is wrong), and joining a full channel or one the
server refuses says why; joining did nothing before.
- Pokes can carry a message (up to 100 characters); they were always sent
empty.
- While a priority speaker talks, everyone else (watched streams too) is
dimmed by the server's setting, as in TeamSpeak; nobody was dimmed before.
- BBCode from other clients shows as formatting (bold, colours, links,
quotes, lists, code, pictures) instead of raw tags, and the server's
welcome message opens the server chat. Messages with emoji keep their
line breaks.
- Joining a friend in a subchannel of a server without voice connects into
that subchannel; it connected into the default channel.
- Closing a chat tab left of the selected one keeps the selected chat; the
one after it was selected.
- Connecting with voice from a private chat (Direct Messages) keeps that
conversation open; it turned into the voice channel's chat, and the
composer sent there.
- Observing no longer stops for the whole run the first time a server is
joined with a new identity (the gateway did not know it yet).
- tsgw reconnects its query connection for logins when the TeamSpeak server
restarts; before, every login was refused until tsgw was restarted.
- Push-to-talk controls (Hold to talk) showed in voice activation and
continuous mode until the settings had been opened once.
## [0.0.1-alpha] - 2026-10-04
Generated
+11
View File
@@ -3534,9 +3534,11 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -7869,6 +7871,7 @@ dependencies = [
"i-slint-backend-android-activity",
"i-slint-backend-linuxkms",
"i-slint-backend-selector",
"i-slint-backend-winit",
"i-slint-common",
"i-slint-core",
"i-slint-core-macros",
@@ -9692,9 +9695,13 @@ version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"bytes",
"dirs",
"futures",
"h2",
"hickory-resolver",
"http",
"httpdate",
"md5",
"reqwest",
"rusqlite",
@@ -9826,9 +9833,11 @@ dependencies = [
"aes-gcm",
"base64 0.22.1",
"ctr 0.10.1",
"curve25519-dalek 4.1.3",
"pbkdf2",
"reqwest",
"schema-api",
"sha2 0.10.9",
"subtle",
"thiserror 2.0.21",
"tokio",
@@ -9862,6 +9871,7 @@ dependencies = [
"tracing",
"windows 0.62.2",
"x11rb",
"zbus",
]
[[package]]
@@ -9872,6 +9882,7 @@ dependencies = [
"russh",
"serde",
"serde_json",
"socket2",
"thiserror 2.0.21",
"tokio",
"tracing",
+18
View File
@@ -129,3 +129,21 @@ against or offered back to upstream.
Tests cover an independent signature vector, persistence validation/redaction,
wire field names, clearing and reconnect snapshot replacement. The account
UUID and the ordinary server identity remain separate.
15. **myTeamSpeak presentation, TeamSpeak 6** (`tsproto/src/license.rs`,
`tsproto/src/myts.rs`, `tsclientlib/src/myts.rs`, `tsclientlib/src/lib.rs`,
`tsproto-packets/src/packets.rs`, `tsproto-structs/declarations/Book.toml`).
License block types 4–7 (Token, License_Sign, MyTsId_Sign, Updater), which
carry nothing after the header. `myts::Certificate` checks a myTeamSpeak
certificate chain as a TeamSpeak 6 server does: leaf type, validity window,
key derived from a given root, cofactorless Ed25519 with a reduced S;
`Identity::id_bytes` and `public_signature_certificate`. `MytsData` holds the
avatar and the badges, each with the certificate that verifies it, and the
User Tag; `MytsData::updates` builds `updatemytsdata` (split by certificate,
bare parameters to clear) and `clientupdate client_user_tag`, which
`Connection::send_myts_update` and `send_user_tag` send. The escaped writer
also escapes `\a` and `\b`, as TeamSpeak does for binary values. Book:
`Client::my_team_speak_avatar`, `my_team_speak_id` and `signed_badges`.
16. **Privilege key when connecting** (`tsclientlib/src/lib.rs`, "Voelin patch").
`ConnectOptions::default_token` sets `client_default_token` of `clientinit`,
which upstream always sent empty, so a privilege key (a bookmark's, or the
`token=` of a `ts3server://` link) can be used on connect.
+22 -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.
@@ -392,6 +393,7 @@ impl Connection {
channel: None,
channel_password: None,
password: None,
default_token: None,
input_muted: false,
output_muted: false,
input_hardware_enabled: true,
@@ -556,7 +558,7 @@ impl Connection {
version_sign: Cow::Borrowed(client_version_sign.as_ref()),
client_key_offset: counter,
phonetic_name: "".into(),
default_token: "".into(),
default_token: Cow::Borrowed(options.default_token.as_deref().unwrap_or_default()),
hardware_id: Cow::Borrowed(options.hardware_id.as_ref()),
badges: None,
signed_badges: None,
@@ -1730,6 +1732,7 @@ pub struct ConnectOptions {
channel: Option<Cow<'static, str>>,
channel_password: Option<Cow<'static, str>>,
password: Option<Cow<'static, str>>,
default_token: Option<Cow<'static, str>>,
input_muted: bool,
output_muted: bool,
input_hardware_enabled: bool,
@@ -1944,6 +1947,20 @@ impl ConnectOptions {
self
}
/// Use a privilege key (token) when connecting.
/// Voelin patch: sent as `client_default_token` in `clientinit`.
///
/// # Example
/// ```
/// # use tsclientlib::Connection;
/// let opts = Connection::build("localhost").default_token("My privilege key");
/// ```
#[inline]
pub fn default_token<S: Into<Cow<'static, str>>>(mut self, token: S) -> Self {
self.default_token = Some(token.into());
self
}
/// Connect to the server in a muted state.
///
/// # Example
@@ -2064,6 +2081,10 @@ impl ConnectOptions {
#[inline]
pub fn get_password(&self) -> Option<&str> { self.password.as_ref().map(AsRef::as_ref) }
#[inline]
pub fn get_default_token(&self) -> Option<&str> {
self.default_token.as_ref().map(AsRef::as_ref)
}
#[inline]
pub fn get_input_muted(&self) -> bool { self.input_muted }
#[inline]
pub fn get_output_muted(&self) -> bool { self.output_muted }
+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());
}
}
+8 -5
View File
@@ -13,7 +13,7 @@ use std::sync::Arc;
use voelin_core::stream::{StreamState, ViewerInfo, ViewerState};
use voelin_core::{Event, SessionId, VoiceState};
use voelin_model::Presence;
use voelin_model::{Presence, channel_title};
/// What the voice notification shows.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -72,13 +72,13 @@ impl Session {
self.name.as_deref().unwrap_or("a server")
}
/// Our channel's name and how many are in it.
/// Our channel's name (a spacer's text) and how many are in it.
fn channel(&self) -> Option<(&str, usize)> {
let id = self.own_channel?;
let channel = self.presence.channels.get(&id)?;
let people =
self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count();
Some((channel.name.as_str(), people))
Some((channel_title(channel).0, people))
}
}
@@ -222,8 +222,11 @@ mod tests {
fn presence(people: u16) -> Event {
let mut p = Presence::default();
p.channels
.insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() });
// A spacer shows its text.
p.channels.insert(
2,
ChannelInfo { id: 2, name: "[cspacer1]Chill Zone".into(), ..Default::default() },
);
for id in 1..=people {
p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() });
}
+224 -8
View File
@@ -1,5 +1,6 @@
//! Incoming voice: per-client jitter buffer, decoder and mixer, with a
//! volume and mute per client.
//! volume and mute per client, and everyone else dimmed while a priority
//! speaker talks.
//!
//! The jitter buffer is the vendored `tsclientlib::audio::AudioHandler`. Per
//! sender it keeps a queue of Opus packets and adapts its length:
@@ -24,16 +25,44 @@ use tsclientlib::ClientId;
use tsclientlib::audio::{AudioHandler, Error as QueueError};
use tsproto_packets::packets::InAudioBuf;
use crate::pcm::FRAME_SAMPLES;
/// Loudest per-client volume: +12 dB.
pub const MAX_CLIENT_VOLUME: f32 = 4.0;
/// Most a priority speaker dims the others (dB).
const MAX_DIMM_DB: f32 = -60.0;
/// The dimming for a priority speaker fades in and out over this many
/// samples (5 frames, 100 ms) instead of jumping.
const DIMM_RAMP_SAMPLES: usize = 5 * FRAME_SAMPLES;
/// Jitter buffer, decoder and mixer for incoming voice, keyed by sender.
/// Output is interleaved stereo at 48 kHz.
#[derive(Default)]
pub struct Mixer {
handler: AudioHandler<ClientId>,
volumes: HashMap<ClientId, f32>,
muted: HashSet<ClientId>,
/// While one of them talks, everyone else is dimmed.
priority: HashSet<ClientId>,
/// Linear gain of the others while a priority speaker talks (1: none).
dimm: f32,
/// How far the dimming has faded in (0..=1).
fade: f32,
/// The others' mix while the dimming fades (reused).
others: Vec<f32>,
}
impl Default for Mixer {
fn default() -> Self {
Self {
handler: AudioHandler::new(),
volumes: HashMap::new(),
muted: HashSet::new(),
priority: HashSet::new(),
dimm: 1.0,
fade: 0.0,
others: Vec::new(),
}
}
}
impl Mixer {
@@ -53,18 +82,63 @@ impl Mixer {
}
/// Add the next `buf.len() / 2` stereo frames of all talkers to `buf`
/// (not cleared first), each scaled by its volume. Returns the clients
/// that stopped talking.
/// (not cleared first), each scaled by its volume, and dimmed while a
/// priority speaker talks. Returns the clients that stopped talking.
pub fn fill_buffer(&mut self, buf: &mut [f32]) -> Vec<ClientId> {
for (id, queue) in self.handler.get_mut_queues() {
queue.volume = if self.muted.contains(id) {
let queues = self.handler.get_mut_queues();
// A priority speaker with a queue (talking or buffering) dims all
// other queues, streams too, unless we muted it.
let dim = queues.keys().any(|id| self.priority.contains(id) && !self.muted.contains(id));
let frames = buf.len() / 2;
let step = frames as f32 / DIMM_RAMP_SAMPLES as f32;
let from = self.fade;
self.fade = if dim { (from + step).min(1.0) } else { (from - step).max(0.0) };
let to = self.fade;
let dimm = self.dimm;
let gain = |fade: f32| 1.0 + (dimm - 1.0) * fade;
let fading = from != to;
// While fading, the others are mixed into a buffer of their own and
// ramped sample by sample; the priority speakers go straight to `buf`.
let mut priority = Vec::new();
for (id, queue) in queues {
// Muted talkers are still decoded so their queues stay in sync.
let volume = if self.muted.contains(id) {
0.0
} else {
self.volumes.get(id).copied().unwrap_or(1.0)
};
queue.volume = if self.priority.contains(id) {
if fading {
priority.push((*id, volume));
0.0
} else {
volume
}
} else if fading {
volume
} else {
volume * gain(to)
};
}
// Muted talkers are still decoded so their queues stay in sync.
self.handler.fill_buffer(buf)
if !fading {
return self.handler.fill_buffer(buf);
}
self.others.clear();
self.others.resize(buf.len(), 0.0);
let stopped = self.handler.fill_buffer_with_proc(&mut self.others, |id, samples| {
if let Some(&(_, volume)) = priority.iter().find(|(p, _)| p == id) {
for (out, s) in buf.iter_mut().zip(samples) {
*out += s * volume;
}
}
});
// From the last frame's gain to this one's.
for (i, (out, s)) in buf.chunks_exact_mut(2).zip(self.others.chunks_exact(2)).enumerate() {
let g = gain(from + (to - from) * (i + 1) as f32 / frames as f32);
out[0] += s[0] * g;
out[1] += s[1] * g;
}
stopped
}
/// Linear gain for one client, clamped to `0..=`[`MAX_CLIENT_VOLUME`].
@@ -99,6 +173,16 @@ impl Mixer {
self.muted.contains(&id)
}
/// The priority speakers, and how much everyone else is dimmed while
/// one of them talks: dB, clamped to -60..=0 (NaN: not at all).
/// Replaces the previous set; [`forget`](Self::forget) leaves it alone,
/// the caller sends a new set when the clients change.
pub fn set_priority(&mut self, clients: impl IntoIterator<Item = ClientId>, dimm_db: f32) {
self.priority = clients.into_iter().collect();
let db = if dimm_db.is_nan() { 0.0 } else { dimm_db.clamp(MAX_DIMM_DB, 0.0) };
self.dimm = 10f32.powf(db / 20.0);
}
/// Forget volume and mute of a client (e.g. it left the server; client
/// ids are reused).
pub fn forget(&mut self, id: ClientId) {
@@ -129,6 +213,8 @@ impl std::fmt::Debug for Mixer {
.field("talkers", &self.handler.get_queues().len())
.field("volumes", &self.volumes)
.field("muted", &self.muted)
.field("priority", &self.priority)
.field("dimm", &self.dimm)
.finish()
}
}
@@ -199,6 +285,136 @@ mod tests {
assert!(pcm::goertzel_power(tail, 500.0, SAMPLE_RATE) > 1e-4);
}
/// A priority speaker dims the other talker by the server's -18 dB, fading
/// in and out, but not itself, and not while we muted it.
#[test]
fn priority_speaker_dims_others() {
let (a, p) = (ClientId(3), ClientId(5));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone_a = pcm::sine(500.0, 4.0, 0.2);
let tone_p = pcm::sine(1300.0, 4.0, 0.2);
let frame = |tone: &[f32], i: u16| {
let at = i as usize * FRAME_SAMPLES;
tone[at..at + FRAME_SAMPLES].to_vec()
};
let mut mixer = Mixer::new();
mixer.set_priority([p], -18.0);
let (mut id_a, mut id_p) = (0u16, 0u16);
// `frames` frames with a talking and p too if `with_p`; returns the
// second half of the mix.
let mut play = |mixer: &mut Mixer, frames: u16, with_p: bool| {
let mut out = Vec::new();
for _ in 0..frames {
let fa = frame(&tone_a, id_a);
mixer
.handle_packet(a, packet(3, id_a, enc_a.encode_to_bytes(&fa).unwrap()))
.unwrap();
id_a += 1;
if with_p {
let fp = frame(&tone_p, id_p);
let data = enc_p.encode_to_bytes(&fp).unwrap();
mixer.handle_packet(p, packet(5, id_p, data)).unwrap();
id_p += 1;
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
}
out.split_off(out.len() / 2)
};
let power = |out: &[f32], f| pcm::goertzel_power(out, f, SAMPLE_RATE);
let db = |level: f32, full: f32| 10.0 * (level / full).log10();
let alone = play(&mut mixer, 30, false);
let full = power(&alone, 500.0);
assert!(full > 1e-4);
// The dimming fades in over 5 frames: 1/5 of the way after the first.
play(&mut mixer, 1, true);
assert!((mixer.fade - 0.2).abs() < 1e-6, "fade {}", mixer.fade);
let both = play(&mut mixer, 50, true);
let dimmed = db(power(&both, 500.0), full);
assert!((dimmed + 18.0).abs() < 1.0, "dimmed by {dimmed} dB");
let own = db(power(&both, 1300.0), full);
assert!(own.abs() < 1.0, "priority speaker at {own} dB");
// p stops: its queue ends after three lost frames, and a is back.
let after = play(&mut mixer, 40, false);
assert_eq!(mixer.talkers().collect::<Vec<_>>(), vec![a]);
assert_eq!(mixer.fade, 0.0);
let back = db(power(&after, 500.0), full);
assert!(back.abs() < 1.0, "after the priority speaker: {back} dB");
// A priority speaker we muted dims nobody.
mixer.set_muted(p, true);
let muted = play(&mut mixer, 40, true);
assert_eq!(mixer.talkers().count(), 2);
let level = db(power(&muted, 500.0), full);
assert!(level.abs() < 1.0, "muted priority speaker: {level} dB");
assert!(power(&muted, 1300.0) < 1e-6);
}
/// The dimming fades in and out sample by sample, not in a step per
/// frame: the other talker's level (per period of its tone) never jumps.
#[test]
fn priority_dimming_ramps_per_sample() {
let (a, p) = (ClientId(3), ClientId(5));
let mut enc_a = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut enc_p = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let tone = pcm::sine(500.0, 2.0, 0.2);
let mut mixer = Mixer::new();
mixer.set_priority([p], -18.0);
// p is not heard (volume 0) but dims, so the mix is a's tone alone.
mixer.set_volume(p, 0.0);
let mut out = Vec::new();
// p talks from frame 30 to 59.
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
let id = i as u16;
mixer.handle_packet(a, packet(3, id, enc_a.encode_to_bytes(frame).unwrap())).unwrap();
if let Some(j) = i.checked_sub(30).filter(|j| *j < 30) {
let data = enc_p.encode_to_bytes(frame).unwrap();
mixer.handle_packet(p, packet(5, j as u16, data)).unwrap();
}
let mut buf = vec![0.0; FRAME_SAMPLES * 2];
mixer.fill_buffer(&mut buf);
out.extend(pcm::to_mono(&buf, 2));
}
assert_eq!(mixer.fade, 0.0);
// The level per period of the 500 Hz tone (96 samples, 10 a frame).
let level: Vec<f32> = out.chunks_exact(96).map(|c| pcm::energy(c).sqrt()).collect();
let full = level[200..300].iter().sum::<f32>() / 100.0;
let mean = |range: std::ops::Range<usize>| {
level[range.clone()].iter().sum::<f32>() / range.len() as f32 / full
};
let jump = level[200..].windows(2).map(|w| (w[1] - w[0]).abs() / full).fold(0.0, f32::max);
assert!(jump < 0.05, "the level jumps by {jump} of full");
// Fully dimmed after 5 frames, and back after p's queue ended.
let dimmed = mean(350..600);
assert!((dimmed - 0.126).abs() < 0.02, "dimmed to {dimmed}");
let back = mean(800..1000);
assert!((back - 1.0).abs() < 0.05, "back to {back}");
}
#[test]
fn priority_dimm_bounds() {
let mut mixer = Mixer::new();
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], -18.0);
assert!((mixer.dimm - 0.1259).abs() < 1e-3);
mixer.set_priority([ClientId(1)], 6.0);
assert_eq!(mixer.dimm, 1.0);
mixer.set_priority([ClientId(1)], f32::NEG_INFINITY);
assert!((mixer.dimm - 0.001).abs() < 1e-6);
mixer.set_priority([ClientId(1)], f32::NAN);
assert_eq!(mixer.dimm, 1.0);
// Forgetting a client keeps the set: the caller replaces it.
mixer.forget(ClientId(1));
assert!(mixer.priority.contains(&ClientId(1)));
mixer.set_priority([], -18.0);
assert!(mixer.priority.is_empty());
}
#[test]
fn volume_bounds_and_forget() {
let mut mixer = Mixer::new();
+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" }
+48 -1
View File
@@ -42,6 +42,12 @@ pub(crate) enum AudioIn {
},
/// The client left; client ids are reused, so forget its volume.
ClientLeft(ClientId),
/// The priority speakers: while one talks, everyone else (streams too)
/// is dimmed by `dimm_db` (the server's setting, e.g. -18).
PrioritySpeakers {
clients: Vec<ClientId>,
dimm_db: f32,
},
/// An Opus frame (48 kHz) of a watched stream; `time` is its RTP time
/// on the 48 kHz clock.
StreamAudio {
@@ -208,6 +214,9 @@ impl Pipeline {
AudioIn::ClientVolume { client, volume } => self.mixer.set_volume(client, volume),
AudioIn::ClientMuted { client, muted } => self.mixer.set_muted(client, muted),
AudioIn::ClientLeft(client) => self.mixer.forget(client),
AudioIn::PrioritySpeakers { clients, dimm_db } => {
self.mixer.set_priority(clients, dimm_db);
}
AudioIn::StreamAudio { stream, time, data } => self.stream_packet(stream, time, &data),
AudioIn::StreamVolume { stream, volume } => {
if let Some(s) = self.streams.get(&stream) {
@@ -547,7 +556,7 @@ mod devices {
#[cfg(test)]
mod tests {
use voelin_audio::pcm::{SAMPLE_RATE, energy, sine, white_noise};
use voelin_audio::pcm::{SAMPLE_RATE, energy, goertzel_power, sine, white_noise};
use voelin_audio::{ProcessingSettings, VadSettings};
use super::*;
@@ -668,6 +677,44 @@ mod tests {
assert!(!p.mixer.is_muted(ClientId(3)));
}
/// While a priority speaker talks, another talker and a watched stream
/// are dimmed by the server's setting.
#[test]
fn priority_speaker() {
let mut p = pipeline(TransmitMode::PushToTalk);
p.handle(AudioIn::PrioritySpeakers { clients: vec![ClientId(2)], dimm_db: -12.0 });
let mut voice = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut priority = VoiceEncoder::new(VoiceCodec::Voice).unwrap();
let mut music = VoiceEncoder::new(VoiceCodec::Music).unwrap();
let tone = sine(700.0, 2.0, 0.3);
let stream = pcm::from_mono(&sine(1100.0, 2.0, 0.3), 2);
let other = sine(1700.0, 1.0, 0.3);
let mut out = Vec::new();
for (i, frame) in tone.chunks_exact(FRAME_SAMPLES).enumerate() {
p.handle(incoming(1, i as u16, voice.encode_to_bytes(frame).unwrap()));
let frame = &stream[i * FRAME_SAMPLES * 2..(i + 1) * FRAME_SAMPLES * 2];
let data: Arc<[u8]> = music.encode_to_bytes(frame).unwrap().into();
let time = i as u64 * OPUS_FRAME;
p.handle(AudioIn::StreamAudio { stream: "s".into(), time, data });
// The priority speaker talks during the second second.
if let Some(j) = i.checked_sub(50) {
let frame = &other[j * FRAME_SAMPLES..(j + 1) * FRAME_SAMPLES];
p.handle(incoming(2, j as u16, priority.encode_to_bytes(frame).unwrap()));
}
out.extend(p.playback_frame());
}
// The second half of each second.
let half = SAMPLE_RATE as usize / 2;
let level = |second: usize, freq: f32| {
let from = second * 2 * half + half;
goertzel_power(&out[from..from + half], freq, SAMPLE_RATE)
};
for freq in [700.0, 1100.0] {
let ratio_db = 10.0 * (level(1, freq) / level(0, freq)).log10();
assert!((ratio_db + 12.0).abs() < 1.0, "{freq} Hz dimmed by {ratio_db} dB");
}
}
/// End to end: a remote talker is played, the speakers leak into the
/// microphone 30 ms later, and the echo canceller (fed with what was
/// played) removes it from what we would send.
+87 -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,
@@ -60,6 +60,8 @@ fn server_details(server: &data::Server, uid: Option<&str>) -> ServerDetails {
platform: server.platform.clone(),
version: server.version.clone(),
max_clients: server.max_clients,
// `as` saturates (and turns NaN into 0); the mixer clamps it.
priority_speaker_dimm_db: server.priority_speaker_dimm_modificator.round() as i32,
default_server_group: Some(server.default_server_group.0),
default_channel_group: Some(server.default_channel_group.0),
}
@@ -115,7 +117,12 @@ pub(crate) fn presence_from_book(
needed_talk_power: c.needed_talk_power.unwrap_or(0),
is_default: c.is_default.unwrap_or(false),
icon: c.icon.map_or(0, |i| i.0),
banner_gfx_url: c.banner_gfx_url.clone().filter(|u| !u.is_empty()),
banner_gfx_url: c
.banner_gfx_url
.as_deref()
.map(str::trim)
.filter(|u| !u.is_empty())
.map(str::to_owned),
// A number the book keeps as text.
banner_mode: c
.banner_mode
@@ -147,11 +154,15 @@ pub(crate) fn presence_from_book(
server_groups,
country: Some(c.country_code.clone()).filter(|c| !c.is_empty()),
avatar: Some(c.avatar_hash.clone()).filter(|h| !h.is_empty()),
myts_avatar: c.my_team_speak_avatar.as_deref().and_then(myts_avatar_url),
description: Some(c.description.clone()).filter(|d| !d.is_empty()),
talk_power: c.talk_power,
talker: c.talk_power_granted,
channel_group: Some(c.channel_group.0),
badges: parse_badges(&c.badges),
badges: shown_badges(
&c.badges,
c.signed_badges.as_deref().unwrap_or_default(),
),
icon: c.icon.0,
recording: c.is_recording,
priority_speaker: c.is_priority_speaker,
@@ -177,10 +188,8 @@ mod tests {
InMessage::new(&packet.header(), text.as_bytes()).unwrap()
}
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
/// in the channel list, when a channel is created and when it is edited.
#[test]
fn channel_banners() {
/// The book of a TeamSpeak 6 server (6.0.0-beta13.1) after `initserver`.
fn ts6_book() -> data::Connection {
let InMessage::InitServer(init) = message(concat!(
"initserver virtualserver_name=Test virtualserver_welcomemessage ",
"virtualserver_platform=Linux virtualserver_version=6.0.0-beta13.1 ",
@@ -200,20 +209,29 @@ mod tests {
)) else {
panic!("not an initserver");
};
let mut book = data::Connection::new(EccKeyPrivP256::create().to_pub(), &init);
let channel = |cid: u64, order: u64, name: &str, banner: &str| {
format!(
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
channel_storage_quota=4294967295"
)
};
data::Connection::new(EccKeyPrivP256::create().to_pub(), &init)
}
/// A `channellist` entry as TeamSpeak 6 sends it.
fn channel(cid: u64, order: u64, name: &str, banner: &str) -> String {
format!(
"cid={cid} cpid=0 channel_name={name} channel_topic channel_codec=4 \
channel_codec_quality=6 channel_maxclients=-1 channel_maxfamilyclients=-1 \
channel_order={order} channel_flag_permanent=1 channel_flag_semi_permanent=0 \
channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 \
channel_codec_is_unencrypted=1 channel_delete_delay=0 \
channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=1 \
channel_flag_maxfamilyclients_inherited=0 channel_needed_talk_power=0 \
channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 {banner} \
channel_storage_quota=4294967295"
)
}
/// Channel banners as a TeamSpeak 6 server (6.0.0-beta13.1) sends them:
/// in the channel list, when a channel is created and when it is edited.
#[test]
fn channel_banners() {
let mut book = ts6_book();
let list = format!(
"channellist {}|{}",
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
@@ -265,5 +283,52 @@ mod tests {
assert_eq!(p.server.banner_gfx_interval_s, 60);
assert_eq!(p.server.banner_mode, BannerMode::KeepAspect);
assert_eq!(BannerMode::from_wire("7"), BannerMode::NoAdjust);
assert_eq!(p.server.priority_speaker_dimm_db, -18);
}
/// The myTeamSpeak avatar of a client as a TeamSpeak 6 server sends it:
/// when the client enters and when it changes.
#[test]
fn myts_avatars() {
let mut book = ts6_book();
book.handle_command(&message(&format!("channellist {}", channel(1, 0, "Lobby", ""))))
.unwrap();
let enter = |clid: u16, avatar: &str| {
format!(
"notifycliententerview reasonid=0 ctid=1 clid={clid} client_database_id={clid} \
client_nickname=c{clid} client_type=0 cfid=0 client_unique_identifier=u{clid}= \
client_flag_avatar client_description client_icon_id=0 client_input_muted=0 \
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
client_output_hardware=1 client_meta_data client_is_recording=0 \
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
client_servergroups=8 client_away=0 client_away_message client_talk_power=75 \
client_talk_request=0 client_talk_request_msg client_is_talker=0 \
client_is_priority_speaker=0 client_unread_messages=0 client_nickname_phonetic \
client_needed_serverquery_view_power=75 client_is_channel_commander=0 \
client_country=RU client_badges client_myteamspeak_id=m{clid} \
client_integrations{avatar}"
)
};
for text in [
enter(
5,
r" client_myteamspeak_avatar=3,https:\/\/a.example\/away.png;2,https:\/\/a.example\/on.png",
),
// A TeamSpeak 3 server, or a client without one.
enter(6, ""),
enter(7, " client_myteamspeak_avatar"),
] {
book.handle_command(&message(&text)).unwrap();
}
let p = presence_from_book(&book, None, |_| false);
let avatar = |p: &Presence, clid: u16| p.clients[&clid].myts_avatar.clone();
assert_eq!(avatar(&p, 5).as_deref(), Some("https://a.example/on.png"));
assert_eq!((avatar(&p, 6), avatar(&p, 7)), (None, None));
book.handle_command(&message(
r"notifyclientupdated clid=6 client_myteamspeak_avatar=4,https:\/\/a.example\/off.png",
))
.unwrap();
let p = presence_from_book(&book, None, |_| false);
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
}
}
+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);
}
}
+73 -12
View File
@@ -39,9 +39,9 @@
//! [`Event::Poke`]), private messages to any client (a
//! [`ChatTarget::Private`] chat, stored under the peer's unique id), the
//! channels' file browsers, avatars and icons ([`files`], cached in
//! [`cache`]) and offline messages ([`offline`]). The host banner and
//! channel banners are pictures on the web, fetched into the same cache
//! ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person
//! [`cache`]) and offline messages ([`offline`]). The host banner, channel
//! banners and the clients' badges are pictures on the web, fetched into the
//! same cache ([`Event::PictureReady`]). Contacts (friends, blocked people, per-person
//! volume) are engine-wide ([`contacts`]).
mod audio;
@@ -96,14 +96,27 @@ use voelin_stream::{
EncodedFrame, LayerId, LayerSpec, SrtpProfile, StreamInfo, StreamSetup, ViewerInfo,
};
pub use voice::VoiceOptions;
/// Banners are downloaded and shown by the same rule.
pub use web::is_svg;
/// Pictures from the web go through the desktop's proxy (set at startup).
pub use web::set_proxy_resolver;
pub type SessionId = u64;
/// The longest poke message servers take, in characters; a longer one is
/// cut ([`Command::Poke`]).
pub const POKE_MESSAGE_MAX: usize = 100;
/// What the UI asks for.
#[derive(Clone, Debug)]
pub enum Command {
/// Main account proof for every current and future voice connection.
SetMytsIdentity(Option<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>,
@@ -111,10 +124,14 @@ pub enum Command {
DisconnectVoice {
session: SessionId,
},
/// Invisible presence and relay chat through a `tsgw` gateway.
/// Invisible presence and relay chat through a `tsgw` gateway: the first
/// of `urls` (best first, [`discover::gateways`]) that logs in, tried in
/// turn again whenever it is lost. Sent again with the same `urls` and
/// identity while it runs, it is not started over; while still
/// connecting, it tries again at once (at most every 5 s).
ObserveGateway {
session: SessionId,
url: String,
urls: Vec<String>,
identity: Box<tsclientlib::Identity>,
},
/// Invisible presence and relay chat with own ServerQuery credentials.
@@ -153,6 +170,7 @@ pub enum Command {
session: SessionId,
request: GatewayRequest,
},
/// Refusals come as [`Event::JoinFailed`].
MoveToChannel {
session: SessionId,
channel: ChannelId,
@@ -273,7 +291,8 @@ pub enum Command {
volume: f32,
},
/// Poke a client (voice): the server shows it a notification with
/// `message`. Failures come as [`Event::Error`].
/// `message`, cut to [`POKE_MESSAGE_MAX`] characters. Failures come as
/// [`Event::Error`].
Poke {
session: SessionId,
client: u16,
@@ -365,6 +384,14 @@ pub enum Command {
session: SessionId,
client_uid: String,
},
/// Get a picture on the web that a chat message shows (`[img]`) into
/// the cache ([`Event::PictureReady`]) while `cache.fetch_images` is on;
/// one larger than `max_bytes` is not reported.
FetchPicture {
session: SessionId,
url: String,
max_bytes: u64,
},
/// Our offline messages ([`Event::OfflineMessages`]); see [`offline`].
ListOfflineMessages {
session: SessionId,
@@ -469,6 +496,17 @@ pub struct SessionState {
pub server_uid: Option<String>,
}
/// Why the server did not let us into a channel ([`Event::JoinFailed`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JoinFailure {
/// The channel's password is missing or wrong.
Password,
/// The channel, or the channel with its subchannels, is full.
Full,
/// Anything else, as a sentence for the user.
Other(String),
}
/// What the engine reports.
#[derive(Clone, Debug)]
pub enum Event {
@@ -534,6 +572,12 @@ pub enum Event {
session: SessionId,
message: String,
},
/// The server refused [`Command::MoveToChannel`] into `channel`.
JoinFailed {
session: SessionId,
channel: ChannelId,
reason: JoinFailure,
},
/// The streams in our channel (TeamSpeak 6), full list.
StreamsChanged {
session: SessionId,
@@ -640,9 +684,10 @@ pub enum Event {
request: RequestId,
result: Result<(), String>,
},
/// A client's avatar is in the cache: `path`, its MD5 `hash`
/// ([`voelin_model::ClientInfo::avatar`]). Comes when the client appears
/// with an avatar and when it changes.
/// A client's avatar is in the cache: `path`, and `hash`: the MD5 of a
/// server avatar ([`voelin_model::ClientInfo::avatar`]), or the address
/// of a myTeamSpeak avatar ([`voelin_model::ClientInfo::myts_avatar`]).
/// Comes when the client appears with an avatar and when it changes.
AvatarReady {
session: SessionId,
client_uid: String,
@@ -656,9 +701,11 @@ pub enum Event {
path: PathBuf,
},
/// A picture on the web is in the cache: the host banner
/// ([`ServerDetails::banner_gfx_url`]) or a channel's
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]) at `url` (setting
/// `cache.fetch_images`). Comes again when the host banner was reloaded
/// ([`ServerDetails::banner_gfx_url`]), a channel's
/// ([`voelin_model::ChannelInfo::banner_gfx_url`]), a badge's
/// ([`voelin_model::badges::icon_url`]) or one a chat message shows
/// ([`Command::FetchPicture`]) at `url` (setting `cache.fetch_images`).
/// Comes again when the host banner was reloaded
/// (`banner_gfx_interval_s`, at least a minute): the file at `path`
/// changed.
PictureReady {
@@ -816,6 +863,7 @@ async fn run(
contacts.load().await;
let mut sessions: HashMap<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));
@@ -873,6 +921,16 @@ async fn run(
});
continue;
}
Command::SetMytsData(data) => {
myts_data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
continue;
}
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
@@ -949,6 +1007,7 @@ async fn run(
settings.clone(),
engine.clone(),
myts_identity.subscribe(),
myts_data.subscribe(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -1020,6 +1079,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::CreateDirectory { session, .. }
| Command::SetAvatar { session, .. }
| Command::FetchAvatar { session, .. }
| Command::FetchPicture { session, .. }
| Command::ListOfflineMessages { session, .. }
| Command::GetOfflineMessage { session, .. }
| Command::SendOfflineMessage { session, .. }
@@ -1027,6 +1087,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. }
File diff suppressed because it is too large. Load diff
+5 -4
View File
@@ -1121,15 +1121,16 @@ 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 and banners of servers we are on.
/// Download the avatars, icons, banners and badges of servers we are on,
/// and the pictures their chats show (`[img]`).
pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
"cache.fetch_images",
Kind::Bool,
"Download avatars, icons and banners of the servers we are on.",
"Download avatars, icons, banners and badges of the servers we are on, and pictures in chat.",
|| true,
);
+492 -23
View File
@@ -33,7 +33,7 @@ use crate::cache;
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
use crate::offline::{OfflineMessage, OfflineMessageInfo};
use crate::settings::{FILES_PROGRESS_MS, SharedSettings};
use crate::{Event, SessionId};
use crate::{Event, JoinFailure, POKE_MESSAGE_MAX, SessionId};
#[derive(Clone, Debug)]
pub struct VoiceOptions {
@@ -43,8 +43,12 @@ pub struct VoiceOptions {
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`.
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
@@ -60,6 +64,8 @@ impl VoiceOptions {
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
@@ -70,6 +76,8 @@ impl VoiceOptions {
#[derive(Clone)]
pub(crate) struct VoiceLink {
pub myts_identity: watch::Receiver<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,
@@ -225,8 +233,35 @@ fn now_ms() -> i64 {
.unwrap_or_default()
}
/// What `client_user_tag` is to be set to, if anything: on servers that
/// know it (`user_tags`), the tag `wanted` where `shown` is another (or
/// none), or `again` after a new account proof; empty (cleared) where one
/// is shown that is no longer wanted.
fn user_tag_update(
wanted: Option<&tsclientlib::UserTag>,
shown: Option<&tsclientlib::UserTag>,
user_tags: bool,
again: bool,
now_ms: i64,
) -> Option<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>),
@@ -236,6 +271,16 @@ enum Input {
/// A command waiting for the server's answer.
enum Pending {
MytsIdentity(Instant),
/// `updatemytsdata`: whether it showed the avatar and the badges (else
/// it cleared them), and the ids of the badges shown; what the server
/// published is only logged.
MytsData {
avatar: Option<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,
@@ -253,6 +298,10 @@ enum Pending {
id: u32,
message: Option<OfflineMessage>,
},
/// Moving ourselves; refusals are reported as [`Event::JoinFailed`].
Move {
channel: ChannelId,
},
/// Failures are reported as [`VoiceEvent::Error`] with this label.
Report(&'static str),
/// Best effort: the answer does not matter.
@@ -290,17 +339,21 @@ impl Job {
}
}
/// How long a picture of `size` bytes may take to arrive: half a minute,
/// plus its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on
/// slow links while a stalled transfer still ends.
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
fn image_download_time(size: u64) -> Duration {
Duration::from_secs(30 + size / cache::MIN_PICTURE_RATE)
Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30);
/// Bound background image handshakes without imposing a deadline on user transfers.
fn expire_image_jobs(jobs: &mut HashMap<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 {
@@ -340,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(
@@ -365,7 +424,14 @@ async fn run_inner(
if let Some(channel) = &options.channel {
builder = builder.channel(channel.clone());
}
if let Some(pw) = options.channel_password.as_ref().filter(|p| !p.is_empty()) {
builder = builder.channel_password(pw.clone());
}
if let Some(token) = &options.token {
builder = builder.default_token(token.clone());
}
let mut identity = link.myts_identity.clone();
let mut data = link.myts_data.clone();
// A changed account invalidates an in-flight handshake. Drop that connection
// and take a fresh snapshot before publishing any connected state.
let mut con = timeout(Duration::from_secs(30), async {
@@ -433,8 +499,14 @@ async fn run_inner(
pending: HashMap::new(),
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
myts_shown: tsclientlib::MytsData::default(),
};
voice.publish_state()?;
// The account's avatar, badges and User Tag, for everyone on the
// server (as the official client, once connected).
data.borrow_and_update();
voice.send_myts_data(true);
let mut tick = tokio::time::interval(Duration::from_millis(250));
let result = loop {
@@ -445,7 +517,9 @@ async fn run_inner(
}) {
break Err(anyhow::anyhow!("myTeamSpeak account update timed out"));
}
let input = next_input(&mut voice.con.events(), commands, &mut tick, &mut identity).await;
let input =
next_input(&mut voice.con.events(), commands, &mut tick, &mut identity, &mut data)
.await;
match input {
Input::AccountSourceClosed => break Err(anyhow::anyhow!("account source closed")),
Input::MytsIdentityChanged => {
@@ -456,6 +530,15 @@ async fn run_inner(
}
Err(e) => break Err(anyhow::anyhow!("myTeamSpeak account update: {e}")),
}
// After the proof, what is shown of the account (a sign-in):
// its change, if any, is in this one. All of it again: the
// server checks it for the myTS ID it holds when it comes.
data.borrow_and_update();
voice.send_myts_data(true);
}
Input::MytsDataChanged => {
data.borrow_and_update();
voice.send_myts_data(false);
}
Input::Item(None) => break Err(anyhow::anyhow!("connection closed")),
Input::Item(Some(Err(e))) => break Err(e.into()),
@@ -488,6 +571,7 @@ async fn next_input(
commands: &mut mpsc::UnboundedReceiver<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;
@@ -496,6 +580,11 @@ async fn next_input(
} else {
Input::AccountSourceClosed
},
changed = data.changed() => if changed.is_ok() {
Input::MytsDataChanged
} else {
Input::AccountSourceClosed
},
input = async {
// Keep account changes first without starving network or timers when
// the audio command queue remains ready.
@@ -562,6 +651,10 @@ impl Voice {
self.message(target, invoker, message);
}
}
// Connected again after a reconnect.
if self.myts_data_due {
self.send_myts_data(true);
}
self.publish_state()?;
}
StreamItem::Audio(packet) => {
@@ -644,6 +737,9 @@ impl Voice {
}
StreamItem::DisconnectedTemporarily(reason) => {
warn!(?reason, "voice connection interrupted, reconnecting");
// A new client on the server: it shows nothing of the account.
self.myts_data_due = true;
self.myts_shown = tsclientlib::MytsData::default();
}
_ => {}
}
@@ -801,7 +897,38 @@ impl Voice {
};
self.link.emit(Event::OfflineMessage { session, request, result });
}
Pending::Move { channel } => {
if let Err(e) = result
&& let Some(reason) = join_failure(e)
{
self.link.emit(Event::JoinFailed { session, channel, reason });
}
}
Pending::Quiet | Pending::MytsIdentity(_) => {}
Pending::MytsData { avatar, badges, badge_ids } => match result {
Ok(()) => self.myts_published(avatar, badges, &badge_ids),
Err(TsError::ParameterInvalid) => warn!(
"the server refused the account's myTeamSpeak certificate (error 1538): it \
is expired, revoked or not a myTeamSpeak signing certificate, or the \
server could not load myTeamSpeak's revocation list"
),
Err(e) => warn!(error = %e, "the server refused the account's avatar or badges"),
},
Pending::UserTag(value) => match result {
Ok(()) => {
let own = self.con.get_state().ok().and_then(|state| {
state.clients.get(&state.own_client).and_then(|c| c.user_tag.clone())
});
if value.is_empty() {
info!("the server no longer shows a User Tag for the account");
} else if own.as_deref() == Some(value.as_str()) {
info!("the server shows the account's User Tag");
} else {
warn!("the server took the account's User Tag but shows another value");
}
}
Err(e) => warn!(error = %e, "the server refused the account's User Tag"),
},
Pending::Report(what) => {
if let Err(e) = result {
let _ = self.events.send(VoiceEvent::Error(format!("{what}: {e}")));
@@ -810,6 +937,129 @@ impl Voice {
}
}
/// What is to be shown of the account on this connection: what the UI
/// gave, when it is for the myTS ID this connection presents; nothing
/// without one (signed out).
fn myts_wanted(&self) -> tsclientlib::MytsData {
let identity = self.link.myts_identity.borrow();
let data = self.link.myts_data.borrow();
match (identity.as_deref(), data.as_deref()) {
(Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(),
_ => tsclientlib::MytsData::default(),
}
}
/// Whether the server knows the User Tag (TeamSpeak 6: it names
/// `client_user_tag` for our client, protocol 8 on).
fn has_user_tags(&self) -> bool {
self.con.get_state().is_ok_and(|state| {
state.server.protocol_version >= 8
|| state.clients.get(&state.own_client).is_some_and(|c| c.user_tag.is_some())
})
}
/// Show the server the account's avatar, badges and User Tag where it
/// shows something else (`updatemytsdata`, `clientupdate`), or clear
/// them; `again`: all of it, after a new account proof. While
/// reconnecting, once connected again.
fn send_myts_data(&mut self, again: bool) {
self.myts_data_due = false;
if self.con.get_state().is_err() {
self.myts_data_due = true;
return;
}
let mut wanted = self.myts_wanted();
let user_tags = self.has_user_tags();
if !user_tags {
wanted.user_tag = None;
}
for update in wanted.updates(&self.myts_shown, again) {
let shows = |part: &Option<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);
@@ -840,13 +1090,15 @@ impl Voice {
self.send(out, Pending::Report("message"))?;
}
VoiceCmd::Move(channel, password) => {
let state = self.con.get_state()?;
let own = &state.clients[&state.own_client];
let mut part = own.client_move(tsclientlib::ChannelId(channel));
if let Some(pw) = &password {
part = part.set_password(pw);
}
part.send(&mut self.con)?;
let own = self.con.get_state()?.own_client;
let cpw = encode_password(password.as_deref());
let cmd =
c2s::OutClientMoveMessage::new(&mut std::iter::once(c2s::OutClientMovePart {
client_id: own,
channel_id: tsclientlib::ChannelId(channel),
channel_password: (!cpw.is_empty()).then_some(cpw.as_str().into()),
}));
self.send(cmd, Pending::Move { channel })?;
}
VoiceCmd::SetInputMuted(muted) => {
self.con.get_state()?.client_update().set_input_muted(muted).send(&mut self.con)?;
@@ -864,7 +1116,7 @@ impl Voice {
let cmd = c2s::OutClientPokeRequestMessage::new(&mut std::iter::once(
c2s::OutClientPokeRequestPart {
client_id: tsclientlib::ClientId(client),
message: message.as_str().into(),
message: poke_message(&message).into(),
},
));
self.send(cmd, Pending::Report("poke"))?;
@@ -1053,6 +1305,48 @@ impl Voice {
}
}
/// Why a move into a channel failed, for the user; `None` when there is
/// nothing to tell (we are in that channel already).
fn join_failure(error: TsError) -> Option<JoinFailure> {
let text = match error {
TsError::ChannelAlreadyIn => return None,
TsError::ChannelInvalidPassword => return Some(JoinFailure::Password),
TsError::ChannelMaxclientsReached | TsError::ChannelMaxfamilyReached => {
return Some(JoinFailure::Full);
}
TsError::ChannelInvalidId => "The channel does not exist any more.".to_owned(),
TsError::PermissionsClientInsufficient | TsError::Permissions => {
"You are not allowed to join this channel.".to_owned()
}
TsError::ClientIsFlooding => "Too many requests: try again in a moment.".to_owned(),
// The error's name in words (its Display is the name).
e => format!("The server refused to move you: {}.", error_words(e)),
};
Some(JoinFailure::Other(text))
}
/// A poke's message as servers take it: its first [`POKE_MESSAGE_MAX`]
/// characters (not bytes, so a letter is never cut in half).
fn poke_message(message: &str) -> &str {
match message.char_indices().nth(POKE_MESSAGE_MAX) {
Some((end, _)) => &message[..end],
None => message,
}
}
/// A TeamSpeak error's name in lowercase words:
/// `ChannelIsPrivateChannel` is "channel is private channel".
fn error_words(error: TsError) -> String {
let mut words = String::new();
for c in format!("{error:?}").chars() {
if c.is_ascii_uppercase() && !words.is_empty() {
words.push(' ');
}
words.push(c.to_ascii_lowercase());
}
words
}
/// A failed transfer, for the user.
fn transfer_error(error: &tsclientlib::Error) -> String {
match error {
@@ -1063,6 +1357,47 @@ fn transfer_error(error: &tsclientlib::Error) -> String {
}
}
#[cfg(test)]
mod join_tests {
use super::*;
#[test]
fn refused_moves_say_why() {
assert_eq!(join_failure(TsError::ChannelInvalidPassword), Some(JoinFailure::Password));
assert_eq!(join_failure(TsError::ChannelMaxclientsReached), Some(JoinFailure::Full));
assert_eq!(join_failure(TsError::ChannelMaxfamilyReached), Some(JoinFailure::Full));
// Moving to the channel we are in.
assert_eq!(join_failure(TsError::ChannelAlreadyIn), None);
let other = |text: &str| Some(JoinFailure::Other(text.into()));
assert_eq!(
join_failure(TsError::PermissionsClientInsufficient),
other("You are not allowed to join this channel.")
);
// The rest in words, not the error's name.
assert_eq!(
join_failure(TsError::ChannelIsPrivateChannel),
other("The server refused to move you: channel is private channel.")
);
}
}
#[cfg(test)]
mod poke_tests {
use super::*;
#[test]
fn long_pokes_are_cut_by_characters() {
assert_eq!(poke_message("hi"), "hi");
assert_eq!(poke_message(""), "");
let exact = "x".repeat(POKE_MESSAGE_MAX);
assert_eq!(poke_message(&exact), exact);
// Two bytes each: cut after 100 letters, not 100 bytes.
let long = "ä".repeat(150);
assert_eq!(poke_message(&long), "ä".repeat(POKE_MESSAGE_MAX));
assert_eq!(poke_message(&"🙂".repeat(101)).chars().count(), POKE_MESSAGE_MAX);
}
}
#[cfg(test)]
mod image_download_tests {
use super::*;
@@ -1087,10 +1422,10 @@ mod image_download_tests {
},
);
}
expire_image_jobs(&mut jobs, started + Duration::from_secs(14));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1));
assert_eq!(jobs.len(), 2);
assert!(reports.lock().unwrap().is_empty());
expire_image_jobs(&mut jobs, started + Duration::from_secs(15));
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION);
assert_eq!(jobs.len(), 1);
assert!(jobs.contains_key(&FiletransferHandle(2)));
assert!(
@@ -1102,10 +1437,10 @@ mod image_download_tests {
#[test]
fn large_pictures_get_time_to_arrive() {
assert_eq!(image_download_time(0), Duration::from_secs(30));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(33));
assert_eq!(image_download_time(0), Duration::from_secs(60));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(30 + 2048));
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384));
}
}
@@ -1116,6 +1451,7 @@ mod account_tests {
#[tokio::test(start_paused = true)]
async fn account_priority_preserves_ready_network_and_timer_progress() {
let (account, mut identity) = watch::channel(None);
let (account_data, mut data) = watch::channel(None);
let (commands, mut receiver) = mpsc::unbounded_channel();
for _ in 0..512 {
commands.send(VoiceCmd::SetInputMuted(false)).unwrap();
@@ -1126,14 +1462,22 @@ mod account_tests {
let mut tick = tokio::time::interval(Duration::from_millis(1));
account.send_replace(None);
assert!(matches!(
next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await,
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
Input::MytsIdentityChanged
));
identity.borrow_and_update();
// What is shown of the account changes too, ahead of the rest.
account_data.send_replace(Some(Arc::new(tsclientlib::MytsData::default())));
assert!(matches!(
next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await,
Input::MytsDataChanged
));
data.borrow_and_update();
let (mut network, mut timers, mut audio) = (0, 0, 0);
for _ in 0..512 {
tokio::time::advance(Duration::from_millis(1)).await;
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity).await {
match next_input(&mut stream, &mut receiver, &mut tick, &mut identity, &mut data).await
{
Input::Item(_) => network += 1,
Input::Tick => timers += 1,
Input::Cmd(_) => audio += 1,
@@ -1143,6 +1487,130 @@ mod account_tests {
assert!(network > 0 && timers > 0 && audio > 0);
}
fn account_data(myts_id: &[u8]) -> tsclientlib::MytsData {
let signed = |data: &[u8]| tsclientlib::Signed { certificate: vec![1], data: data.into() };
tsclientlib::MytsData {
myts_id: myts_id.to_vec(),
avatar: signed(b"avatar"),
badges: signed(b"badges"),
badge_ids: vec!["b1".into()],
user_tag: Some(tsclientlib::UserTag {
tag: "a@myteamspeak.com".into(),
token: vec![2],
}),
}
}
/// The User Tag is set where it is not shown yet, or after a new account
/// proof, and cleared where it is no longer wanted: on TeamSpeak 6
/// servers only.
#[test]
fn the_user_tag_is_set_where_it_changed() {
let tag = |tag: &str| tsclientlib::UserTag { tag: tag.into(), token: vec![2] };
let (a, b) = (tag("a@myteamspeak.com"), tag("b@myteamspeak.com"));
let update =
|wanted, shown, user_tags, again| user_tag_update(wanted, shown, user_tags, again, 5);
let set = Some(a.value(5));
assert!(set.as_deref().unwrap().starts_with(r#"{"myts_token":"Ag==","tag":"a@"#));
assert_eq!(update(Some(&a), None, true, false), set);
assert_eq!(update(Some(&a), Some(&a), true, false), None, "unchanged");
assert_eq!(update(Some(&a), Some(&a), true, true), set, "after a new account proof");
assert_eq!(update(Some(&a), Some(&b), true, false), set, "another tag");
assert_eq!(update(None, Some(&a), true, false).as_deref(), Some(""), "cleared");
assert_eq!(update(None, Some(&a), true, true).as_deref(), Some(""));
assert_eq!(update(None, None, true, true), None, "nothing to clear");
// Not a TeamSpeak 6 server: nothing, set or cleared.
assert_eq!(update(Some(&a), None, false, true), None);
assert_eq!(update(None, Some(&a), false, false), None);
}
/// The server publishes the ids of the badges that verified.
#[test]
fn badges_the_server_dropped_are_named() {
let sent: Vec<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();
@@ -1168,6 +1636,7 @@ mod account_tests {
events,
settings: SharedSettings::new(crate::settings::Settings::default()),
myts_identity: identity,
myts_data: watch::channel(None).1,
};
let (_commands, commands) = mpsc::unbounded_channel();
let (events, mut received) = mpsc::unbounded_channel();
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);
}
+125
View File
@@ -123,6 +123,131 @@ async fn ts3_engine() {
.await;
}
/// A channel password and a privilege key work when connecting; a refused
/// move says why. One connection, as the servers refuse quick reconnects.
async fn channel_joins(voice_addr: &str, query: voelin_query::Connect) {
use voelin_core::JoinFailure;
use voelin_query::{Command as Query, QueryClient};
let (admin, _) = QueryClient::connect(&query).await.unwrap();
let tag = std::process::id() % 10_000;
let create = |name: &str| {
Query::new("channelcreate")
.arg("channel_name", format!("{name}-{tag}"))
.arg("channel_flag_semi_permanent", 1)
};
let locked = admin.send(&create("locked").arg("channel_password", "secret")).await.unwrap()[0]
.parse::<u64>("cid")
.unwrap();
let full =
create("full").arg("channel_maxclients", 0).arg("channel_flag_maxclients_unlimited", 0);
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
// A key for the Normal group, which has to keep to passwords and limits.
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
let normal = groups
.iter()
.find(|g| g.get("name") == Some("Normal") && g.get("type") == Some("1"))
.and_then(|g| g.parse::<u64>("sgid"))
.expect("a Normal server group");
let key = Query::new("privilegekeyadd")
.arg("tokentype", 0)
.arg("tokenid1", normal)
.arg("tokenid2", 0);
let token = admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned();
let channels = admin.send(&Query::new("channellist").flag("-flags")).await.unwrap();
let lobby = channels
.iter()
.find(|c| c.flag("channel_flag_default") == Some(true))
.and_then(|c| c.parse::<u64>("cid"))
.expect("a default channel");
let engine = Engine::start();
let check = {
let (engine, voice_addr, token) = (engine.clone(), voice_addr.to_owned(), token.clone());
tokio::spawn(async move {
let mut events = engine.subscribe();
let mut options = VoiceOptions::new(&voice_addr, format!("joins-{tag}"));
options.channel = Some(format!("locked-{tag}"));
options.channel_password = Some("secret".into());
options.token = Some(token);
engine.send(Command::ConnectVoice { session: 1, options: Box::new(options) });
let (mut own, mut presence) = (None, None);
wait_for(&mut events, "connected into the channel, in the key's group", |e| {
match e {
Event::State { session: 1, state } => own = state.own_client,
Event::Presence { session: 1, presence: p } => presence = Some(p.clone()),
_ => {}
}
let client = own.and_then(|id| presence.as_ref()?.clients.get(&id).cloned());
client.is_some_and(|c| c.channel == locked && c.server_groups.contains(&normal))
})
.await;
let moved = async |events: &mut Receiver<Event>, channel: u64| {
wait_for(
events,
"a move",
|e| matches!(e, Event::State { session: 1, state } if state.own_channel == Some(channel)),
)
.await;
};
let refused =
async |events: &mut Receiver<Event>, channel: u64, reason: JoinFailure| {
let failed = wait_for(events, "a refused move", |e| {
matches!(e, Event::JoinFailed { session: 1, .. })
})
.await;
let Event::JoinFailed { channel: c, reason: r, .. } = failed else {
unreachable!()
};
assert_eq!((c, r), (channel, reason));
};
let move_to = |channel, password: Option<&str>| Command::MoveToChannel {
session: 1,
channel,
password: password.map(Into::into),
};
engine.send(move_to(lobby, None));
moved(&mut events, lobby).await;
engine.send(move_to(locked, None));
refused(&mut events, locked, JoinFailure::Password).await;
engine.send(move_to(locked, Some("wrong")));
refused(&mut events, locked, JoinFailure::Password).await;
engine.send(move_to(locked, Some("secret")));
moved(&mut events, locked).await;
// Moving where we are says nothing: the next refusal is the full channel's.
engine.send(move_to(locked, Some("secret")));
engine.send(move_to(full, None));
refused(&mut events, full, JoinFailure::Full).await;
})
};
let result = check.await;
engine.send(Command::CloseSession { session: 1 });
tokio::time::sleep(Duration::from_millis(500)).await;
// Clean up everything before reporting a failure; the key is gone once used.
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
for cid in [locked, full] {
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
}
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_channel_joins() {
if !live() {
return;
}
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_channel_joins() {
if !live() {
return;
}
channel_joins("127.0.0.1:9987", query(voelin_query::Transport::Raw, "127.0.0.1:10011")).await;
}
/// A 1×1 PNG.
const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
+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 = []
+94
View File
@@ -0,0 +1,94 @@
uid,name,description,filename,codes
4b27be5a-b92a-4b30-8b2d-14b59653f427,20th Anniversary,Celebrating 20 Years of TeamSpeak,20_years,
f81ad44d-e931-47d1-a3ef-5fd160217cf8,4Netplayers,4Netplayers customer,4netplayers,
b78a0f3e-8758-4572-b102-42a79b4a0342,????,Reads between the line,hat,
2bf80270-8efe-46dc-a472-3280a0479145,Alpha Tester,Helped to test our software. THANK YOU!,Alpha,
05114019-6b46-4b13-b5a1-e5179ef69fb5,April Fools!,"Roses are red, gaming is fun, you are carrying too much to be able to run :(",rpg,
1a518885-520c-4f54-9f49-8b1acb674771,Braindance,I’m chippin’ in,Braindance,P4TEKZ80PZ
cbf5aafd-2554-4053-80bb-0cf82ec0a430,Bright Idea,TeamSpeak took my idea on board,FeatureBadge_Lightbulb,
d6062d9c-42a3-49c9-91dd-8c43a5a46805,Bug Catcher,I found a bug!,BugBadge_Splat,
dfc70674-0fd0-431e-b3a1-edc32d7b09b2,Challenge Accepted,"Unlocked at SCILL Play — Challenges, tournaments and more!",scill,
afed63f4-82f1-4479-ab02-0ef053f55723,Communities Early Adopter,Thank you for your Support!,communities_early_adopter,
54be472d-3163-4076-9059-7f46128d937e,Communities Purchase,Purchased a TeamSpeak Community,communities_purchase,
f85f7e21-753a-4566-b26a-4e3e9155d2ef,Cyberpunk,We have a city to burn,Cyberpunk,
c028298c-84ff-4e22-be4e-b8c17552b4bb,Digi,Digi joined your channel #DIGWIN,digi,
56df5ce2-6c5a-4a24-90e2-29e497e26170,Drone Champions League,I follow the Drone Champions League,DCL_Badge,DRONECHAMP
935e5a2a-954a-44ca-aa7a-55c79285b601,E3 2018 - Winner,Discovered at E3 2018,E3-2018,
61723e54-3da2-4f19-a33f-fcdc8ef5eaa0,Father's Day 2022,Not all heroes wear capes,fathersday2022,
b9c7d6ad-5b99-40fb-988c-1d02ab6cc130,Found Tim Speak,Found Tim Speak at Gamescom 2018,met_tim,XJN4WJZEJN
809bdd5a-2601-4152-82ff-a21d23d8fd46,G2 Esports,Aged 20 years being a G2 fan,G2_Esports,
62444179-0d99-42ba-a45c-c6b1557d079a,Gamescom 2014,Registered at Gamescom 2014,gamescom_2014,
50bbdbc8-0f2a-46eb-9808-602225b49627,Gamescom 2016,Registered during Gamescom 2016,gamescom_2016,
534c9582-ab02-4267-aec6-2d94361daa2a,Gamescom 2017,Visited TeamSpeak at Gamescom 2017,gamescom_2017,DK9JGRJH1Q
4eef1ecf-a0ea-423d-bfd0-496543a00305,Gamescom 2018,Visited TeamSpeak at Gamescom 2018,gamescom_2018,8CXB49KPJ4
b82a45a5-b235-4926-be77-de102222e5eb,Gamescom 2019,Visited TeamSpeak at Gamescom 2019,Gamescom19,PNKCB76VZ8
34dbfa8f-bd27-494c-aa08-a312fc0bb240,Gamescom Hero 2017,Gaming Hero at Gamescom 2017,hero_2017,
24512806-f886-4440-b579-9e26e4219ef6,Gamescom Hero 2018,Gamescom Exclusive Gaming Hero 2018,gamescom_2018_played,BJCFQBU53C
d49fd07e-99fb-41de-8d7b-c98064713171,GommeHD.net,Your #1 Minecraft Network for over 10 years,GMHD,
c565972a-3912-457b-826f-84820c1ba6ca,Halloween 2021,Happy Halloween 2021,halloween21,
133595e7-950f-4ef2-b113-f91a68b5770d,Halloween 2021 Special,Earned by participating in our Halloween 2021 special stream,halloween21_special,
fb154277-5fe7-428a-85a4-43c0bdcdda3d,Halloween 2022,Spooky_Scary_Skeletons.mp4,halloween22,
e6679ce2-d458-493c-8ffb-5660e47ac99f,Happy Hanami,Enjoy the view,hanami2023,
de7bd960-eb02-47e1-9ce2-a44f6e255d8f,Happy Holidays 2019,Happy holidays from everyone at TeamSpeak!,Happy_Holidays,
d4ea0251-ba46-4c1a-83b7-59db3f89e52c,Happy New Year 2021,Survived the great toilet paper crisis of 2020,firework_2020,
1519e001-06a0-458c-9195-a8a6d0ec87fc,Happy New Year 2023,"Aw man, here we go again",2023_NewYear,
834d4cc1-cd80-48d6-96c4-23d131d78649,Happy Summer 2023,heat death of the universe,happy_summer_2023,
c68bcc52-7aeb-4868-b4d2-e7b20716f9ba,Heatwave 2022,I'm melting... help,summer_icecream,
94242c4e-6742-4540-8b66-ce951ed57159,Helping Hand,\ pushed some buttons *beep* *bop* ~ thanks!,homebase,
288a56c6-4da3-48de-9c9f-bd9eede5d832,Immortal Roleplay,This is your life.,Immortal_Roleplay,
69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d,International Peace Day,"United we stand, divided we fall",peaceday2022,
9ea23c77-8755-4d82-b30c-92f4aac109ef,International Women's Day 2021,"To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day!",wft,
7d9fa2b1-b6fa-47ad-9838-c239a4ddd116,MIFCOM,MIFCOM | Entered Performance,mifcom,
ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776,Merry Christmas 2019,It’s the most wonderful ‘Tim’ of the Year,Christmas,
c6480fe2-ee25-4ee8-9853-243652c8ec54,Merry Christmas 2020,"Let it snow, let it snow, let it snow!",Christmas2020,
0581aa0f-8c2d-4681-bb9f-8492fec49977,Merry Christmas 2021,Look what Santa's left under the server tree!,christmas2021,
d4875b30-9908-43cb-a1eb-1a958e226078,Merry Christmas 2022,There's snow place like home,christmas2022,
87ccf9ea-67c9-45e5-adbc-77e210e6128a,Met Tim,Met Tim Speak IRL,tim_irl,
0d98391c-ecdf-4f26-931a-49bfd669cda7,Mind Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_MindEgg,
2fdda3c6-20e0-48f1-9c12-f39239a2ed02,Mother's Day 2022,Thanks for bearing with us,rose,
c3f823eb-5d5c-40f9-9dbd-3437d59a539d,Official TeamSpeak Gamer,New myTeamSpeak member,TS-2018,
8dfa37ac-b40d-4466-b393-ff2184a9adf3,Overwatch League,I follow the Overwatch League,OWL_Badge,
4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac,PGL Antwerp 2022,Watched the PGL CS:GO Major,PGLant,
fa3ece28-64df-431f-b1b3-90844bfdd2d9,Paris Games Week 2014,Registered at Paris Games Week 2014,paris_gamesweek_2014,
d95f9901-c42d-4bac-8849-7164fd9e2310,Paris Games Week 2016,Registered during Paris Games Week 2016,paris_gamesweek_2016,
0005232e-538e-4cb2-93b6-d7d83e873829,PietSmiet,Werde Snob auf PietSmiet.de ;),PietSmiet,
be932556-dfa9-4dc6-afd0-98de0ab25777,PolTeamgeist,WooOOHoohOOHooo,PolTeamgeist,
5f6d49e4-35c8-4809-8c81-6e71f7f749e9,Power Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_PowerEgg,
ceee2445-4fbf-4f06-9421-286f0f4e875a,Pride,Never be afraid to show your colors.,pride,
1aa375e8-7207-45bf-8b80-556bafafc834,Reality Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_RealityEgg,
f22c22f1-8e2d-4d99-8de9-f352dc26ac5b,Rocket Beans TV,Rocket Beans TV Community,rbtv,RWGE2NURJZ
2c9698c1-1fec-4baa-a28f-4845f045f42f,Soul Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SoulEgg,
641a4d85-2351-482c-97a1-02fc3b6abbb5,Space Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SpaceEgg,
63261116-4359-4842-873e-56820afbe068,SpartaTheOriginal,Olaf Toast @ twitch.tv/SpartaTheOriginal,Toast,
ef567ec5-f46e-4520-be07-6021023cf6bd,Sponsorship License,Sponsored by TeamSpeak,Sponsorship,
7a627d47-5496-4d68-83b5-2c4eafff9b30,"Stay Home, Stay Safe","Playing Apart, Staying Connected",StaySafeStayHome,
7262a528-c7df-4369-bc2c-d34bf5853d7b,TS Chat Alpha Tester,"Helped us test our new mobile app, thanks!",slim_golden,
6eee759e-b1e9-4937-b023-07fc778532a2,TS Gameday Participant,At least i tried...,silvered,
e1447b99-53b0-448a-98b7-ee7bad8bd268,TS Gameday Winner,As shiny as the golden frying pan,goldenjoystick,
1cb07348-34a4-4741-b50f-c41e584370f7,TeamSpeak Addon Author,Creator of TeamSpeak Addons,addon_author,
450f81c1-ab41-4211-a338-222fa94ed157,TeamSpeak Addon Developer (Bronze),Creator of at least 1 TeamSpeak Addon,addon_author_bronze,
94ec66de-5940-4e38-b002-970df0cf6c94,TeamSpeak Addon Developer (Gold),Creator of at least 5 TeamSpeak Addons,addon_author_gold,
c9e97536-5a2d-4c8e-a135-af404587a472,TeamSpeak Addon Developer (Silver),Creator of at least 3 TeamSpeak Addons,addon_author_silver,
9cd152a7-bf65-4ece-aeba-62d27678f79a,TeamSpeak Competition Winner Badge,TeamSpeak Competition Winner,CompWinnerBadge,
64221fd1-706c-4bb2-ba55-996c39effa79,TeamSpeak Jedi,myTeamSpeak early adopter,TS-OG,
6b187e83-873b-46b0-b2c2-a31af15e76a4,TeamSpeak Merch Badge,TeamSpeak Merch Owner - 1st Edition,cap_red,
22b9ec39-7694-453e-864c-dfc7b1b0d7c7,TeamSpeak Merch Badge 2.0,TeamSpeak Merch Owner - 2nd Edition,topper,
205916f3-a953-4754-8905-bc15069b1f91,TeamSpeak Merch Badge 3.0,TeamSpeak Merch Owner — 3rd Edition,Merch3,
8d843dfa-c51a-407f-87b3-94cfc8f03e96,TeamSpeak Staff,Official Staff Member,teamspeak_staff,
c2368518-3728-4260-bcd1-8b85e9f8984c,Test,"Testing, Testing.",Testing,
4086a249-a503-4f31-9e83-8a0a8e3089bd,Tim-o'-Lantern,Mwuhaahaahaahaahaa,Tim-O-Lantern,JQGCTAQWHT
089c7295-3aa2-48b0-b2f1-2dd1bec12caf,Time Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_TimeEgg,
904e232c-f369-44db-87f7-5142e15620cc,Time Machine,Worked like a machine to update addons in super-quick time.,time_machine,
4c61af66-22ef-4897-b0bb-25fcef2acf60,Undead Nightmare,I'm the last of my kind,undead_nightmare,
b0a36aea-3e46-4e83-a455-6e92ae1b9d94,Undead Nightmare,I'm the last of my kind,undead_nightmare,
0cd924ed-c5ea-459e-b60a-4f1bc0b65f07,"Up, Up and Away!",Find me on Mount Chiliad,"up,_up_and_away!",
4b0fd4f5-d456-4294-973d-853a1db5c7d8,Valentim's Day 2019,Valentim's Day 2019,Valentines_Badge,
92801833-e721-4b7e-84d4-6c02dbb332b9,Valentim's Day 2020,Valentim's Day 2020,Valentim2020,
958f904b-8260-48a4-a961-f786cbd39411,Valentine's Day 2023,Love you like my Tamagotchi,ValentinesDay23,
a676c708-da67-4784-ba7f-3fb7e8d2e865,Valentines Day 2021,"Roses are red, TS is blue, Servers are Sweet and so are you.",valentine21,
c54a9f92-07f7-4214-90f3-eafeea8005da,World Backup Day,Don't be an April Fool. Back up your data!,backupday_2023,
448a6d13-4e08-46a1-aafa-b4ff6d6c2d06,World Bonsai Day,"harmony, balance, patience",bonsai_day,
0f976a27-ddf5-447c-b79c-0644a8e8a297,Year of the Dragon 2024,"Arise, Shenron!",year_of_the_dragon_2024,
8c22fe26-30ac-4231-8b31-67d8a75c808a,Year of the Ox 2021,Only listen to the fortune cookie; disregard all other fortune telling units.,ox21,
970c70e6-00a1-41c1-ac5c-81c89a06c7a6,Year of the Rabbit 2023,Do a barrel roll!,chineseNY2023,
92356386-0451-4a97-87d9-10ff4f43260c,Year of the Tiger 2022,Rocky sends his regards,tiger,
1 uid name description filename codes
2 4b27be5a-b92a-4b30-8b2d-14b59653f427 20th Anniversary Celebrating 20 Years of TeamSpeak 20_years
3 f81ad44d-e931-47d1-a3ef-5fd160217cf8 4Netplayers 4Netplayers customer 4netplayers
4 b78a0f3e-8758-4572-b102-42a79b4a0342 ???? Reads between the line hat
5 2bf80270-8efe-46dc-a472-3280a0479145 Alpha Tester Helped to test our software. THANK YOU! Alpha
6 05114019-6b46-4b13-b5a1-e5179ef69fb5 April Fools! Roses are red, gaming is fun, you are carrying too much to be able to run :( rpg
7 1a518885-520c-4f54-9f49-8b1acb674771 Braindance I’m chippin’ in Braindance P4TEKZ80PZ
8 cbf5aafd-2554-4053-80bb-0cf82ec0a430 Bright Idea TeamSpeak took my idea on board FeatureBadge_Lightbulb
9 d6062d9c-42a3-49c9-91dd-8c43a5a46805 Bug Catcher I found a bug! BugBadge_Splat
10 dfc70674-0fd0-431e-b3a1-edc32d7b09b2 Challenge Accepted Unlocked at SCILL Play — Challenges, tournaments and more! scill
11 afed63f4-82f1-4479-ab02-0ef053f55723 Communities Early Adopter Thank you for your Support! communities_early_adopter
12 54be472d-3163-4076-9059-7f46128d937e Communities Purchase Purchased a TeamSpeak Community communities_purchase
13 f85f7e21-753a-4566-b26a-4e3e9155d2ef Cyberpunk We have a city to burn Cyberpunk
14 c028298c-84ff-4e22-be4e-b8c17552b4bb Digi Digi joined your channel #DIGWIN digi
15 56df5ce2-6c5a-4a24-90e2-29e497e26170 Drone Champions League I follow the Drone Champions League DCL_Badge DRONECHAMP
16 935e5a2a-954a-44ca-aa7a-55c79285b601 E3 2018 - Winner Discovered at E3 2018 E3-2018
17 61723e54-3da2-4f19-a33f-fcdc8ef5eaa0 Father's Day 2022 Not all heroes wear capes fathersday2022
18 b9c7d6ad-5b99-40fb-988c-1d02ab6cc130 Found Tim Speak Found Tim Speak at Gamescom 2018 met_tim XJN4WJZEJN
19 809bdd5a-2601-4152-82ff-a21d23d8fd46 G2 Esports Aged 20 years being a G2 fan G2_Esports
20 62444179-0d99-42ba-a45c-c6b1557d079a Gamescom 2014 Registered at Gamescom 2014 gamescom_2014
21 50bbdbc8-0f2a-46eb-9808-602225b49627 Gamescom 2016 Registered during Gamescom 2016 gamescom_2016
22 534c9582-ab02-4267-aec6-2d94361daa2a Gamescom 2017 Visited TeamSpeak at Gamescom 2017 gamescom_2017 DK9JGRJH1Q
23 4eef1ecf-a0ea-423d-bfd0-496543a00305 Gamescom 2018 Visited TeamSpeak at Gamescom 2018 gamescom_2018 8CXB49KPJ4
24 b82a45a5-b235-4926-be77-de102222e5eb Gamescom 2019 Visited TeamSpeak at Gamescom 2019 Gamescom19 PNKCB76VZ8
25 34dbfa8f-bd27-494c-aa08-a312fc0bb240 Gamescom Hero 2017 Gaming Hero at Gamescom 2017 hero_2017
26 24512806-f886-4440-b579-9e26e4219ef6 Gamescom Hero 2018 Gamescom Exclusive Gaming Hero 2018 gamescom_2018_played BJCFQBU53C
27 d49fd07e-99fb-41de-8d7b-c98064713171 GommeHD.net Your #1 Minecraft Network for over 10 years GMHD
28 c565972a-3912-457b-826f-84820c1ba6ca Halloween 2021 Happy Halloween 2021 halloween21
29 133595e7-950f-4ef2-b113-f91a68b5770d Halloween 2021 Special Earned by participating in our Halloween 2021 special stream halloween21_special
30 fb154277-5fe7-428a-85a4-43c0bdcdda3d Halloween 2022 Spooky_Scary_Skeletons.mp4 halloween22
31 e6679ce2-d458-493c-8ffb-5660e47ac99f Happy Hanami Enjoy the view hanami2023
32 de7bd960-eb02-47e1-9ce2-a44f6e255d8f Happy Holidays 2019 Happy holidays from everyone at TeamSpeak! Happy_Holidays
33 d4ea0251-ba46-4c1a-83b7-59db3f89e52c Happy New Year 2021 Survived the great toilet paper crisis of 2020 firework_2020
34 1519e001-06a0-458c-9195-a8a6d0ec87fc Happy New Year 2023 Aw man, here we go again 2023_NewYear
35 834d4cc1-cd80-48d6-96c4-23d131d78649 Happy Summer 2023 heat death of the universe happy_summer_2023
36 c68bcc52-7aeb-4868-b4d2-e7b20716f9ba Heatwave 2022 I'm melting... help summer_icecream
37 94242c4e-6742-4540-8b66-ce951ed57159 Helping Hand \ pushed some buttons *beep* *bop* ~ thanks! homebase
38 288a56c6-4da3-48de-9c9f-bd9eede5d832 Immortal Roleplay This is your life. Immortal_Roleplay
39 69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d International Peace Day United we stand, divided we fall peaceday2022
40 9ea23c77-8755-4d82-b30c-92f4aac109ef International Women's Day 2021 To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day! wft
41 7d9fa2b1-b6fa-47ad-9838-c239a4ddd116 MIFCOM MIFCOM | Entered Performance mifcom
42 ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776 Merry Christmas 2019 It’s the most wonderful ‘Tim’ of the Year Christmas
43 c6480fe2-ee25-4ee8-9853-243652c8ec54 Merry Christmas 2020 Let it snow, let it snow, let it snow! Christmas2020
44 0581aa0f-8c2d-4681-bb9f-8492fec49977 Merry Christmas 2021 Look what Santa's left under the server tree! christmas2021
45 d4875b30-9908-43cb-a1eb-1a958e226078 Merry Christmas 2022 There's snow place like home christmas2022
46 87ccf9ea-67c9-45e5-adbc-77e210e6128a Met Tim Met Tim Speak IRL tim_irl
47 0d98391c-ecdf-4f26-931a-49bfd669cda7 Mind Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_MindEgg
48 2fdda3c6-20e0-48f1-9c12-f39239a2ed02 Mother's Day 2022 Thanks for bearing with us rose
49 c3f823eb-5d5c-40f9-9dbd-3437d59a539d Official TeamSpeak Gamer New myTeamSpeak member TS-2018
50 8dfa37ac-b40d-4466-b393-ff2184a9adf3 Overwatch League I follow the Overwatch League OWL_Badge
51 4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac PGL Antwerp 2022 Watched the PGL CS:GO Major PGLant
52 fa3ece28-64df-431f-b1b3-90844bfdd2d9 Paris Games Week 2014 Registered at Paris Games Week 2014 paris_gamesweek_2014
53 d95f9901-c42d-4bac-8849-7164fd9e2310 Paris Games Week 2016 Registered during Paris Games Week 2016 paris_gamesweek_2016
54 0005232e-538e-4cb2-93b6-d7d83e873829 PietSmiet Werde Snob auf PietSmiet.de ;) PietSmiet
55 be932556-dfa9-4dc6-afd0-98de0ab25777 PolTeamgeist WooOOHoohOOHooo PolTeamgeist
56 5f6d49e4-35c8-4809-8c81-6e71f7f749e9 Power Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_PowerEgg
57 ceee2445-4fbf-4f06-9421-286f0f4e875a Pride Never be afraid to show your colors. pride
58 1aa375e8-7207-45bf-8b80-556bafafc834 Reality Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_RealityEgg
59 f22c22f1-8e2d-4d99-8de9-f352dc26ac5b Rocket Beans TV Rocket Beans TV Community rbtv RWGE2NURJZ
60 2c9698c1-1fec-4baa-a28f-4845f045f42f Soul Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SoulEgg
61 641a4d85-2351-482c-97a1-02fc3b6abbb5 Space Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SpaceEgg
62 63261116-4359-4842-873e-56820afbe068 SpartaTheOriginal Olaf Toast @ twitch.tv/SpartaTheOriginal Toast
63 ef567ec5-f46e-4520-be07-6021023cf6bd Sponsorship License Sponsored by TeamSpeak Sponsorship
64 7a627d47-5496-4d68-83b5-2c4eafff9b30 Stay Home, Stay Safe Playing Apart, Staying Connected StaySafeStayHome
65 7262a528-c7df-4369-bc2c-d34bf5853d7b TS Chat Alpha Tester Helped us test our new mobile app, thanks! slim_golden
66 6eee759e-b1e9-4937-b023-07fc778532a2 TS Gameday Participant At least i tried... silvered
67 e1447b99-53b0-448a-98b7-ee7bad8bd268 TS Gameday Winner As shiny as the golden frying pan goldenjoystick
68 1cb07348-34a4-4741-b50f-c41e584370f7 TeamSpeak Addon Author Creator of TeamSpeak Addons addon_author
69 450f81c1-ab41-4211-a338-222fa94ed157 TeamSpeak Addon Developer (Bronze) Creator of at least 1 TeamSpeak Addon addon_author_bronze
70 94ec66de-5940-4e38-b002-970df0cf6c94 TeamSpeak Addon Developer (Gold) Creator of at least 5 TeamSpeak Addons addon_author_gold
71 c9e97536-5a2d-4c8e-a135-af404587a472 TeamSpeak Addon Developer (Silver) Creator of at least 3 TeamSpeak Addons addon_author_silver
72 9cd152a7-bf65-4ece-aeba-62d27678f79a TeamSpeak Competition Winner Badge TeamSpeak Competition Winner CompWinnerBadge
73 64221fd1-706c-4bb2-ba55-996c39effa79 TeamSpeak Jedi myTeamSpeak early adopter TS-OG
74 6b187e83-873b-46b0-b2c2-a31af15e76a4 TeamSpeak Merch Badge TeamSpeak Merch Owner - 1st Edition cap_red
75 22b9ec39-7694-453e-864c-dfc7b1b0d7c7 TeamSpeak Merch Badge 2.0 TeamSpeak Merch Owner - 2nd Edition topper
76 205916f3-a953-4754-8905-bc15069b1f91 TeamSpeak Merch Badge 3.0 TeamSpeak Merch Owner — 3rd Edition Merch3
77 8d843dfa-c51a-407f-87b3-94cfc8f03e96 TeamSpeak Staff Official Staff Member teamspeak_staff
78 c2368518-3728-4260-bcd1-8b85e9f8984c Test Testing, Testing. Testing
79 4086a249-a503-4f31-9e83-8a0a8e3089bd Tim-o'-Lantern Mwuhaahaahaahaahaa Tim-O-Lantern JQGCTAQWHT
80 089c7295-3aa2-48b0-b2f1-2dd1bec12caf Time Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_TimeEgg
81 904e232c-f369-44db-87f7-5142e15620cc Time Machine Worked like a machine to update addons in super-quick time. time_machine
82 4c61af66-22ef-4897-b0bb-25fcef2acf60 Undead Nightmare I'm the last of my kind undead_nightmare
83 b0a36aea-3e46-4e83-a455-6e92ae1b9d94 Undead Nightmare I'm the last of my kind undead_nightmare
84 0cd924ed-c5ea-459e-b60a-4f1bc0b65f07 Up, Up and Away! Find me on Mount Chiliad up,_up_and_away!
85 4b0fd4f5-d456-4294-973d-853a1db5c7d8 Valentim's Day 2019 Valentim's Day 2019 Valentines_Badge
86 92801833-e721-4b7e-84d4-6c02dbb332b9 Valentim's Day 2020 Valentim's Day 2020 Valentim2020
87 958f904b-8260-48a4-a961-f786cbd39411 Valentine's Day 2023 Love you like my Tamagotchi ValentinesDay23
88 a676c708-da67-4784-ba7f-3fb7e8d2e865 Valentines Day 2021 Roses are red, TS is blue, Servers are Sweet and so are you. valentine21
89 c54a9f92-07f7-4214-90f3-eafeea8005da World Backup Day Don't be an April Fool. Back up your data! backupday_2023
90 448a6d13-4e08-46a1-aafa-b4ff6d6c2d06 World Bonsai Day harmony, balance, patience bonsai_day
91 0f976a27-ddf5-447c-b79c-0644a8e8a297 Year of the Dragon 2024 Arise, Shenron! year_of_the_dragon_2024
92 8c22fe26-30ac-4231-8b31-67d8a75c808a Year of the Ox 2021 Only listen to the fortune cookie; disregard all other fortune telling units. ox21
93 970c70e6-00a1-41c1-ac5c-81c89a06c7a6 Year of the Rabbit 2023 Do a barrel roll! chineseNY2023
94 92356386-0451-4a97-87d9-10ff4f43260c Year of the Tiger 2022 Rocky sends his regards tiger
+144
View File
@@ -0,0 +1,144 @@
//! myTeamSpeak badges: what the GUIDs a client shows (`client_badges`)
//! stand for, and where TeamSpeak keeps their pictures.
//!
//! The table is `data/badges.csv`: tsclientlib's list (2023, also in
//! `proto/tsproto-structs/declarations`) and the newer badges of
//! TeamSpeak's own list (`https://badges-content.teamspeak.com/list`, a
//! protobuf) as of October 2026. Badges added since are unknown here.
use std::collections::HashMap;
use std::sync::LazyLock;
/// How many badges a client shows at most (TeamSpeak lets one pick three).
pub const SHOWN: usize = 3;
/// TeamSpeak's server for the badges' pictures.
const CONTENT: &str = "https://badges-content.teamspeak.com";
/// One badge of the table.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BadgeInfo {
pub name: String,
pub description: String,
/// Its picture's name on TeamSpeak's server, without `.svg`.
pub filename: String,
}
/// The table by GUID (lower case), read once.
static BADGES: LazyLock<HashMap<String, BadgeInfo>> = LazyLock::new(|| {
// Columns: uid, name, description, filename, codes.
records(include_str!("../data/badges.csv"))
.into_iter()
.skip(1)
.filter_map(|mut fields| {
fields.truncate(4);
let [uid, name, description, filename] = <[String; 4]>::try_from(fields).ok()?;
Some((uid.to_ascii_lowercase(), BadgeInfo { name, description, filename }))
})
.collect()
});
/// What a badge GUID stands for; none for one the table does not know.
pub fn info(guid: &str) -> Option<&'static BadgeInfo> {
BADGES.get(&guid.to_ascii_lowercase())
}
/// The address of a badge's picture (an SVG); none for an unknown badge.
pub fn icon_url(guid: &str) -> Option<String> {
let info = info(guid)?;
Some(format!("{CONTENT}/{}/{}.svg", guid.to_ascii_lowercase(), info.filename))
}
/// The records of a CSV text (RFC 4180): fields split at commas; a quoted
/// field may hold commas and line breaks, and `""` for a quote.
fn records(text: &str) -> Vec<Vec<String>> {
let mut records = Vec::new();
let mut record = Vec::new();
let mut field = String::new();
let mut quoted = false;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' if quoted => {
if chars.next_if_eq(&'"').is_some() {
field.push('"');
} else {
quoted = false;
}
}
'"' if field.is_empty() => quoted = true,
',' if !quoted => record.push(std::mem::take(&mut field)),
'\r' if !quoted => {}
'\n' if !quoted => {
record.push(std::mem::take(&mut field));
records.push(std::mem::take(&mut record));
}
c => field.push(c),
}
}
if !field.is_empty() || !record.is_empty() {
record.push(field);
records.push(record);
}
records
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_badges() {
let info = info("4b27be5a-b92a-4b30-8b2d-14b59653f427").unwrap();
assert_eq!(info.name, "20th Anniversary");
assert_eq!(info.description, "Celebrating 20 Years of TeamSpeak");
assert_eq!(info.filename, "20_years");
// Upper case on the wire finds it too.
assert_eq!(super::info("4B27BE5A-B92A-4B30-8B2D-14B59653F427"), Some(info));
assert_eq!(
icon_url("4b27be5a-b92a-4b30-8b2d-14b59653f427").as_deref(),
Some(
"https://badges-content.teamspeak.com/4b27be5a-b92a-4b30-8b2d-14b59653f427/20_years.svg"
)
);
}
#[test]
fn quoted_fields_keep_their_commas() {
let fools = info("05114019-6b46-4b13-b5a1-e5179ef69fb5").unwrap();
assert_eq!(fools.name, "April Fools!");
assert_eq!(
fools.description,
"Roses are red, gaming is fun, you are carrying too much to be able to run :("
);
assert_eq!(fools.filename, "rpg");
let stay = info("7a627d47-5496-4d68-83b5-2c4eafff9b30").unwrap();
assert_eq!(stay.name, "Stay Home, Stay Safe");
assert_eq!(stay.description, "Playing Apart, Staying Connected");
let up = info("0cd924ed-c5ea-459e-b60a-4f1bc0b65f07").unwrap();
assert_eq!(up.filename, "up,_up_and_away!");
}
#[test]
fn unknown_badges() {
assert_eq!(info("00000000-0000-0000-0000-000000000000"), None);
assert_eq!(info(""), None);
assert_eq!(icon_url("00000000-0000-0000-0000-000000000000"), None);
}
#[test]
fn every_row_is_read() {
let rows = include_str!("../data/badges.csv").lines().count() - 1;
assert_eq!(BADGES.len(), rows);
assert!(BADGES.values().all(|b| !b.name.is_empty() && !b.filename.is_empty()));
}
#[test]
fn csv_records() {
assert_eq!(
records("a,\"b, \"\"c\"\"\",\r\n\"multi\nline\",d"),
[vec!["a", "b, \"c\"", ""], vec!["multi\nline", "d"]]
);
assert!(records("").is_empty());
}
}
+7 -39
View File
@@ -7,6 +7,7 @@
use serde::{Deserialize, Serialize};
use crate::percent;
use crate::presence::{ChannelId, ClientId};
fn is_false(b: &bool) -> bool {
@@ -93,7 +94,7 @@ impl FileRef {
let mut channel = None;
for pair in query.split('&') {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
let value = percent_decode(value);
let value = percent::decode(value);
match key.to_ascii_lowercase().as_str() {
"serveruid" => file.server_uid = Some(value).filter(|v| !v.is_empty()),
"channel" | "cid" => channel = value.parse().ok(),
@@ -106,7 +107,7 @@ impl FileRef {
}
}
if file.name.is_empty() {
file.name = percent_decode(host.trim_end_matches('/'));
file.name = percent::decode(host.trim_end_matches('/'));
}
file.channel = channel?;
(!file.name.is_empty()).then_some(file)
@@ -114,15 +115,15 @@ impl FileRef {
/// The link as TeamSpeak clients post it: `[URL=ts3file://…]name[/URL]`.
pub fn to_bbcode(&self) -> String {
let mut url = format!("ts3file://{}?", percent_encode(&self.name));
let mut url = format!("ts3file://{}?", percent::encode(&self.name));
if let Some(uid) = &self.server_uid {
url.push_str(&format!("serverUID={}&", percent_encode(uid)));
url.push_str(&format!("serverUID={}&", percent::encode(uid)));
}
url.push_str(&format!(
"channel={}&path={}&filename={}&isDir={}",
self.channel,
percent_encode(&self.path),
percent_encode(&self.name),
percent::encode(&self.path),
percent::encode(&self.name),
u8::from(self.is_dir)
));
if let Some(size) = self.size {
@@ -157,39 +158,6 @@ pub fn parse_file_links(text: &str) -> Vec<FileRef> {
found
}
/// `%XX` escapes to bytes (a `+` stays: file names keep theirs).
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let hex = |b: u8| (b as char).to_digit(16);
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let (Some(h), Some(l)) =
(bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b)))
{
out.push((h * 16 + l) as u8);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn percent_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
/// Format of messages a relay posts on behalf of a user.
pub fn relay_text(format: &str, nick: &str, text: &str) -> String {
format.replace("{nick}", nick).replace("{text}", text)
+6 -2
View File
@@ -3,17 +3,21 @@
//! Nothing in here does IO; the types describe what a server offers and what
//! the user sees.
pub mod badges;
mod chat;
mod link;
mod percent;
mod presence;
mod server;
mod tree;
pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message};
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,
};
pub use tree::{TreeRow, order_siblings, tree_rows};
pub use tree::{Spacer, TreeRow, channel_title, order_siblings, parse_spacer, tree_rows};
+420
View File
@@ -0,0 +1,420 @@
//! Server links: `ts3server://` (TeamSpeak 3 and 5), `teamspeak://`
//! (TeamSpeak 6) and TeamSpeak's short links on `tmspk.gg`, whose page sends
//! the browser on to a `teamspeak://` link.
use crate::percent;
use crate::presence::ChannelId;
/// What a link opens ([`Link::parse`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Link {
/// A server, and maybe a channel on it.
Server(ServerLink),
/// A TeamSpeak 6 invite code (`tmspk.gg/<code>`,
/// `teamspeak://invite=<code>`): only a TeamSpeak service knows the
/// server it stands for.
Invite(String),
}
/// A server link: the server, and what to join it with (none of it empty).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ServerLink {
/// A host name, an IP address (IPv6 without brackets) or a server
/// nickname.
pub host: String,
pub port: Option<u16>,
pub nickname: Option<String>,
/// The server's password.
pub password: Option<String>,
/// The channel to join: its names from the top, separated by `/` (a `/`
/// in a name as `\/`, [`split_channel_path`]), or `/<id>` (`cid=`).
pub channel: Option<String>,
pub channel_password: Option<String>,
/// A privilege key: it puts its user in a server or channel group.
pub token: Option<String>,
}
const SCHEMES: [&str; 2] = ["ts3server://", "teamspeak://"];
const WEB: [&str; 2] = ["https://", "http://"];
const SHORT_HOSTS: [&str; 2] = ["tmspk.gg", "www.tmspk.gg"];
impl Link {
/// Read a link: `ts3server://<host>?<query>` with the keys `port`,
/// `nickname`, `password`, `channel` (`A/B`), `cid`, `channelpassword`
/// and `token` (`teamspeak://` alike; the scheme and the keys in any
/// case, other keys ignored, a `+` kept as it is),
/// `https://tmspk.gg/s/<host>?<query>` (also `/s=<host>`), and the
/// invite codes `tmspk.gg/<code>` and `teamspeak://invite=<code>`. None
/// for anything else.
pub fn parse(text: &str) -> Option<Link> {
let text = text.trim();
// The same length in bytes: an index of one is one of the other.
let lower = text.to_ascii_lowercase();
match SCHEMES.iter().find(|s| lower.starts_with(**s)) {
Some(scheme) => parse_server(&text[scheme.len()..]),
None => parse_short(text, &lower),
}
}
}
impl ServerLink {
/// A link to the server at `address` (`host`, `host:port`, `[v6]`,
/// `[v6]:port` or a bare IPv6 address), joining nothing.
pub fn new(address: &str) -> Self {
let (host, port) = split_address(address.trim());
ServerLink { host: host.to_owned(), port, ..Default::default() }
}
/// The server's address as a bookmark keeps it: `host`, `host:port` or
/// `[v6]:port`.
pub fn address(&self) -> String {
match self.port {
Some(port) if self.host.contains(':') => format!("[{}]:{port}", self.host),
Some(port) => format!("{}:{port}", self.host),
None => self.host.clone(),
}
}
/// The link as TeamSpeak clients open it: `ts3server://<host>?port=…`,
/// then what is set of nickname, password, channel (or `cid` for
/// `/<id>`), channel password and privilege key.
pub fn to_url(&self) -> String {
let mut url = match self.port {
Some(_) if self.host.contains(':') => format!("ts3server://[{}]", self.host),
_ => format!("ts3server://{}", self.host),
};
let pair = |key: &str, value: &Option<String>| {
let value = value.as_deref().filter(|v| !v.is_empty())?;
Some(format!("{key}={}", percent::encode(value)))
};
let channel = self.channel.as_deref().filter(|c| !c.is_empty()).map(|path| {
match channel_path_id(path) {
Some(id) => format!("cid={id}"),
// A `/` between names, `%2F` in one.
None => {
let names: Vec<String> =
split_channel_path(path).iter().map(|n| percent::encode(n)).collect();
format!("channel={}", names.join("/"))
}
}
});
let query: Vec<String> = [
self.port.map(|port| format!("port={port}")),
pair("nickname", &self.nickname),
pair("password", &self.password),
channel,
pair("channelpassword", &self.channel_password),
pair("token", &self.token),
]
.into_iter()
.flatten()
.collect();
if !query.is_empty() {
url.push('?');
url.push_str(&query.join("&"));
}
url
}
}
/// A channel path's names from the top: `Gaming/Raid Night` →
/// `["Gaming", "Raid Night"]`, `AC\/DC` → `["AC/DC"]`.
pub fn split_channel_path(path: &str) -> Vec<String> {
let mut names = Vec::new();
let mut name = String::new();
let mut chars = path.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\\' if chars.peek() == Some(&'/') => {
name.push('/');
chars.next();
}
'/' => names.push(std::mem::take(&mut name)),
c => name.push(c),
}
}
names.push(name);
names
}
/// A channel path from its names from the top, a `/` in a name as `\/`:
/// the reverse of [`split_channel_path`].
pub fn join_channel_path(names: &[impl AsRef<str>]) -> String {
names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::<Vec<_>>().join("/")
}
/// The channel id of a path `/<id>` (what `cid=` gives).
pub fn channel_path_id(path: &str) -> Option<ChannelId> {
let id = path.strip_prefix('/')?;
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
id.parse().ok()
}
/// After `ts3server://` or `teamspeak://`: `<host>[:port][/]?<query>`, or
/// `invite=<code>`.
fn parse_server(rest: &str) -> Option<Link> {
let (head, query) = rest.split_once('?').unwrap_or((rest, ""));
let authority = head.split('/').next().unwrap_or_default();
if let Some(key) = authority.get(..7).filter(|k| k.eq_ignore_ascii_case("invite=")) {
let code = percent::decode(&authority[key.len()..]);
return (!code.is_empty()).then_some(Link::Invite(code));
}
let authority = percent::decode(authority);
let (host, port) = split_address(&authority);
if host.is_empty() || host.chars().any(|c| c.is_whitespace() || c.is_control()) {
return None;
}
let mut link = ServerLink { host: host.to_owned(), port, ..Default::default() };
let mut cid = None;
for pair in query.split('&') {
let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
let value = Some(percent::decode(raw)).filter(|v| !v.is_empty());
match key.to_ascii_lowercase().as_str() {
// One that is no port is ignored.
"port" => link.port = value.as_deref().and_then(parse_port).or(link.port),
"nickname" => link.nickname = value,
"password" => link.password = value,
// A `/` between names, `%2F` in one.
"channel" => {
let names: Vec<String> = raw.split('/').map(percent::decode).collect();
link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != "");
}
"cid" => cid = value.and_then(|v| v.parse::<ChannelId>().ok()).filter(|c| *c != 0),
"channelpassword" => link.channel_password = value,
"token" => link.token = value,
_ => {}
}
}
// The id names one channel for sure.
if let Some(cid) = cid {
link.channel = Some(format!("/{cid}"));
}
Some(Link::Server(link))
}
/// `tmspk.gg/s/<host>?…` (or `/s=`), with or without `https://`, goes where
/// its page sends the browser: `teamspeak://<host>?…`; any other path is an
/// invite code.
fn parse_short(text: &str, lower: &str) -> Option<Link> {
let start = WEB.iter().find(|s| lower.starts_with(**s)).map_or(0, |s| s.len());
let (host, path) = text[start..].split_once('/')?;
if !SHORT_HOSTS.contains(&host.to_ascii_lowercase().as_str()) {
return None;
}
if path.get(..2).is_some_and(|s| s.eq_ignore_ascii_case("s/") || s.eq_ignore_ascii_case("s=")) {
return parse_server(&path[2..]);
}
let code = path.split(['?', '#', '/']).next().unwrap_or_default();
let valid = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_');
(!code.is_empty() && code.bytes().all(valid)).then(|| Link::Invite(code.to_owned()))
}
/// `host`, `host:port`, `[v6]`, `[v6]:port` or a bare IPv6 address: the
/// host (an IPv6 address without its brackets) and the port, if one is
/// given that is one.
fn split_address(address: &str) -> (&str, Option<u16>) {
if let Some((host, after)) = address.strip_prefix('[').and_then(|a| a.split_once(']')) {
return (host, after.strip_prefix(':').and_then(parse_port));
}
match address.rsplit_once(':') {
// A port follows the only colon; more colons: an IPv6 address.
Some((host, port))
if !host.contains(':')
&& !port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit()) =>
{
(host, parse_port(port))
}
_ => (address, None),
}
}
fn parse_port(text: &str) -> Option<u16> {
text.parse().ok().filter(|p| *p != 0)
}
#[cfg(test)]
mod tests {
use super::*;
fn server(text: &str) -> ServerLink {
match Link::parse(text) {
Some(Link::Server(link)) => link,
other => panic!("{text}: {other:?}"),
}
}
fn host(host: &str, port: Option<u16>) -> ServerLink {
ServerLink { host: host.into(), port, ..Default::default() }
}
#[test]
fn every_parameter() {
let link = server(
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid+1&token=AbC%2Bd&addbookmark=Mine",
);
assert_eq!(
link,
ServerLink {
host: "ts.example.org".into(),
port: Some(9988),
nickname: Some("Nova X".into()),
password: Some("s3cr?t".into()),
channel: Some("Gaming/Raid Night".into()),
// A `+` stays.
channel_password: Some("raid+1".into()),
token: Some("AbC+d".into()),
}
);
assert_eq!(link.address(), "ts.example.org:9988");
assert_eq!(
link.to_url(),
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid%2B1&token=AbC%2Bd"
);
assert_eq!(Link::parse(&link.to_url()), Some(Link::Server(link)));
// A channel id names the channel, also next to a path.
assert_eq!(server("ts3server://h?cid=12").channel.as_deref(), Some("/12"));
assert_eq!(server("ts3server://h?channel=Lobby&cid=12").channel.as_deref(), Some("/12"));
assert_eq!(server("ts3server://h?cid=x&channel=Lobby").channel.as_deref(), Some("Lobby"));
assert_eq!(server("ts3server://h?cid=12").to_url(), "ts3server://h?cid=12");
// Empty values are none.
assert_eq!(server("ts3server://h?nickname=&channel=&password"), host("h", None));
}
#[test]
fn teamspeak_scheme_is_the_same() {
let query = "ts.example.org?port=9987&channel=Lobby&nickname=Nova";
assert_eq!(
Link::parse(&format!("teamspeak://{query}")),
Link::parse(&format!("ts3server://{query}"))
);
// Any case, of the scheme and the keys; the host as written.
let link = server("TeamSpeak://TS.Example.org/?PORT=9988&Channel=Lobby&CID=");
assert_eq!(
link,
ServerLink { channel: Some("Lobby".into()), ..host("TS.Example.org", Some(9988)) }
);
assert_eq!(server("TS3SERVER://h:9988"), host("h", Some(9988)));
}
#[test]
fn short_links() {
for text in [
"https://tmspk.gg/s/ts.example.org?port=9988&channel=Lobby",
"https://tmspk.gg/s=ts.example.org?port=9988&channel=Lobby",
"HTTPS://www.TMSPK.gg/S/ts.example.org?port=9988&channel=Lobby",
"tmspk.gg/s/ts.example.org/?port=9988&channel=Lobby",
"http://tmspk.gg/s/ts.example.org:9988?channel=Lobby",
] {
assert_eq!(
server(text),
ServerLink { channel: Some("Lobby".into()), ..host("ts.example.org", Some(9988)) },
"{text}"
);
}
let invite = |code: &str| Some(Link::Invite(code.into()));
assert_eq!(Link::parse("https://tmspk.gg/AbC12x"), invite("AbC12x"));
assert_eq!(Link::parse("tmspk.gg/AbC12x/?ref=1"), invite("AbC12x"));
assert_eq!(Link::parse("teamspeak://invite=AbC12x"), invite("AbC12x"));
assert_eq!(Link::parse("TEAMSPEAK://Invite=AbC12x/"), invite("AbC12x"));
for text in ["https://tmspk.gg/", "https://tmspk.gg", "tmspk.gg/a.b", "teamspeak://invite="]
{
assert_eq!(Link::parse(text), None, "{text}");
}
}
#[test]
fn ipv6() {
let v6 = host("2001:db8::1", Some(9987));
assert_eq!(server("ts3server://[2001:db8::1]?port=9987"), v6);
assert_eq!(server("ts3server://[2001:db8::1]:9987"), v6);
assert_eq!(v6.address(), "[2001:db8::1]:9987");
assert_eq!(v6.to_url(), "ts3server://[2001:db8::1]?port=9987");
// Without a port, with or without brackets.
let bare = host("2001:db8::1", None);
assert_eq!(server("ts3server://2001:db8::1"), bare);
assert_eq!(server("ts3server://[2001:db8::1]"), bare);
assert_eq!(bare.address(), "2001:db8::1");
assert_eq!(ServerLink::new(" [2001:db8::1]:9988 "), host("2001:db8::1", Some(9988)));
}
#[test]
fn escapes() {
let link = server("ts3server://h?channel=%C3%84rger/Caf%C3%A9&nickname=J%C3%BCrgen");
assert_eq!(link.channel.as_deref(), Some("Ärger/Café"));
assert_eq!(link.nickname.as_deref(), Some("Jürgen"));
// `%2F` is a `/` in a name.
let link = server("ts3server://h?channel=AC%2FDC/Live");
assert_eq!(link.channel.as_deref(), Some("AC\\/DC/Live"));
assert_eq!(split_channel_path("AC\\/DC/Live"), ["AC/DC", "Live"]);
assert_eq!(join_channel_path(&["AC/DC", "Live"]), "AC\\/DC/Live");
assert_eq!(link.to_url(), "ts3server://h?channel=AC%2FDC/Live");
assert_eq!(split_channel_path("Lobby"), ["Lobby"]);
assert_eq!(channel_path_id("/12"), Some(12));
assert_eq!(channel_path_id("12"), None);
assert_eq!(channel_path_id("/1a"), None);
}
#[test]
fn invalid_ports_are_ignored() {
for text in [
"ts3server://h?port=abc",
"ts3server://h?port=70000",
"ts3server://h?port=0",
"ts3server://h?port=",
"ts3server://h:70000",
] {
assert_eq!(server(text), host("h", None), "{text}");
}
// One in the address stays.
assert_eq!(server("ts3server://h:9988?port=x"), host("h", Some(9988)));
}
#[test]
fn other_links_are_none() {
for text in [
"",
"http://example.com",
"https://example.com/s/ts.example.org",
"ts3file://a.png?serverUID=x&channel=1",
"ts3server://",
"ts3server://?port=9987",
"ts3server://a b",
"ts.example.org",
"mailto:a@example.org",
] {
assert_eq!(Link::parse(text), None, "{text:?}");
}
}
#[test]
fn round_trip() {
// The invite links of voelin-ui (`vm::servers::invite_link`).
for (address, names, url) in [
(
"ts.example.com:9988",
&["Gaming", "Raid Night"][..],
"ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night",
),
(" ts.example.com ", &[], "ts3server://ts.example.com"),
(
"[2001:db8::1]:9987",
&["Chill & Co"],
"ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co",
),
("2001:db8::1", &[], "ts3server://2001:db8::1"),
("h:x", &["Ä/b"], "ts3server://h:x?channel=%C3%84%2Fb"),
] {
let mut link = ServerLink::new(address);
link.channel = (!names.is_empty()).then(|| join_channel_path(names));
assert_eq!(link.to_url(), url);
assert_eq!(Link::parse(url), Some(Link::Server(link.clone())), "{url}");
assert_eq!(link.address(), address.trim());
if let Some(path) = &link.channel {
assert_eq!(split_channel_path(path), names);
}
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! Percent escapes in links: file links ([`crate::FileRef`]) and server
//! links ([`crate::Link`]).
/// `%XX` escapes to bytes, read as UTF-8 (a `+` stays: file names and
/// passwords keep theirs).
pub(crate) fn decode(s: &str) -> String {
let bytes = s.as_bytes();
let hex = |b: u8| (b as char).to_digit(16);
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let (Some(h), Some(l)) =
(bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b)))
{
out.push((h * 16 + l) as u8);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Every byte but letters, digits and `-._~` as `%XX`.
pub(crate) fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes() {
assert_eq!(decode("Raid%20Night"), "Raid Night");
assert_eq!(decode("%C3%84b"), "Äb");
assert_eq!(decode("a+b"), "a+b");
// A broken escape stays as it is.
assert_eq!(decode("100%"), "100%");
assert_eq!(decode("%zz"), "%zz");
assert_eq!(encode("Chill & Co/Ä"), "Chill%20%26%20Co%2F%C3%84");
assert_eq!(decode(&encode("a b+c%")), "a b+c%");
}
}
+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();
+5
View File
@@ -184,6 +184,11 @@ pub struct ServerDetails {
pub version: String,
#[serde(default)]
pub max_clients: u16,
/// How much everyone else is dimmed while a priority speaker talks
/// (dB, e.g. -18; `virtualserver_priority_speaker_dimm_modificator`,
/// rounded).
#[serde(default)]
pub priority_speaker_dimm_db: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_server_group: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
+77 -1
View File
@@ -1,4 +1,5 @@
//! Flatten presence into display rows in TeamSpeak's channel order.
//! Flatten presence into display rows in TeamSpeak's channel order, and
//! read the names of spacer channels.
use std::collections::HashMap;
@@ -64,6 +65,51 @@ fn add_level<'a>(
}
}
/// How a TeamSpeak spacer channel draws its text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Spacer {
Left,
Center,
Right,
/// The text repeated across the row: a line such as `---`.
Fill,
}
impl Spacer {
/// Whether a spacer with this text only separates the rows around it
/// (a line, or no text): nothing to search for or pick.
pub fn separates(self, text: &str) -> bool {
self == Spacer::Fill || text.trim().is_empty()
}
}
/// A spacer name split into its kind and its text: `[cspacer]Games` is a
/// centred "Games", `[*spacer1]-=` repeats "-=", plain `[spacer3]` is an
/// empty row. The part between `spacer` and `]` only keeps the names
/// unique, so anything goes there. Anything else is not a spacer.
pub fn parse_spacer(name: &str) -> Option<(Spacer, &str)> {
let (inside, text) = name.strip_prefix('[')?.split_once(']')?;
let (kind, _suffix) = inside.split_once("spacer")?;
let kind = match kind {
"" | "l" => Spacer::Left,
"c" => Spacer::Center,
"r" => Spacer::Right,
"*" => Spacer::Fill,
_ => return None,
};
Some((kind, text))
}
/// A channel's name as shown, and its spacer kind. Only top-level channels
/// are spacers, as in TeamSpeak: a sub-channel keeps its name as it is.
/// Names sent to the server (joining by name, invite links) stay raw.
pub fn channel_title(channel: &ChannelInfo) -> (&str, Option<Spacer>) {
match parse_spacer(&channel.name).filter(|_| channel.parent == 0) {
Some((kind, text)) => (text, Some(kind)),
None => (&channel.name, None),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -113,4 +159,34 @@ mod tests {
["0#Lobby", "1-Alice", "1-zed", "0#Games"]
);
}
#[test]
fn spacer_names() {
use Spacer::*;
for (name, spacer) in [
("[spacer0]", Some((Left, ""))),
("[spacer3]Hi", Some((Left, "Hi"))),
("[lspacer]Hi", Some((Left, "Hi"))),
("[rspacer9]Hi", Some((Right, "Hi"))),
("[cspacer]Hi", Some((Center, "Hi"))),
("[cspacerx]Hi", Some((Center, "Hi"))),
("[cspacer12]Гамесы [1]", Some((Center, "Гамесы [1]"))),
("[*spacer1]-=", Some((Fill, "-="))),
("[*spacer]", Some((Fill, ""))),
("[cspacer2Games", None),
("Games", None),
("[Spacer]x", None),
("[xspacer]x", None),
("[spacr]x", None),
("x[spacer]", None),
] {
assert_eq!(parse_spacer(name), spacer, "{name}");
}
assert!(Fill.separates("-=") && Left.separates("") && Center.separates(" "));
assert!(!Left.separates("Hi"));
// Only top-level channels are spacers: a sub-channel keeps its name.
assert_eq!(channel_title(&ch(1, 0, 0, "[rspacer]Staff")), ("Staff", Some(Right)));
assert_eq!(channel_title(&ch(2, 1, 0, "[rspacer]Staff")), ("[rspacer]Staff", None));
assert_eq!(channel_title(&ch(3, 0, 0, "Lobby")), ("Lobby", None));
}
}
+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)
}
}
+93 -1
View File
@@ -16,7 +16,8 @@
//! of the other, or (without both unique ids) the same nickname.
//!
//! Pages are by time: `(ts_ms, id)` orders a chat ([`PageQuery`]). A
//! [`ChatCursor`] remembers how far a chat is synced with a gateway.
//! [`ChatCursor`] remembers how far a chat is synced with a gateway, a
//! [`ChatRead`] how far it was read on this device.
use rusqlite::{OptionalExtension, Row, Transaction, params};
use serde::{Deserialize, Serialize};
@@ -226,6 +227,31 @@ pub struct ChatCursor {
pub updated_ms: i64,
}
/// How far a chat was read on this device: the newest message read, by
/// `(ts_ms, id)` as a chat is ordered. TeamSpeak has no read receipts, so
/// this stays on the device.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChatRead {
/// Unix milliseconds of the message.
pub ts_ms: i64,
/// Its local id ([`StoredMessage::id`]).
pub id: i64,
/// Unix milliseconds of the last change.
pub updated_ms: i64,
}
/// Version 5: how far each chat was read ([`ChatRead`]).
pub(crate) const SCHEMA_5: &str = r#"
CREATE TABLE chat_reads (
server_uid TEXT NOT NULL,
target TEXT NOT NULL,
read_ms INTEGER NOT NULL,
read_id INTEGER NOT NULL DEFAULT 0,
updated_ms INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (server_uid, target)
) WITHOUT ROWID;
"#;
/// Version 2: times in milliseconds, sources, gateway ids and metadata,
/// dedupe keys, sync cursors and server aliases. Old messages keep their
/// data (source `local`, their second times in milliseconds).
@@ -686,6 +712,53 @@ impl Store {
Ok(())
}
/// How far a chat was read on this device.
pub fn chat_read(&self, server_uid: &str, target: &ChatTarget) -> Result<Option<ChatRead>> {
Ok(self
.db
.prepare_cached(
"SELECT read_ms, read_id, updated_ms FROM chat_reads
WHERE server_uid = ?1 AND target = ?2",
)?
.query_row(params![server_uid, target.key()], |r| {
Ok(ChatRead { ts_ms: r.get(0)?, id: r.get(1)?, updated_ms: r.get(2)? })
})
.optional()?)
}
/// How far each chat of a server was read on this device.
pub fn chat_reads(&self, server_uid: &str) -> Result<Vec<(ChatTarget, ChatRead)>> {
let mut stmt = self.db.prepare_cached(
"SELECT target, read_ms, read_id, updated_ms FROM chat_reads
WHERE server_uid = ?1 ORDER BY target",
)?;
let rows = stmt.query_map([server_uid], |r| {
let target: String = r.get(0)?;
let read = ChatRead { ts_ms: r.get(1)?, id: r.get(2)?, updated_ms: r.get(3)? };
Ok((ChatTarget::from_key(&target), read))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Remember how far a chat was read on this device (replacing what was
/// there).
pub fn set_chat_read(
&self,
server_uid: &str,
target: &ChatTarget,
read: &ChatRead,
) -> Result<()> {
self.db
.prepare_cached(
"INSERT INTO chat_reads (server_uid, target, read_ms, read_id, updated_ms)
VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT (server_uid, target) DO UPDATE SET read_ms = excluded.read_ms,
read_id = excluded.read_id, updated_ms = excluded.updated_ms",
)?
.execute(params![server_uid, target.key(), read.ts_ms, read.id, read.updated_ms])?;
Ok(())
}
/// Forget the gateway ids of a chat (another gateway numbers its
/// messages differently) and its cursor; the rows stay, as seen by this
/// device, and are matched again with the new gateway's copies.
@@ -962,6 +1035,25 @@ mod tests {
assert_eq!(store.server_alias("voice:host").unwrap().as_deref(), Some("uid2"));
}
#[test]
fn read_markers() {
let store = Store::open_in_memory().unwrap();
let (channel, dm) = (ChatTarget::Channel(1), ChatTarget::Private("uid-b".into()));
assert_eq!(store.chat_read(SRV, &channel).unwrap(), None);
assert!(store.chat_reads(SRV).unwrap().is_empty());
let read = ChatRead { ts_ms: 1_000, id: 7, updated_ms: 5 };
store.set_chat_read(SRV, &channel, &read).unwrap();
assert_eq!(store.chat_read(SRV, &channel).unwrap(), Some(read));
// Set again: the same row, moved.
let later = ChatRead { ts_ms: 2_000, id: 9, updated_ms: 6 };
store.set_chat_read(SRV, &channel, &later).unwrap();
assert_eq!(store.chat_read(SRV, &channel).unwrap(), Some(later));
store.set_chat_read(SRV, &dm, &read).unwrap();
store.set_chat_read("other", &channel, &read).unwrap();
assert_eq!(store.chat_reads(SRV).unwrap(), [(channel.clone(), later), (dm, read)]);
assert_eq!(store.chat_reads("other").unwrap(), [(channel, read)]);
}
/// A database of version 1 with messages is upgraded in place.
#[test]
fn migrates_version_1_with_data() {
+1 -1
View File
@@ -14,7 +14,7 @@ mod secrets;
mod store;
pub use chat::{
ChatCursor, ChatTarget, MessageSource, NewMessage, PageQuery, Reaction, RemoteInfo,
ChatCursor, ChatRead, ChatTarget, MessageSource, NewMessage, PageQuery, Reaction, RemoteInfo,
StoredMessage, SyncState, WriteOutcome, Written,
};
pub use contacts::{Contact, ContactSeen, Relation};
+111 -1
View File
@@ -23,6 +23,7 @@ const MIGRATIONS: &[Migration] = &[
Migration::Code(crate::chat::migrate_2),
Migration::Sql(crate::contacts::SCHEMA_3),
Migration::Sql(SCHEMA_4),
Migration::Sql(crate::chat::SCHEMA_5),
];
/// Version 4: where each identity came from ([`IdentityOrigin`]) and which
@@ -147,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.
@@ -167,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()
@@ -531,6 +569,48 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// A database of version 4 learns where its chats were read, keeping
/// its messages; nothing is read yet.
#[test]
fn migrates_version_4_read_markers() {
use crate::{ChatRead, ChatTarget, PageQuery};
let dir = std::env::temp_dir().join(format!("voelin-store-v4-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("client.db");
{
let mut db = rusqlite::Connection::open(&path).unwrap();
db.execute_batch(SCHEMA_1).unwrap();
let tx = db.transaction().unwrap();
crate::chat::migrate_2(&tx).unwrap();
tx.commit().unwrap();
db.execute_batch(crate::contacts::SCHEMA_3).unwrap();
db.execute_batch(SCHEMA_4).unwrap();
db.pragma_update(None, "user_version", 4).unwrap();
db.execute(
"INSERT INTO messages (server_uid, target, ts, ts_ms, author_name, text)
VALUES ('srv', 'channel/1', 1, 1000, 'a', 'kept')",
[],
)
.unwrap();
}
let store = Store::open(&path).unwrap();
assert_eq!(Store::SCHEMA_VERSION, 5);
assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION);
let channel = ChatTarget::Channel(1);
let rows = store.messages("srv", &channel, PageQuery::default()).unwrap();
assert_eq!(rows.len(), 1);
assert!(store.chat_reads("srv").unwrap().is_empty());
let read = ChatRead { ts_ms: rows[0].ts_ms, id: rows[0].id, updated_ms: 1 };
store.set_chat_read("srv", &channel, &read).unwrap();
drop(store);
// Opened again: the marker is there and nothing runs twice.
let store = Store::open(&path).unwrap();
assert_eq!(store.chat_read("srv", &channel).unwrap(), Some(read));
drop(store);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn bookmarks_keep_order_and_fields() {
let store = Store::open_in_memory().unwrap();
@@ -562,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();
+8 -2
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"
@@ -50,7 +50,9 @@ tsclientlib = { path = "../proto/tsclientlib" }
# and PipeWire, global hotkeys through the portal and X11.
[target.'cfg(not(target_os = "android"))'.dependencies]
voelin-myts = { path = "../voelin-myts" }
slint = { version = "1.18", features = ["renderer-software"] }
# winit's focus events (an unstable API, so this minor version only):
# messages are read only while the window has the focus (`app::watch_focus`).
slint = { version = "~1.18", features = ["renderer-software", "unstable-winit-030"] }
voelin-core = { path = "../voelin-core", default-features = false, features = ["media-desktop"] }
voelin-platform = { path = "../voelin-platform" }
voelin-store = { path = "../voelin-store", features = ["keyring"] }
@@ -67,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
+391 -30
View File
@@ -24,9 +24,10 @@ use voelin_core::settings::{
};
use voelin_core::stream::StreamInfo;
use voelin_core::{
AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState,
AudioSettings, Command, Engine, Event, History, HistoryMessage, ObserveState, SessionState,
VoiceState,
};
use voelin_model::{Capabilities, ChannelId, ChatTarget, GroupInfo, Presence};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence};
use voelin_platform::crash;
use voelin_store::{Bookmark, MemorySecrets, Secrets, Store};
@@ -144,7 +145,17 @@ pub(crate) struct Tab {
/// Live messages of a session that keeps no history (no server unique
/// id yet): grouped from the message before, without ids.
pub last: Option<Previous>,
/// Messages not read, not ours: those after `read` (without stored
/// history, those that came while the tab was not on screen).
pub unread: i32,
/// The newest message read, by `(ts_ms, id)`: kept in the store
/// (`chat_reads`) when the tab is left, the session closes and on exit
/// (`App::save_read`). `stored_read` is what the store has.
pub read: Option<(i64, i64)>,
pub stored_read: Option<(i64, i64)>,
/// The message the "New" divider is above: the first that was new when
/// the tab came on screen. It stays until the tab is left.
pub divider: Option<i64>,
/// Nothing older exists as far as the engine can tell.
pub complete: bool,
/// A gateway page arrived: the chat is not only what we saw.
@@ -163,6 +174,8 @@ pub(crate) struct Tab {
pub topic_messages: Vec<Msg>,
/// The message jumped to from the pins.
pub marked: Option<i64>,
/// What the lines of `messages` were built from.
pub cache: crate::vm::chat::LineCache,
}
impl Tab {
@@ -174,6 +187,9 @@ impl Tab {
messages: Vec::new(),
last: None,
unread: 0,
read: None,
stored_read: None,
divider: None,
complete: false,
synced: false,
loading: false,
@@ -185,9 +201,15 @@ impl Tab {
topic: None,
topic_messages: Vec::new(),
marked: None,
cache: Default::default(),
}
}
/// A private chat (on the Direct Messages page, not in the chat strip).
pub fn is_private(&self) -> bool {
matches!(self.target, ChatTarget::Private(_))
}
/// A handle for a message that has none yet.
pub fn take_key(&mut self) -> i32 {
self.next_key += 1;
@@ -197,6 +219,50 @@ impl Tab {
pub fn message(&self, key: i32) -> Option<&HistoryMessage> {
self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message)
}
/// Where each message is and whether it is ours (`own`), for the read
/// markers ([`crate::vm::chat::first_unread`]).
pub fn positions(&self, own: impl Fn(&ChatMessage) -> bool) -> Vec<(i64, i64, bool)> {
self.messages
.iter()
.map(|m| (m.message.message.ts_ms, m.message.id, own(&m.message.message)))
.collect()
}
/// Where the newest message is.
pub fn newest(&self) -> Option<(i64, i64)> {
self.messages.last().map(|m| (m.message.message.ts_ms, m.message.id))
}
/// The tab came on screen: the first new message gets the divider
/// (unless one shows), and everything is read.
pub fn enter(&mut self, own: impl Fn(&ChatMessage) -> bool) {
if self.unread > 0 && self.divider.is_none() {
let first = crate::vm::chat::first_unread(&self.positions(own), self.read);
self.divider = first.map(|i| self.messages[i].message.id);
}
self.catch_up();
}
/// Everything in the tab is read (it is on screen).
pub fn catch_up(&mut self) {
self.read = self.read.max(self.newest());
self.unread = 0;
}
/// Count what is not read: what came after `read`, not ours.
pub fn count_unread(&mut self, own: impl Fn(&ChatMessage) -> bool) {
self.unread = crate::vm::chat::unread_count(&self.positions(own), self.read);
}
/// Start from where the store says the chat was read (`reads`: by the
/// store's name of the chat).
pub fn read_from(&mut self, reads: &HashMap<String, (i64, i64)>) {
if let Some(&read) = reads.get(&crate::chat::store_target(&self.target).key()) {
self.read = self.read.max(Some(read));
self.stored_read = Some(read);
}
}
}
/// What we know about one server session.
@@ -208,6 +274,10 @@ pub(crate) struct SessionView {
pub talking: HashSet<u16>,
pub tabs: Vec<Tab>,
pub current_tab: usize,
/// The chat strip's chat last current (the server's or a channel's): a
/// private chat is current only on the Direct Messages page, and this
/// one is current again when that page is left.
pub channel_tab: ChatTarget,
/// The own channel's tab was focused for this voice connection.
pub focused_own_channel: bool,
/// The streams in our channel (TeamSpeak 6).
@@ -219,7 +289,8 @@ pub(crate) struct SessionView {
pub avatars: HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
pub icons: HashMap<u32, PathBuf>,
/// Banners in the engine's cache, by address ([`Event::PictureReady`]).
/// Banners and badges in the engine's cache, by address
/// ([`Event::PictureReady`]).
pub pictures: HashMap<String, PathBuf>,
/// The server's icon id as its voice connection last told it
/// ([`Event::ServerDetails`]); kept while disconnected, for the rail.
@@ -234,6 +305,11 @@ pub(crate) struct SessionView {
pub gateway_caps: Vec<String>,
/// The client whose member card is open.
pub member_card: Option<u16>,
/// Passwords given for locked channels, until voice disconnects.
pub channel_passwords: HashMap<ChannelId, String>,
/// The channel a voice connection was asked into, until it is joined
/// or joined again (`App::join_after_connect`).
pub join_after_connect: Option<ChannelId>,
/// Viewers of the streams in the gateway's directory, by stream id.
pub stream_viewers: HashMap<String, u32>,
/// Downloads started from chat, by transfer id.
@@ -242,6 +318,10 @@ pub(crate) struct SessionView {
pub next_transfer: u64,
/// What the home, messages and events screens keep of the session.
pub extra: crate::social::SessionExtra,
/// Where its chats were read, from the store (by the store's name of
/// the chat), for the server unique id `reads_of`.
pub reads: HashMap<String, (i64, i64)>,
pub reads_of: Option<String>,
}
impl Default for SessionView {
@@ -254,6 +334,7 @@ impl Default for SessionView {
talking: HashSet::new(),
tabs: vec![Tab::new(ChatTarget::Server, "Server".into())],
current_tab: 0,
channel_tab: ChatTarget::Server,
focused_own_channel: false,
streams: Vec::new(),
applied_playback: HashSet::new(),
@@ -266,10 +347,14 @@ impl Default for SessionView {
channel_groups: Vec::new(),
gateway_caps: Vec::new(),
member_card: None,
channel_passwords: HashMap::new(),
join_after_connect: None,
stream_viewers: HashMap::new(),
downloads: HashMap::new(),
next_transfer: 1,
extra: Default::default(),
reads: HashMap::new(),
reads_of: None,
}
}
}
@@ -290,7 +375,7 @@ impl SessionView {
self.channel_of(client)
.filter(|c| Some(*c) != self.state.own_channel)
.and_then(|c| self.presence.channels.get(&c))
.map_or_else(String::new, |c| c.name.clone())
.map_or_else(String::new, |c| crate::vm::tree::channel_title(c).0.to_owned())
}
/// A client's nickname, or its id.
@@ -301,9 +386,69 @@ impl SessionView {
.map_or_else(|| format!("client {client}"), |c| c.nickname.clone())
}
/// Unread messages in all chats.
pub fn unread(&self) -> i32 {
self.tabs.iter().map(|t| t.unread).sum()
/// Unread messages in the server's and the channels' chats (the rail and
/// the chat strip count them; private chats count on the Direct
/// Messages page).
pub fn channel_unread(&self) -> i32 {
self.tabs.iter().filter(|t| !t.is_private()).map(|t| t.unread).sum()
}
/// Unread messages in private chats.
pub fn private_unread(&self) -> i32 {
self.tabs.iter().filter(|t| t.is_private()).map(|t| t.unread).sum()
}
/// Make tab `index` the current one; the chat strip remembers it unless
/// it is a private chat.
pub fn set_current_tab(&mut self, index: usize) {
self.current_tab = index;
if let Some(tab) = self.tabs.get(index).filter(|t| !t.is_private()) {
self.channel_tab = tab.target.clone();
}
}
/// Focus tab `index`. While a private chat is current (the Direct
/// Messages page shows it, and its composer sends there), a chat of the
/// strip does not take its place: it is the strip's chat, current once
/// that page is left (voice connecting focuses its channel's chat).
pub fn focus_tab(&mut self, index: usize) {
let Some(tab) = self.tabs.get(index) else { return };
if !tab.is_private() && self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
self.channel_tab = tab.target.clone();
} else {
self.set_current_tab(index);
}
}
/// Remove tab `index`. The current tab stays; when it is this one, the
/// chat strip's next tab takes its place, else its last.
pub fn remove_tab(&mut self, index: usize) -> Tab {
let tab = self.tabs.remove(index);
if self.current_tab > index {
self.current_tab -= 1;
} else if self.current_tab == index {
let (strip, _) = crate::vm::chat::strip(self.tabs.iter().map(|t| &t.target), 0);
let next = strip.iter().find(|&&i| i >= index).or(strip.last()).copied();
self.set_current_tab(next.unwrap_or(0));
}
tab
}
/// Leave a current private chat for the chat strip's last one (the
/// Direct Messages page was left); `true` if the current tab changed.
pub fn leave_private(&mut self) -> bool {
if !self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
return false;
}
self.current_tab = self.tabs.iter().position(|t| t.target == self.channel_tab).unwrap_or(0);
true
}
/// A new tab for `target`, read as far as the store says.
pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab {
let mut tab = Tab::new(target, title);
tab.read_from(&self.reads);
tab
}
/// The session's gateway offers this feature
@@ -349,7 +494,10 @@ pub(crate) struct Models {
pub tree: Rc<VecModel<TreeItem>>,
pub members: Rc<VecModel<MemberItem>>,
pub server_members: Rc<VecModel<MemberItem>>,
/// The chat strip: the current session's tabs without its private chats.
pub tabs: Rc<VecModel<ChatTab>>,
/// Which of the session's tabs each of `tabs` is ([`crate::vm::chat::strip`]).
pub strip: RefCell<Vec<usize>>,
pub streams: Rc<VecModel<StreamItem>>,
pub viewers: Rc<VecModel<ViewerItem>>,
pub pins: Rc<VecModel<PinItem>>,
@@ -378,6 +526,7 @@ impl Models {
members: Rc::default(),
server_members: Rc::default(),
tabs: Rc::default(),
strip: RefCell::new(vec![0]),
streams: Rc::default(),
viewers: Rc::default(),
pins: Rc::default(),
@@ -393,26 +542,32 @@ impl Models {
gateway_perms: Rc::default(),
all_settings: Rc::default(),
};
bridge.set_servers(ModelRc::from(models.servers.clone()));
bridge.set_tree(ModelRc::from(models.tree.clone()));
bridge.set_members(ModelRc::from(models.members.clone()));
bridge.set_server_members(ModelRc::from(models.server_members.clone()));
bridge.set_tabs(ModelRc::from(models.tabs.clone()));
bridge.set_streams(ModelRc::from(models.streams.clone()));
bridge.set_share_viewers(ModelRc::from(models.viewers.clone()));
bridge.set_pins(ModelRc::from(models.pins.clone()));
bridge.set_topics(ModelRc::from(models.topics.clone()));
bridge.set_topic_messages(ModelRc::from(models.topic_messages.clone()));
bridge.set_viewer_qualities(ModelRc::from(models.qualities.clone()));
bridge.set_messages(ModelRc::from(models.no_chat.clone()));
bridge.set_layers(ModelRc::from(models.layers.clone()));
bridge.set_audio_sources(ModelRc::from(models.audio_sources.clone()));
bridge.set_identities(ModelRc::from(models.identities.clone()));
bridge.set_gateway_config(ModelRc::from(models.gateway_config.clone()));
bridge.set_gateway_perms(ModelRc::from(models.gateway_perms.clone()));
bridge.set_all_settings(ModelRc::from(models.all_settings.clone()));
models.attach(bridge);
models
}
/// Show the models in `bridge`: the main window's, and the viewer's own
/// window's (its player reads the stream's qualities).
pub(crate) fn attach(&self, bridge: &Bridge) {
bridge.set_servers(ModelRc::from(self.servers.clone()));
bridge.set_tree(ModelRc::from(self.tree.clone()));
bridge.set_members(ModelRc::from(self.members.clone()));
bridge.set_server_members(ModelRc::from(self.server_members.clone()));
bridge.set_tabs(ModelRc::from(self.tabs.clone()));
bridge.set_streams(ModelRc::from(self.streams.clone()));
bridge.set_share_viewers(ModelRc::from(self.viewers.clone()));
bridge.set_pins(ModelRc::from(self.pins.clone()));
bridge.set_topics(ModelRc::from(self.topics.clone()));
bridge.set_topic_messages(ModelRc::from(self.topic_messages.clone()));
bridge.set_viewer_qualities(ModelRc::from(self.qualities.clone()));
bridge.set_messages(ModelRc::from(self.no_chat.clone()));
bridge.set_layers(ModelRc::from(self.layers.clone()));
bridge.set_audio_sources(ModelRc::from(self.audio_sources.clone()));
bridge.set_identities(ModelRc::from(self.identities.clone()));
bridge.set_gateway_config(ModelRc::from(self.gateway_config.clone()));
bridge.set_gateway_perms(ModelRc::from(self.gateway_perms.clone()));
bridge.set_all_settings(ModelRc::from(self.all_settings.clone()));
}
}
pub(crate) struct App {
@@ -430,6 +585,9 @@ pub(crate) struct App {
pub sessions: HashMap<i64, SessionView>,
pub models: Models,
pub status: String,
/// What the toast of the next copy says instead of "Copied" (an invite
/// names its channel and link).
pub copy_note: Option<String>,
/// The members panel's search.
pub member_filter: String,
/// The topics drawer's search.
@@ -451,6 +609,16 @@ pub(crate) struct App {
pub contacts: HashMap<String, voelin_core::Contact>,
/// The client in the volume dialog: session, client id, unique id.
pub playback_dialog: Option<(i64, u16, Option<String>)>,
/// The locked channel the password dialog is for: session, channel.
pub join_target: Option<(i64, ChannelId)>,
/// Who the poke dialog pokes: session, client, nickname.
pub poke_target: Option<(i64, u16, String)>,
/// The window has the focus (desktop: winit tells; elsewhere assumed):
/// messages are read only then.
pub focused: bool,
/// The chat whose messages are on screen (session, target): when it is
/// left, it is stored and loses its divider (`App::track_reading`).
pub reading: Option<(i64, ChatTarget)>,
pub mic_test: bool,
pub ptt: GlobalPtt,
pub video: Video,
@@ -487,6 +655,8 @@ pub(crate) struct App {
pub pages: crate::settings_pages::Pages,
/// The Stream Studio (studio.rs).
pub studio: crate::studio::StudioState,
/// The stream's own window (popout.rs).
pub popout: crate::popout::Popout,
}
thread_local! {
@@ -643,6 +813,9 @@ pub fn run(options: RunOptions) -> Result<()> {
let bridge = ui.global::<Bridge>();
bridge.set_app_name(voelin_platform::APP_NAME.into());
bridge.set_app_version(env!("CARGO_PKG_VERSION").into());
bridge.set_desktop(cfg!(not(target_os = "android")));
#[cfg(not(target_os = "android"))]
watch_focus(&ui);
let models = Models::new(&bridge);
// Wayland and X11 find the desktop file (and icon) by this id.
#[cfg(not(target_os = "android"))]
@@ -678,6 +851,7 @@ pub fn run(options: RunOptions) -> Result<()> {
sessions: HashMap::new(),
models,
status: String::new(),
copy_note: None,
member_filter: String::new(),
topic_filter: String::new(),
voice_view: false,
@@ -690,6 +864,10 @@ pub fn run(options: RunOptions) -> Result<()> {
playback,
contacts: HashMap::new(),
playback_dialog: None,
join_target: None,
poke_target: None,
focused: true,
reading: None,
mic_test: false,
ptt,
video,
@@ -709,15 +887,23 @@ pub fn run(options: RunOptions) -> Result<()> {
social: Default::default(),
pages: Default::default(),
studio: Default::default(),
popout: Default::default(),
};
APP.with(|a| *a.borrow_mut() = Some(app));
crate::bind::wire(&ui);
// The studio's and the stream's windows close with the main window,
// so the app ends.
ui.window().on_close_requested(|| {
with_app(App::close_windows);
slint::CloseRequestResponse::HideWindow
});
with_app(|app| {
app.apply_appearance();
app.load_own_uids();
app.apply_srtp();
app.refresh_all();
app.refresh_settings_flags();
app.refresh_transmit();
app.refresh_crash_notice();
app.load_recent_chats();
app.refresh_people();
@@ -764,6 +950,10 @@ pub fn run(options: RunOptions) -> Result<()> {
if let Err(e) = app.prefs.flush() {
warn!(%e, "could not store settings");
}
let ids: Vec<i64> = app.sessions.keys().copied().collect();
for id in ids {
app.save_reads(id);
}
app.watch = None;
app.share = None;
if own && !app.demo_ui {
@@ -783,6 +973,20 @@ pub fn run(options: RunOptions) -> Result<()> {
Ok(())
}
/// Tell the app when the window gains or loses the focus: messages are read
/// only while it has it. (winit's focus events; without them, as on
/// Android, the window counts as focused.)
#[cfg(not(target_os = "android"))]
fn watch_focus(ui: &MainWindow) {
use slint::winit_030::{EventResult, WinitWindowAccessor, winit::event::WindowEvent};
ui.window().on_winit_window_event(|_, event| {
if let WindowEvent::Focused(focused) = *event {
later(move |app| app.window_focused(focused));
}
EventResult::Propagate
});
}
/// Open a file or folder with the desktop's default application.
pub(crate) fn open_path(path: &Path) -> std::io::Result<()> {
open_target(path.as_os_str())
@@ -843,6 +1047,19 @@ impl App {
}
}
/// Open a page on the web in the browser. Pages open through here, so
/// a platform without a desktop opener (Android) can open them its own
/// way.
pub(crate) fn open_url(&self, url: &str) -> std::io::Result<()> {
open_target(std::ffi::OsStr::new(url))
}
/// Nav.copy put text on the clipboard: one toast says so.
pub fn copied(&mut self) {
let text = self.copy_note.take().unwrap_or_else(|| "Copied".to_owned());
self.set_status(text);
}
pub fn store_settings(&self) {
if let Err(e) = self.prefs.set(&UI, self.settings.clone()) {
warn!(%e, "could not store settings");
@@ -855,6 +1072,8 @@ impl App {
fn setting_changed(&mut self, key: &str) {
if key == AUDIO.name() && !self.audio_dirty {
self.audio = self.prefs.get(&AUDIO);
// The voice controls follow the transmit mode.
self.refresh_transmit();
} else if key == CRASH_REPORTS.name() {
let enabled = self.prefs.get(&CRASH_REPORTS);
if enabled != self.settings.crash_reports {
@@ -887,19 +1106,39 @@ impl App {
let id = session as i64;
let view = self.sessions.entry(id).or_default();
let was_voice = view.state.voice;
let was_observe = view.state.observe;
let was_channel = view.state.own_channel;
view.state = state.clone();
if state.voice != VoiceState::Connected {
view.focused_own_channel = false;
}
if state.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected
{
view.channel_passwords.clear();
view.join_after_connect = None;
}
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
// A new connection: volumes are sent again.
view.applied_playback.clear();
}
// Where its chats were read, once the server is known; kept
// when the session ends.
self.load_reads(id);
let off = |voice: VoiceState, observe: ObserveState| {
voice == VoiceState::Disconnected && observe == ObserveState::Off
};
if off(state.voice, state.observe) && !off(was_voice, was_observe) {
self.save_reads(id);
}
let view = self.sessions.entry(id).or_default();
let focus = !view.focused_own_channel;
if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected {
self.set_status("Connected");
}
if self.current == Some(id) {
if self.track_reading() {
self.refresh_chat();
}
// The voice channel's chat is always at hand, and focused
// once per connection.
if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) {
@@ -907,6 +1146,12 @@ impl App {
self.sessions.entry(id).or_default().focused_own_channel = true;
}
}
// Where we are with voice, when it changed here: home's last
// place, which `refresh_servers` shows (voice on another
// server does not take it back at each of its events).
if (state.voice, state.own_channel) != (was_voice, was_channel) {
self.remember_voice(id);
}
self.refresh_servers();
self.refresh_toolbar();
self.refresh_tree();
@@ -915,6 +1160,7 @@ impl App {
if self.open_client_pending && self.current == Some(id) {
self.open_first_client();
}
self.join_after_connect(id);
}
Event::ServerInfo { session, name, flavor, capabilities } => {
self.sessions.entry(session as i64).or_default().capabilities = capabilities;
@@ -931,9 +1177,28 @@ impl App {
self.autoshare();
}
Event::Presence { session, presence } => {
self.sessions.entry(session as i64).or_default().presence = presence;
let view = self.sessions.entry(session as i64).or_default();
// The server chat shows its welcome and host message, with
// their pictures.
let said = crate::chat::server_texts(&view.presence.server)
!= crate::chat::server_texts(&presence.server);
// Our channel's path: known only now (a new connection),
// or renamed.
let path = |v: &SessionView| {
v.state.own_channel.map(|c| crate::vm::tree::channel_path(&v.presence, c))
};
let path_before = path(view);
view.presence = presence;
let renamed = path(view) != path_before;
self.apply_client_playback(session as i64);
self.join_after_connect(session as i64);
if renamed && self.remember_voice(session as i64) {
self.refresh_servers();
}
if self.current == Some(session as i64) {
if said {
self.fetch_previews(session as i64);
}
self.refresh_toolbar();
self.refresh_tree();
self.refresh_chat();
@@ -980,6 +1245,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);
}
@@ -1001,8 +1269,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();
@@ -1014,7 +1282,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) {
@@ -1025,12 +1293,13 @@ 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();
self.refresh_tree();
self.refresh_chat();
self.refresh_member_card();
}
}
Event::Transfer { session, transfer, state } => {
@@ -1045,6 +1314,9 @@ impl App {
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
Event::Error { .. } if self.demo_ui => {}
Event::Error { message, .. } => self.set_status(message),
Event::JoinFailed { session, channel, reason } => {
self.join_failed(session as i64, channel, reason);
}
Event::SettingChanged { key } => self.setting_changed(&key),
Event::SettingRejected { key, message } => {
self.set_status(format!("Setting {key}: {message}"));
@@ -1077,3 +1349,92 @@ impl App {
self.refresh_streams();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channel_unread_ignores_private_tabs() {
let mut view = SessionView::default();
view.tabs.push(Tab::new(ChatTarget::Channel(1), "Lobby".into()));
view.tabs.push(Tab::new(ChatTarget::Private("a".into()), "@Nova".into()));
for (tab, unread) in view.tabs.iter_mut().zip([1, 2, 4]) {
tab.unread = unread;
}
assert_eq!(view.channel_unread(), 3);
assert_eq!(view.private_unread(), 4);
}
/// Closing a tab keeps the current chat, or selects the strip's next
/// one (never a private chat).
#[test]
fn closing_a_tab_keeps_the_current_chat() {
let mut view = SessionView::default();
for target in [
ChatTarget::Channel(1),
ChatTarget::Channel(2),
ChatTarget::Private("a".into()),
ChatTarget::Channel(3),
] {
view.tabs.push(Tab::new(target, String::new()));
}
let current = |v: &SessionView| v.tabs[v.current_tab].target.clone();
view.set_current_tab(2);
view.remove_tab(1);
assert_eq!(current(&view), ChatTarget::Channel(2));
// [Server, 2, @a, 3]: the next tab of the strip, past the private chat.
view.remove_tab(1);
assert_eq!(current(&view), ChatTarget::Channel(3));
assert_eq!(view.channel_tab, ChatTarget::Channel(3));
// The last one: the strip's last, the server chat.
view.remove_tab(2);
assert_eq!(current(&view), ChatTarget::Server);
}
/// A private chat is current only on the Direct Messages page: leaving
/// it goes back to the strip's last chat.
#[test]
fn leaving_a_private_chat_restores_the_strip_tab() {
let mut view = SessionView::default();
view.tabs.push(Tab::new(ChatTarget::Channel(1), "Lobby".into()));
view.tabs.push(Tab::new(ChatTarget::Private("a".into()), "@Nova".into()));
view.set_current_tab(1);
assert!(!view.leave_private());
view.set_current_tab(2);
assert_eq!(view.channel_tab, ChatTarget::Channel(1));
assert!(view.leave_private());
assert_eq!(view.current_tab, 1);
// The strip's chat was closed meanwhile: the server chat.
view.set_current_tab(2);
view.tabs.remove(1);
view.current_tab = 1;
assert!(view.leave_private());
assert_eq!(view.current_tab, 0);
}
/// A channel's chat focused while a private chat is current (voice
/// connecting on the Direct Messages page) waits for the page to be
/// left: the conversation and its composer stay the private chat's.
#[test]
fn a_strip_chat_does_not_replace_a_current_private_chat() {
let mut view = SessionView::default();
view.tabs.push(Tab::new(ChatTarget::Channel(1), "Lobby".into()));
view.tabs.push(Tab::new(ChatTarget::Private("a".into()), "@Nova".into()));
view.tabs.push(Tab::new(ChatTarget::Private("b".into()), "@Ivy".into()));
view.focus_tab(2);
assert_eq!(view.current_tab, 2);
view.focus_tab(1);
assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Channel(1)));
// Another private chat does.
view.focus_tab(3);
assert_eq!(view.current_tab, 3);
assert!(view.leave_private());
assert_eq!(view.current_tab, 1);
// Without a private chat current, any chat.
view.focus_tab(0);
assert_eq!((view.current_tab, &view.channel_tab), (0, &ChatTarget::Server));
view.focus_tab(9);
assert_eq!(view.current_tab, 0);
}
}
+38 -4
View File
@@ -1,6 +1,7 @@
//! Appearance settings (`ui.theme`, `ui.font_scale`, `ui.narrow_breakpoint`,
//! `ui.image_cache_mb`): applied to the Theme and Nav globals and the image
//! cache whenever they change, from the settings page or elsewhere.
//! `ui.image_cache_mb`, `ui.members_width`, `ui.voice_compact`): applied to
//! the Theme and Nav globals and the image cache whenever they change, from
//! the settings page or elsewhere.
use slint::ComponentHandle;
use tracing::warn;
@@ -8,7 +9,8 @@ use tracing::warn;
use crate::app::{App, AppearanceForm, Bridge, Nav, Theme};
use crate::images;
use crate::settings::{
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT, UI_THEME,
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT,
UI_THEME, UI_VOICE_COMPACT,
};
impl App {
@@ -29,6 +31,7 @@ impl App {
if nav.get_right_panel_width() != width {
nav.set_right_panel_width(width);
}
nav.set_voice_compact(self.prefs.get(&UI_VOICE_COMPACT));
let bridge = ui.global::<Bridge>();
bridge.set_appearance(AppearanceForm {
theme: theme.as_str().into(),
@@ -37,7 +40,20 @@ impl App {
image_cache_mb: cache_mb as f32,
});
bridge.set_image_cache_usage(images::usage_text().into());
self.studio_theme();
self.theme_windows();
}
/// The windows of their own (the studio's, the stream's) follow the main
/// window's theme.
pub(crate) fn theme_windows(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let theme = ui.global::<Theme>();
if let Some(window) = &self.studio.window {
copy_theme(&theme, &window.global::<Theme>());
}
if let Some(window) = &self.popout.window {
copy_theme(&theme, &window.global::<Theme>());
}
}
/// The settings page changed the form: store the keys (they apply
@@ -71,4 +87,22 @@ impl App {
warn!(%e, "could not store the panel width");
}
}
/// The voice channel view's stage was made smaller or larger: store it
/// (`ui.voice_compact`), so it comes back the same.
pub(crate) fn voice_compact_changed(&mut self, compact: bool) {
if self.prefs.get(&UI_VOICE_COMPACT) == compact {
return;
}
if let Err(e) = self.prefs.set(&UI_VOICE_COMPACT, compact) {
warn!(%e, "could not store the stage size");
}
}
}
/// Each window has its own Theme global.
fn copy_theme(from: &Theme, to: &Theme) {
to.set_mode(from.get_mode());
to.set_font_scale(from.get_font_scale());
to.set_system_dark(from.get_system_dark());
}
+24 -2
View File
@@ -13,11 +13,20 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_open_channel_chat(|cid| {
with_app(|app| app.open_chat(ChatTarget::Channel(cid as ChannelId), true));
});
// A tab of the chat strip, which leaves out private chats.
bridge.on_select_tab(|i| {
with_app(|app| app.select_tab(i as usize));
with_app(|app| {
if let Some(index) = app.strip_tab(i) {
app.select_tab(index);
}
});
});
bridge.on_close_tab(|i| {
with_app(|app| app.close_tab(i as usize));
with_app(|app| {
if let Some(index) = app.strip_tab(i) {
app.close_tab(index);
}
});
});
bridge.on_send_message(|text| {
with_app(|app| app.send_message(text.to_string()));
@@ -25,6 +34,12 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_load_older(|| {
with_app(App::load_older);
});
bridge.on_mark_read(|| {
with_app(App::mark_read);
});
bridge.on_chat_shown_changed(|| {
with_app(App::chat_shown_changed);
});
bridge.on_react(|key, emoji| {
with_app(|app| app.react(key, emoji.to_string()));
});
@@ -55,12 +70,19 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_create_topic(|key, title| {
with_app(|app| app.create_topic(key, title.to_string()));
});
bridge.on_open_link(|link, masked| {
with_app(|app| app.open_link_text(&link, masked));
});
bridge.on_quote_text(|author, text| crate::vm::chat::quote(&author, &text).into());
bridge.on_open_member(|id| {
with_app(|app| app.open_member(id));
});
bridge.on_member_action(|action| {
with_app(|app| app.member_action(&action));
});
bridge.on_send_poke(|text| {
with_app(|app| app.send_poke(&text));
});
bridge.on_member_volume(|percent| {
with_app(|app| app.member_volume(percent));
});
+4 -1
View File
@@ -1,4 +1,5 @@
//! Emoji: images for the `Images` global, and the picker's rows.
//! Emoji: images for the `Images` global (and an avatar's one letter), and
//! the picker's rows.
use std::rc::Rc;
@@ -7,6 +8,7 @@ use slint::{ComponentHandle, Model, ModelRc, VecModel};
use crate::app::{Emoji, EmojiCell, EmojiRow, Images, MainWindow};
use crate::emoji::{self, PickerEmoji};
use crate::images;
use crate::vm::avatar;
/// Rows of `columns` cells.
fn rows(emoji: Vec<PickerEmoji>, columns: usize) -> Vec<EmojiRow> {
@@ -38,6 +40,7 @@ pub(super) fn wire(ui: &MainWindow) {
let images_global = ui.global::<Images>();
images_global.on_emoji(|key| images::emoji(&key));
images_global.on_emoji_text(|key| emoji::text_of(&key).into());
images_global.on_first_letter(|initials| avatar::first_letter(&initials).into());
let global = ui.global::<Emoji>();
let weak = ui.as_weak();
global.on_load(move || {
+3 -3
View File
@@ -7,18 +7,18 @@ mod pages;
mod servers;
mod settings;
mod social;
mod streams;
pub(crate) mod streams;
pub(crate) mod studio;
use slint::ComponentHandle;
use crate::app::{MainWindow, StudioBridge};
use crate::app::{Bridge, MainWindow, StudioBridge};
/// Connect every callback of the window.
pub(crate) fn wire(ui: &MainWindow) {
servers::wire(ui);
chat::wire(ui);
streams::wire(ui);
streams::wire(&ui.global::<Bridge>());
settings::wire(ui);
emoji::wire(ui);
social::wire(ui);
+13 -7
View File
@@ -4,7 +4,7 @@ use slint::ComponentHandle;
use voelin_core::Command;
use voelin_model::ChannelId;
use crate::app::{Bridge, MainWindow, with_app};
use crate::app::{App, Bridge, MainWindow, with_app};
pub(super) fn wire(ui: &MainWindow) {
let bridge = ui.global::<Bridge>();
@@ -25,13 +25,14 @@ pub(super) fn wire(ui: &MainWindow) {
});
bridge.on_join_channel(|cid| {
with_app(|app| {
app.command(|session| Command::MoveToChannel {
session,
channel: cid as ChannelId,
password: None,
})
if let Some(session) = app.current {
app.join_channel(session, cid as ChannelId);
}
});
});
bridge.on_join_with_password(|password| {
with_app(|app| app.join_with_password(password.to_string()));
});
bridge.on_toggle_collapse(|cid| {
with_app(|app| app.toggle_collapse(cid as ChannelId));
});
@@ -46,8 +47,9 @@ pub(super) fn wire(ui: &MainWindow) {
});
bridge.on_edit_bookmark(|id| with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default());
bridge.on_save_bookmark(|form| {
with_app(|app| app.save_bookmark(form));
with_app(|app| app.save_bookmark(&form));
});
bridge.on_save_and_connect(|form| with_app(|app| app.save_and_connect(&form)).unwrap_or(false));
bridge.on_delete_bookmark(|id| {
with_app(|app| app.delete_bookmark(id as i64));
});
@@ -56,4 +58,8 @@ pub(super) fn wire(ui: &MainWindow) {
with_app(|app| app.client_playback_changed(&form));
});
bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into());
// Nav.copy, from any screen.
bridge.on_copied(|| {
with_app(App::copied);
});
}
+6
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());
@@ -50,6 +53,9 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_panel_resized(|width| {
with_app(|app| app.panel_resized(width));
});
bridge.on_voice_compact_changed(|compact| {
with_app(|app| app.voice_compact_changed(compact));
});
bridge.on_appearance_changed(|form| {
with_app(|app| app.appearance_changed(&form));
});
+13 -3
View File
@@ -3,7 +3,7 @@
use slint::ComponentHandle;
use crate::app::{Bridge, MainWindow, with_app};
use crate::app::{App, Bridge, MainWindow, with_app};
pub(super) fn wire(ui: &MainWindow) {
let bridge = ui.global::<Bridge>();
@@ -26,6 +26,9 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_connect_server(|id| {
with_app(|app| app.connect_server(i64::from(id)));
});
bridge.on_resume(|| {
with_app(|app| app.resume());
});
// Friends.
bridge.on_friends_tab(|tab| {
@@ -108,9 +111,16 @@ pub(super) fn wire(ui: &MainWindow) {
with_app(|app| app.open_preview(key, index)).unwrap_or_default()
});
// Opening the messages or the Library loads what they list.
// Opening the messages or the Library loads what they list; the open
// private chat is the current chat while the messages page shows it.
bridge.on_open_messages(|| {
with_app(|app| app.load_recent_chats());
with_app(|app| {
app.messages_shown();
app.load_recent_chats();
});
});
bridge.on_close_messages(|| {
with_app(App::close_messages);
});
bridge.on_open_library(|| {
with_app(|app| app.load_library());
+10 -6
View File
@@ -1,11 +1,9 @@
//! The streams panel, the share dialog and the viewer.
//! The streams panel, the share dialog and the viewer, for the main window
//! and for the viewer's own window (each has its own Bridge global).
use slint::ComponentHandle;
use crate::app::{Bridge, with_app};
use crate::app::{Bridge, MainWindow, with_app};
pub(super) fn wire(ui: &MainWindow) {
let bridge = ui.global::<Bridge>();
pub(crate) fn wire(bridge: &Bridge) {
bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default());
bridge.on_start_share(|form| {
with_app(|app| app.start_share(form));
@@ -42,6 +40,12 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_toggle_fullscreen(|| {
with_app(|app| app.toggle_fullscreen());
});
bridge.on_pop_out_viewer(|out| {
with_app(|app| if out { app.viewer_pop_out() } else { app.viewer_dock() });
});
bridge.on_show_cursor(|shown| {
with_app(|app| app.viewer_cursor(shown));
});
bridge.on_set_stream_quality(|index| {
with_app(|app| app.set_stream_quality(index));
});
+418 -85
View File
@@ -1,5 +1,7 @@
//! Chat: tabs per session (server, channels, private chats), their
//! messages, and what a gateway adds to them (pins, reactions, topics).
//! The chat strip shows the server's and the channels' tabs; a private chat
//! is the current tab only while the messages page shows it (messages.rs).
//!
//! The engine keeps the history: [`Event::ChatHistory`] is an upsert of
//! messages by their local id (see `voelin_core::history`), so a tab holds
@@ -7,21 +9,66 @@
//! the selected tab are rebuilt from them with [`vm::list::sync`], which
//! touches only the rows that changed. Sessions the engine keeps no history
//! for (it does not know the server yet) fall back to [`Event::Chat`].
//!
//! Messages are read while their tab is on screen in the focused window
//! ([`App::track_reading`]). A tab remembers the newest message read
//! (`Tab::read`, kept in the store's `chat_reads`), counts what came after
//! it, and when it comes on screen shows a "New" divider above the first
//! of those until it is left.
use std::collections::HashMap;
use std::path::PathBuf;
use slint::{ComponentHandle, ModelRc};
use voelin_core::gateway::Pin;
use voelin_core::settings::CACHE_FETCH_IMAGES;
use voelin_core::{
Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
TransferState,
};
use voelin_gateway_proto::{ErrorCode, TopicInfo, feature};
use voelin_model::{ChatMessage, ChatTarget};
use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails};
use voelin_store::ChatRead;
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, PinItem, SessionView, Tab};
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, Nav, PinItem, SessionView, Tab};
use crate::settings::UI_IMAGE_PREVIEW_KB;
use crate::vm;
use crate::vm::chat::{LineCtx, Previous};
use crate::vm::bbcode::LinkKind;
use crate::vm::chat::{LineCache, LineCtx, Previous};
/// Where the server's welcome and host message keep what their lines were
/// built from (`LineCache`), apart from the messages' ids.
const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1];
/// What the server says to everyone who connects, with where its line keeps
/// its parts: its welcome message, and its host message when that goes to
/// the chat log.
pub(crate) fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> {
let host = details.host_message_mode == HostMessageMode::Log;
[Some(&details.welcome_message), host.then_some(&details.host_message)]
.into_iter()
.zip(SERVER_LINES)
.filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id)))
.collect()
}
/// The text of the server's line `key` (-1, -2, …) of a server chat
/// ([`App::lines_of`]), if `tab` is one.
pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Option<&'a str> {
if tab.target != ChatTarget::Server || key >= 0 {
return None;
}
server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text)
}
/// The store's name of a chat.
pub(crate) fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
match target {
ChatTarget::Server => voelin_store::ChatTarget::Server,
ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid),
ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()),
}
}
/// A file being downloaded from a chat message.
pub(crate) struct Download {
@@ -58,48 +105,54 @@ fn ago(ts_ms: i64) -> String {
impl App {
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
let Some(id) = self.current else { return };
let title = match &target {
ChatTarget::Channel(cid) => {
let name = self
.sessions
.get(&id)
.and_then(|v| v.presence.channels.get(cid))
.map(|c| vm::tree::channel_title(c).0.to_owned());
format!("#{}", name.unwrap_or_else(|| cid.to_string()))
}
ChatTarget::Server => "Server".into(),
ChatTarget::Private(uid) => format!("@{}", self.peer_name(uid, None)),
};
let view = self.sessions.entry(id).or_default();
let index = match view.tabs.iter().position(|t| t.target == target) {
Some(i) => i,
None => {
view.tabs.push(Tab::new(target.clone(), title));
if !self.demo_ui {
self.engine.send(Command::OpenChat { session: id as u64, target });
}
view.tabs.len() - 1
}
};
let index = self.chat_tab(id, target);
if focus {
view.current_tab = index;
view.tabs[index].unread = 0;
self.sessions.entry(id).or_default().focus_tab(index);
self.prefetch_counts();
self.track_reading();
}
self.refresh_chat();
self.refresh_servers();
}
/// The index of `target`'s tab in session `id`, opened if new (the
/// engine then sends its history).
pub(crate) fn chat_tab(&mut self, id: i64, target: ChatTarget) -> usize {
let peer = match &target {
ChatTarget::Private(uid) => self.peer_name(uid, None),
_ => String::new(),
};
let view = self.sessions.entry(id).or_default();
if let Some(i) = view.tabs.iter().position(|t| t.target == target) {
return i;
}
let title = vm::chat::tab_title(&view.presence, &target, &peer);
let tab = view.new_tab(target.clone(), title);
view.tabs.push(tab);
if !self.demo_ui {
self.engine.send(Command::OpenChat { session: id as u64, target });
}
view.tabs.len() - 1
}
/// The session's tab that tab `index` of the chat strip is
/// (`Bridge.tabs`, [`vm::chat::strip`]).
pub(crate) fn strip_tab(&self, index: i32) -> Option<usize> {
self.models.strip.borrow().get(usize::try_from(index).ok()?).copied()
}
pub(crate) fn select_tab(&mut self, index: usize) {
if let Some(view) = self.view_mut()
&& index < view.tabs.len()
{
view.current_tab = index;
view.tabs[index].unread = 0;
view.set_current_tab(index);
view.tabs[index].topic = None;
}
if let Some(id) = self.current {
self.fetch_previews(id);
}
self.prefetch_counts();
self.track_reading();
self.refresh_chat();
self.refresh_servers();
}
@@ -110,10 +163,13 @@ impl App {
if index == 0 || index >= view.tabs.len() {
return;
}
let tab = view.tabs.remove(index);
view.current_tab = view.current_tab.min(view.tabs.len() - 1);
self.save_read(id, index);
let tab = self.sessions.entry(id).or_default().remove_tab(index);
self.engine.send(Command::CloseChat { session: id as u64, target: tab.target });
self.prefetch_counts();
self.track_reading();
self.refresh_chat();
self.refresh_servers();
}
pub(crate) fn send_message(&mut self, text: String) {
@@ -132,46 +188,35 @@ impl App {
match view.tabs.iter().position(|t| t.target == *target) {
Some(i) => i,
None => {
view.tabs.push(Tab::new(target.clone(), title()));
let tab = view.new_tab(target.clone(), title());
view.tabs.push(tab);
view.tabs.len() - 1
}
}
}
fn tab_title(view: &SessionView, target: &ChatTarget, author: &str) -> String {
match target {
ChatTarget::Channel(cid) => format!(
"#{}",
view.presence
.channels
.get(cid)
.map(|c| c.name.clone())
.unwrap_or_else(|| cid.to_string())
),
ChatTarget::Private(_) => format!("@{author}"),
ChatTarget::Server => "Server".into(),
}
}
/// A live message of a session without stored history: appended as it
/// comes, without an id.
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
let current = self.current == Some(id);
let reading = self.reads_now(id);
let new = !self.is_own(id, &message);
let view = self.sessions.entry(id).or_default();
let title = Self::tab_title(view, &message.target, &message.author_name);
let title = vm::chat::tab_title(&view.presence, &message.target, &message.author_name);
let index = Self::tab_for(view, &message.target, || title);
let shown = current && view.current_tab == index;
let seen = reading && view.current_tab == index;
let tab = &mut view.tabs[index];
let line = vm::chat::line(&message, tab.last.as_ref());
tab.last = Some(Previous::of(&message));
tab.lines.push(line);
if !shown {
let counted = new && !seen;
if counted {
tab.unread += 1;
}
if current {
self.refresh_chat();
}
if !shown {
if counted {
self.refresh_servers();
}
self.studio_chat_changed(id, &message.target);
@@ -187,6 +232,7 @@ impl App {
complete: bool,
) {
let current = self.current == Some(id);
let reading = self.reads_now(id);
// A private chat is named after the peer, whoever wrote first.
let peer = match target {
ChatTarget::Private(uid) => Some(format!(
@@ -200,9 +246,10 @@ impl App {
};
let view = self.sessions.entry(id).or_default();
let author = messages.first().map_or("", |m| m.message.author_name.as_str());
let title = peer.unwrap_or_else(|| Self::tab_title(view, target, author));
let title = peer.unwrap_or_else(|| vm::chat::tab_title(&view.presence, target, author));
let index = Self::tab_for(view, target, || title);
let shown = current && view.current_tab == index;
let seen = reading && view.current_tab == index;
let own_client = view.state.own_client;
let tab = &mut view.tabs[index];
if source == HistorySource::Gateway {
tab.synced = true;
@@ -211,28 +258,49 @@ impl App {
tab.loading = false;
tab.complete = tab.complete || complete;
}
let mut fresh = 0;
// Without a marker, what the tab holds was read.
if tab.read.is_none() {
tab.read = tab.newest();
}
for message in messages {
match tab.messages.iter().position(|m| m.message.id == message.id) {
Some(i) => tab.messages[i].message = message,
None => {
let key = tab.take_key();
if source == HistorySource::Live {
fresh += 1;
}
tab.messages.push(Msg { key, message });
}
}
}
tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id));
if !shown {
tab.unread += fresh;
// ...and so is a first stored page; a first live message is new.
if tab.read.is_none() {
tab.read = match source {
HistorySource::Live => tab
.messages
.first()
.map(|m| (m.message.message.ts_ms, m.message.id.saturating_sub(1))),
_ => tab.newest(),
};
}
let unread = tab.unread;
let own =
|m: &ChatMessage| crate::social::own_message(&self.social.own_uids, own_client, m);
if seen && source == HistorySource::Live {
tab.catch_up();
} else {
tab.count_unread(own);
// What came while away (a stored or gateway page) gets the
// divider also when its chat is on screen already.
if seen {
tab.enter(own);
}
}
let counted = tab.unread != unread;
if current {
self.fetch_previews(id);
self.refresh_chat();
}
if fresh > 0 && !shown {
if counted {
self.refresh_servers();
}
self.studio_chat_changed(id, target);
@@ -248,22 +316,31 @@ impl App {
}
tab.loading = true;
let target = tab.target.clone();
let before = tab.messages.first().map(|m| m.message.id);
self.engine.send(Command::LoadOlderHistory { session: id as u64, target, before });
let oldest = tab.messages.first().map(|m| &m.message);
if self.demo_ui {
// No engine answers in demo mode.
crate::dev::answer_older(id, target, oldest.cloned());
} else {
let before = oldest.map(|m| m.id);
self.engine.send(Command::LoadOlderHistory { session: id as u64, target, before });
}
self.refresh_chat();
}
/// The lines of a tab, grouped and with everything the row shows (also
/// the stream chat of the Stream Studio, studio.rs).
pub(crate) fn lines_of(
&self,
view: &SessionView,
tab: &Tab,
messages: &[Msg],
) -> Vec<ChatLine> {
/// The lines of a tab's messages (`main`) or of its open topic, grouped
/// and with everything the row shows (also the stream chat of the
/// Stream Studio, studio.rs). The server chat starts with what the
/// server says to everyone who connects ([`Self::server_lines`]).
pub(crate) fn lines_of(&self, view: &SessionView, tab: &Tab, main: bool) -> Vec<ChatLine> {
let messages = if main { &tab.messages } else { &tab.topic_messages };
let gateway = view.gateway_has(feature::PINS)
|| view.gateway_has(feature::REACTIONS)
|| view.gateway_has(feature::TOPICS);
// Pictures on the web show only while pictures are fetched and
// shown.
let shown = self.prefs.get(&CACHE_FETCH_IMAGES) && self.prefs.get(&UI_IMAGE_PREVIEW_KB) > 0;
let pictures = shown.then_some(&view.pictures);
let cache = main.then_some(&tab.cache);
let mut previous: Option<Previous> = None;
let mut lines: Vec<(i64, ChatLine)> = Vec::with_capacity(messages.len());
for m in messages {
@@ -292,6 +369,9 @@ impl App {
topic,
downloads: self.downloads_of(view, m.key),
previews,
pictures,
cache,
unread_start: main && tab.divider == Some(m.message.id),
};
lines.push((
m.message.message.ts_ms,
@@ -299,12 +379,43 @@ impl App {
));
previous = Some(Previous::of(&m.message.message));
}
if let Some(cache) = cache {
let ids = messages.iter().map(|m| m.message.id).chain(SERVER_LINES);
cache.keep(ids, messages.len());
}
// Pokes of a private chat's peer show among its messages.
if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.current) {
lines.extend(self.poke_lines(session, uid));
lines.sort_by_key(|(ts, _)| *ts);
}
lines.into_iter().map(|(_, line)| line).collect()
let server = if main && tab.target == ChatTarget::Server {
Self::server_lines(view, pictures, cache)
} else {
Vec::new()
};
server.into_iter().chain(lines.into_iter().map(|(_, line)| line)).collect()
}
/// What the server says to everyone who connects ([`server_texts`]) as
/// the first lines of the server chat: by the server, without reactions
/// or pins.
fn server_lines(
view: &SessionView,
pictures: Option<&HashMap<String, PathBuf>>,
cache: Option<&LineCache>,
) -> Vec<ChatLine> {
let name = match view.presence.server_name.as_str() {
"" => "Server",
name => name,
};
server_texts(&view.presence.server)
.into_iter()
.enumerate()
.map(|(i, (text, id))| {
let ctx = LineCtx { key: -1 - i as i32, pictures, cache, ..Default::default() };
vm::chat::server_line(name, text, id, i > 0, &ctx)
})
.collect()
}
/// The file cards of a message that has downloads running.
@@ -359,15 +470,22 @@ impl App {
&self.models.tabs,
&[ChatTab { title: "Server".into(), ..Default::default() }],
);
*self.models.strip.borrow_mut() = vec![0];
bridge.set_current_tab(0);
bridge.set_current_chat(0);
let empty = ModelRc::from(self.models.no_chat.clone());
if bridge.get_messages() != empty {
bridge.set_messages(empty);
}
bridge.set_unread_index(-1);
return;
};
let tabs: Vec<ChatTab> = view
.tabs
// Private chats are on the messages page, not in the strip.
let (strip, current) =
vm::chat::strip(view.tabs.iter().map(|t| &t.target), view.current_tab);
let tabs: Vec<ChatTab> = strip
.iter()
.map(|&i| &view.tabs[i])
.map(|t| {
let (last, time) = t
.messages
@@ -385,7 +503,7 @@ impl App {
last: last.into(),
time: time.into(),
title: t.title.clone().into(),
name: t.title.trim_start_matches(['#', '@']).into(),
name: vm::chat::tab_name(&t.title, &t.target).into(),
kind: match t.target {
ChatTarget::Server => 0,
ChatTarget::Channel(_) => 1,
@@ -406,19 +524,38 @@ impl App {
})
.collect();
vm::list::sync(&self.models.tabs, &tabs);
let current = view.current_tab as i32;
*self.models.strip.borrow_mut() = strip;
if bridge.get_current_tab() != current {
bridge.set_current_tab(current);
}
bridge.set_current_chat(view.current_tab as i32);
let tab = &view.tabs[view.current_tab];
// Sessions without stored history push their lines themselves.
let mut divider = None;
if view.has_history() {
vm::list::sync(&tab.lines, &self.lines_of(view, tab, &tab.messages));
let lines = self.lines_of(view, tab, true);
divider = lines.iter().position(|l| l.unread_start);
vm::list::sync(&tab.lines, &lines);
}
let lines = ModelRc::from(tab.lines.clone());
if bridge.get_messages() != lines {
bridge.set_messages(lines);
}
// The "New" divider: how many came from there on, and when.
let new = tab
.divider
.and_then(|d| tab.messages.iter().position(|m| m.message.id == d))
.map_or(&[][..], |i| &tab.messages[i..]);
let session = self.current.unwrap_or_default();
let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count();
bridge.set_unread_index(divider.map_or(-1, |i| i as i32));
bridge.set_unread_count(count as i32);
bridge.set_unread_since(
new.first()
.map(|m| vm::chat::since_time(m.message.message.ts_ms))
.unwrap_or_default()
.into(),
);
bridge.set_more_history(view.has_history() && !tab.complete);
bridge.set_loading_history(tab.loading);
bridge.set_local_history(
@@ -429,6 +566,8 @@ impl App {
bridge.set_has_topics(view.gateway_has(feature::TOPICS));
bridge.set_pins_loading(!tab.pins_loaded && view.gateway_has(feature::PINS));
bridge.set_topics_loading(!tab.topics_loaded && view.gateway_has(feature::TOPICS));
bridge.set_pins_count(vm::chat::known_count(tab.pins_loaded, tab.pins.len()));
bridge.set_topics_count(vm::chat::known_count(tab.topics_loaded, tab.topics.len()));
let pins: Vec<PinItem> = tab
.pins
.iter()
@@ -479,7 +618,174 @@ impl App {
.unwrap_or_default()
.into(),
);
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, &tab.topic_messages));
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, false));
}
/// A link in a message was clicked (`masked`: its text shows something
/// else, [`vm::bbcode::is_masked`]). A page on the web opens in the
/// browser, a masked one once the user saw where it goes (Nav.link-open);
/// a TeamSpeak link in Voelin ([`App::open_link`]).
pub(crate) fn open_link_text(&mut self, link: &str, masked: bool) {
match vm::bbcode::classify_link(link) {
LinkKind::Web(url) if masked => {
if let Some(ui) = self.ui.upgrade() {
let nav = ui.global::<Nav>();
nav.set_link_host(vm::bbcode::link_host(&url).into());
nav.set_link_url(url.into());
nav.set_link_open(true);
}
}
LinkKind::Web(url) => {
if let Err(e) = self.open_url(&url) {
self.set_status(format!("Cannot open the link: {e}"));
}
}
LinkKind::Server(url) => self.open_link(&url),
// A file opens from its card.
LinkKind::File | LinkKind::Refused => {}
}
}
// What is read.
/// The current chat's messages are on screen (`Nav.chat-shown`).
fn chat_shown(&self) -> bool {
self.ui.upgrade().is_some_and(|ui| ui.global::<Nav>().get_chat_shown())
}
/// New messages of session `id` in its current tab are read as they
/// come: they are on screen in the focused window.
fn reads_now(&self, id: i64) -> bool {
self.focused && self.current == Some(id) && self.chat_shown()
}
/// After anything that can change which chat is on screen (a tab, a
/// server, the page, the window's focus): the chat left is stored and
/// loses its divider; the one on screen, in the focused window, is read
/// (its divider above what was new). `true` if a tab changed.
pub(crate) fn track_reading(&mut self) -> bool {
let open = self.current.filter(|_| self.chat_shown()).and_then(|id| {
let view = self.sessions.get(&id)?;
Some((id, view.tabs.get(view.current_tab)?.target.clone()))
});
let mut changed = false;
if open != self.reading {
if let Some((id, target)) = self.reading.take()
&& let Some(index) = self.tab_index(id, &target)
{
let tab = &mut self.sessions.entry(id).or_default().tabs[index];
changed |= tab.divider.take().is_some();
self.save_read(id, index);
}
self.reading = open.clone();
}
if let (true, Some((id, target))) = (self.focused, open)
&& let Some(index) = self.tab_index(id, &target)
{
let own_uids = &self.social.own_uids;
let view = self.sessions.entry(id).or_default();
let own_client = view.state.own_client;
let tab = &mut view.tabs[index];
let before = (tab.unread, tab.divider);
tab.enter(|m| crate::social::own_message(own_uids, own_client, m));
changed |= (tab.unread, tab.divider) != before;
}
changed
}
/// Where the tab of `target` is in session `id`.
fn tab_index(&self, id: i64, target: &ChatTarget) -> Option<usize> {
self.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target)
}
/// The current chat came on screen or left it (`Nav.chat-shown`).
pub(crate) fn chat_shown_changed(&mut self) {
if self.track_reading() {
self.refresh_chat();
self.refresh_servers();
}
}
/// The window gained or lost the focus (winit's events: the desktop
/// only).
#[cfg(not(target_os = "android"))]
pub(crate) fn window_focused(&mut self, focused: bool) {
self.focused = focused;
if self.track_reading() {
self.refresh_chat();
self.refresh_servers();
}
}
/// The current chat is read (the bar over its messages): the divider
/// goes.
pub(crate) fn mark_read(&mut self) {
let Some(id) = self.current else { return };
let Some(view) = self.sessions.get_mut(&id) else { return };
let index = view.current_tab;
let tab = &mut view.tabs[index];
tab.divider = None;
tab.catch_up();
self.save_read(id, index);
self.refresh_chat();
self.refresh_servers();
}
/// Store where tab `index` of session `id` was read, if that moved (not
/// for the sample data of VOELIN_DEMO_UI).
pub(crate) fn save_read(&mut self, id: i64, index: usize) {
if self.demo_ui {
return;
}
let Some(view) = self.sessions.get_mut(&id) else { return };
let Some(server_uid) = view.state.server_uid.as_deref() else { return };
let Some(tab) = view.tabs.get_mut(index) else { return };
let Some((ts_ms, message)) = tab.read.filter(|r| tab.stored_read != Some(*r)) else {
return;
};
let read =
ChatRead { ts_ms, id: message, updated_ms: chrono::Utc::now().timestamp_millis() };
let target = store_target(&tab.target);
match self.store.set_chat_read(server_uid, &target, &read) {
Ok(()) => {
tab.stored_read = tab.read;
// A tab closed and opened again starts from here.
view.reads.insert(target.key(), (ts_ms, message));
}
Err(e) => tracing::warn!(%e, "could not keep where a chat was read"),
}
}
/// Store where every chat of session `id` was read (it ended, or the
/// app exits).
pub(crate) fn save_reads(&mut self, id: i64) {
let count = self.sessions.get(&id).map_or(0, |v| v.tabs.len());
for index in 0..count {
self.save_read(id, index);
}
}
/// Where the chats of session `id` were read, from the store, once its
/// server is known (or another one: the gateway's id wins): its tabs
/// start from there, now and when they open.
pub(crate) fn load_reads(&mut self, id: i64) {
let Some(view) = self.sessions.get_mut(&id) else { return };
if self.demo_ui || view.state.server_uid.is_none() || view.reads_of == view.state.server_uid
{
return;
}
view.reads_of = view.state.server_uid.clone();
let server_uid = view.reads_of.as_deref().unwrap_or_default();
view.reads = match self.store.chat_reads(server_uid) {
Ok(reads) => reads.into_iter().map(|(t, r)| (t.key(), (r.ts_ms, r.id))).collect(),
Err(e) => {
tracing::warn!(%e, "could not read where the chats were read");
HashMap::new()
}
};
for tab in &mut view.tabs {
tab.read_from(&view.reads);
}
}
// Gateway features of a chat.
@@ -494,7 +800,12 @@ impl App {
let view = self.sessions.entry(id).or_default();
match update {
GatewayUpdate::Connected { capabilities, .. }
| GatewayUpdate::Capabilities { capabilities } => view.gateway_caps = capabilities,
| GatewayUpdate::Capabilities { capabilities } => {
view.gateway_caps = capabilities;
if current {
self.prefetch_counts();
}
}
GatewayUpdate::Disconnected { .. } => {
view.gateway_caps.clear();
for tab in &mut view.tabs {
@@ -502,9 +813,11 @@ impl App {
tab.topics_loaded = false;
}
}
// Answers to our requests: a chat closed while they were on
// their way (prefetch_counts asks on every change of chat) stays
// closed.
GatewayUpdate::Pins { target, pins } => {
let index = Self::tab_for(view, &target, || "Server".into());
let tab = &mut view.tabs[index];
let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return };
tab.pins_loaded = true;
tab.pins = pins.into_iter().map(|p| pin_row(tab.take_key(), p)).collect();
tab.pins.sort_by_key(|p| -p.ts_ms);
@@ -521,9 +834,9 @@ impl App {
view.tabs[index].pins.retain(|p| p.message.remote_id != Some(message_id));
}
GatewayUpdate::Topics { target, topics } => {
let index = Self::tab_for(view, &target, || "Server".into());
view.tabs[index].topics = topics;
view.tabs[index].topics_loaded = true;
let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return };
tab.topics = topics;
tab.topics_loaded = true;
}
GatewayUpdate::Topic { topic } => {
let index = Self::tab_for(view, &topic.target.clone(), || "Server".into());
@@ -613,6 +926,20 @@ impl App {
});
}
/// Ask the gateway for the current chat's pins and topics until it sent
/// them, so the header counts them before their drawers are opened.
pub(crate) fn prefetch_counts(&self) {
let Some(view) = self.view() else { return };
let Some(tab) = view.tabs.get(view.current_tab) else { return };
if !tab.pins_loaded && view.gateway_has(feature::PINS) {
self.gateway(GatewayRequest::Pins { target: tab.target.clone() });
}
if !tab.topics_loaded && view.gateway_has(feature::TOPICS) {
let target = tab.target.clone();
self.gateway(GatewayRequest::Topics { target, include_archived: false });
}
}
/// Open the pins of the current chat (loading them once).
pub(crate) fn open_pins(&mut self) {
let Some(view) = self.view() else { return };
@@ -633,8 +960,14 @@ impl App {
if tab.topic.take().is_some() {
tab.topic_messages.clear();
}
// Older than what is loaded: only highlighted once it is.
// Older than what is loaded: only highlighted once it is. The server
// chat's first lines are the server's.
let row = tab.marked.and_then(|id| tab.messages.iter().position(|m| m.message.id == id));
let first = match tab.target {
ChatTarget::Server => server_texts(&view.presence.server).len(),
_ => 0,
};
let row = row.map(|row| row + first);
self.refresh_chat();
if let (Some(row), Some(ui)) = (row, self.ui.upgrade()) {
let bridge = ui.global::<Bridge>();
+432 -39
View File
@@ -7,36 +7,57 @@
//! `VOELIN_SCREENSHOT_DELAY` seconds (default 4) and exit.
//! - `VOELIN_WINDOW_SIZE=<w>x<h>`: the window's size (e.g. `390x844` for the
//! phone layout).
//! - `VOELIN_DEMO_UI=1`: sample servers, channels, chat and streams, no
//! server needed (nothing is stored).
//! - `VOELIN_DEMO_UI=1`: sample servers, channels, chat (two pages of older
//! messages answer scrolling up) and streams, no server needed (nothing is
//! stored).
//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer.
//! - `VOELIN_OPEN=<what>[,<what>...]`: open screens on start: `home`,
//! `server`, `settings[:<section>]` (voice, keybinds, streaming, privacy,
//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server;
//! `server` (`server:chat`: its server chat), `settings[:<section>]`
//! (voice, keybinds, streaming, privacy, appearance, or 0-4), `about`,
//! `share`, `bookmark` (add a server, also `join`;
//! `bookmark:edit` the current one, Advanced open),
//! `emoji` (the picker), `client` (the volume dialog of the first other
//! client once connected), `panel` / `no-panel` (the members panel),
//! `voice` (the voice channel view; on the phone its own screen),
//! `voice` (the voice channel view; on the phone its own screen;
//! `voice:compact` with the smaller stage, not stored),
//! `more` (after `voice` on the phone: the voice screen's More menu,
//! opened once the screen is laid out),
//! `members` (the phone's members page), `notification` (a tapped voice
//! notification), `shared:<text>` (text shared to the app on Android),
//! `pins`, `topics` (the drawers),
//! `topic:<id>` (a topic's messages), `member` (the member card of the
//! first other client), `watch` (the first stream; with sample data the
//! local test pattern in its place), `popout` (the same, popped out),
//! first other client), `poke` (the poke dialog: for the contact shown
//! after `friends`, else for the first other client, its card open),
//! `channel-password` (the password dialog of the first locked channel,
//! the sample's Officers; `channel-password:wrong` as after a refused
//! one), `actions` (the last message's actions, as if hovered),
//! `first-run` (home's banner as before the first server, over the
//! sample data),
//! `unread` (the current chat read up to five messages before its end:
//! the "New" divider, scrolled up to; `unread:end` ten messages before,
//! at the list's end, under the bar that counts the new messages),
//! `link-confirm[:<url>]` (the question before a masked link opens, by
//! default the sample's raid board), `link:<url>` (a TeamSpeak link
//! opened: the server dialog filled in from it, or in voice on its
//! server a move into its channel), `watch` (the first stream; with
//! sample data the local test pattern in its place), `theatre` (after
//! `watch`: in theatre mode), `popout` (`watch` in a window of its own),
//! `tab:<home|servers|chat|activity|you>` (phone layout); `friends[:<uid>]`,
//! `messages[:<uid>]` (a private chat), `inbox` (offline messages),
//! `library`, `events`, `event-form`, `search[:<text>]`,
//! `notifications` (the bell), `join` (join by address), `offline` (an
//! offline message), `picture` (a chat picture opened large), `camera`
//! (the settings' camera preview); settings sections also `account`,
//! `notifications` (the bell), `offline` (an offline message), `picture`
//! (a chat picture opened large), `camera` (the settings' camera
//! preview); settings sections also `account`,
//! `profiles` (also `identities`), `devices`, `notifications`,
//! `integrations`, `advanced` (5-10);
//! `studio[:<what>]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo
//! studio from synthetic sources), `studio:window` in a window of its own,
//! `studio:live` going live, `studio:record`, or a dialog: `studio:source`,
//! `studio:live` going live (also with a screen opened after it:
//! `studio:live,server,voice` shows our stream's card with the studio's
//! picture), `studio:record`, or a dialog: `studio:source`,
//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`.
//! A screenshot also saves the studio's window (`<name>-window.png`) and
//! draws it over the main window.
//! A screenshot also saves the studio's window, or the stream's
//! (`<name>-window.png`), and draws it over the main window.
//! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up.
//! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting
//! everyone) once connected to a TeamSpeak 6 server.
@@ -49,8 +70,8 @@ use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use voelin_core::gateway::Pin;
use voelin_core::stream::{StreamInfo, StreamKind};
use voelin_core::{
Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, OfflineMessageInfo,
Relation, SessionState, Source, VoiceState,
Contact, Event, GatewayUpdate, HistoryMessage, HistorySource, JoinFailure, ObserveState,
OfflineMessageInfo, Relation, SessionState, Source, VoiceState,
};
use voelin_gateway_proto::{
Action, Attendee, ConfigEntry, ConfigSource, EventInfo, EventKind, EventSpec, PermRule,
@@ -63,8 +84,10 @@ 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;
/// The switches read at start.
#[derive(Clone, Debug, Default)]
@@ -145,6 +168,8 @@ fn mobile_tab(name: &str) -> MobileTab {
pub(crate) struct Running {
_screenshot: Option<slint::Timer>,
_resize: Option<slint::Timer>,
_scroll: Option<slint::Timer>,
_more: Option<slint::Timer>,
}
/// Apply the switches once the app is set up.
@@ -194,6 +219,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);
@@ -210,7 +246,13 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
bridge.set_myts(account);
}
"home" => nav.invoke_show(Page::Home),
"server" => nav.invoke_show(Page::Server),
"server" => {
nav.invoke_show(Page::Server);
// The server chat, which starts with the welcome message.
if arg == "chat" {
with_app(|app| app.select_tab(0));
}
}
"settings" => nav.invoke_open_settings(section(arg)),
"about" => nav.invoke_open_about(),
"share" => {
@@ -226,13 +268,22 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
nav.invoke_edit_server(id as i32);
}
}
"bookmark" => nav.invoke_add_server(),
// `join`: the same dialog (Join a server was one of its own).
"bookmark" | "join" => nav.invoke_add_server(),
"emoji" => nav.set_emoji_open(true),
"panel" => nav.set_right_panel_open(true),
"no-panel" => nav.set_right_panel_open(false),
"tab" => nav.set_mobile_tab(mobile_tab(arg)),
"voice" => nav.invoke_show_voice(true),
"voice" => {
nav.invoke_show_voice(true);
// The smaller stage, for this run only.
if arg == "compact" {
nav.set_voice_compact(true);
}
}
"pins" => nav.invoke_show_pins(true),
// Opened once laid out (below).
"more" => {}
// The phone's members page.
"members" => nav.set_members_open(true),
// What Android hands over: a tapped voice notification, text
@@ -255,12 +306,50 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
"member" => {
with_app(|app| app.open_first_member());
}
// After `friends` the contact path (Kairo without a contact
// chosen), else the member card's.
"poke" => {
let friends = nav.get_page() == Page::Friends;
with_app(|app| {
if friends {
let uid = app.social.selected.clone().unwrap_or_else(|| "demo-3".into());
app.contact_action(&uid, "poke");
} else {
app.open_first_member();
app.member_action("poke");
}
});
}
"channel-password" => {
with_app(|app| open_channel_password(app, arg == "wrong"));
}
// A screenshot cannot hover.
"actions" => nav.set_show_actions(true),
// Home as before the first server, over the sample data.
"first-run" => nav.set_first_run(true),
// `end`: further back, so the divider is above the view.
"unread" => {
with_app(|app| open_unread(app, if arg == "end" { 10 } else { 5 }));
}
"link-confirm" => {
let url = if arg.is_empty() { DEMO_RAID_BOARD } else { arg };
with_app(|app| app.open_link_text(url, true));
}
// As a link from the platform comes.
"link" => crate::inbox::request(crate::inbox::Request::OpenLink(arg.to_owned())),
"watch" | "popout" => {
with_app(|app| {
if switches.demo_ui { app.demo_watch() } else { app.watch_first_stream() }
if switches.demo_ui {
app.demo_watch();
} else {
app.watch_first_stream();
}
if what == "popout" {
app.viewer_pop_out();
}
});
ui.global::<Bridge>().set_viewer_popped(what == "popout");
}
"theatre" => nav.set_theatre(true),
// Home, friends, messages, events, the bell, the search.
"friends" => {
with_app(|app| app.select_contact(arg.to_owned()));
@@ -281,7 +370,6 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
"event-form" => nav.invoke_create_event(),
"search" => nav.invoke_open_search(arg.into()),
"notifications" => nav.set_notifications_open(true),
"join" => nav.invoke_join_server(),
"offline" => nav.invoke_write_offline("demo-ari".into(), "Ari".into()),
"picture" => {
let picture = demo_picture(1280, 720, 16);
@@ -324,6 +412,22 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
);
timer
});
// `unread`: up to the divider once the list is laid out (after the
// resize above).
let scroll = switches.open.iter().any(|o| o == "unread").then(|| {
late(ui, switches, |ui| {
let bridge = ui.global::<Bridge>();
bridge.set_jump_index(bridge.get_unread_index());
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
})
});
// `more`: the phone voice screen's More menu (a screenshot cannot tap).
let more = switches.open.iter().any(|o| o == "more").then(|| {
late(ui, switches, |ui| {
let nav = ui.global::<Nav>();
nav.set_more_requests(nav.get_more_requests().wrapping_add(1));
})
});
let screenshot = switches.screenshot.clone().map(|path| {
let weak = ui.as_weak();
let timer = slint::Timer::default();
@@ -336,22 +440,65 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
eprintln!("screenshot failed: {e}");
}
let _ = ui.hide();
// Also when the studio's own window is open.
// Also when the studio's or the stream's own window is
// open.
let _ = slint::quit_event_loop();
}
},
);
timer
});
Running { _screenshot: screenshot, _resize: resize }
Running { _screenshot: screenshot, _resize: resize, _scroll: scroll, _more: more }
}
/// A timer that runs `action` at three quarters of the screenshot delay, once
/// the window has its size and the screens are laid out.
fn late(
ui: &MainWindow,
switches: &Switches,
action: impl Fn(&MainWindow) + 'static,
) -> slint::Timer {
let weak = ui.as_weak();
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::SingleShot,
Duration::from_millis(switches.screenshot_delay * 1000 * 3 / 4),
move || {
if let Some(ui) = weak.upgrade() {
action(&ui);
}
},
);
timer
}
/// The current chat's read marker `back` messages before its end, as if
/// they came while away, its "New" divider shown (`VOELIN_OPEN=unread`).
fn open_unread(app: &mut App, back: usize) {
let Some(id) = app.current else { return };
let own_uids = app.social.own_uids.clone();
let Some(view) = app.sessions.get_mut(&id) else { return };
let own_client = view.state.own_client;
let own = |m: &ChatMessage| crate::social::own_message(&own_uids, own_client, m);
let index = view.current_tab;
let tab = &mut view.tabs[index];
let Some(at) = tab.messages.len().checked_sub(back + 1) else { return };
let read = &tab.messages[at].message;
tab.read = Some((read.message.ts_ms, read.id));
tab.divider = None;
tab.count_unread(own);
tab.enter(own);
app.refresh_chat();
app.refresh_servers();
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
let mut image = ui.window().take_snapshot()?;
if let Some(studio) = with_app(|app| app.studio_snapshot()).flatten() {
let window = with_app(|app| app.studio_snapshot().or_else(|| app.viewer_snapshot())).flatten();
if let Some(window) = window {
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
save_png(&studio, &path.with_file_name(format!("{stem}-window.png")))?;
paste(&mut image, &studio);
save_png(&window, &path.with_file_name(format!("{stem}-window.png")))?;
paste(&mut image, &window);
}
save_png(&image, path)
}
@@ -382,6 +529,25 @@ fn save_png(image: &SharedPixelBuffer<Rgba8Pixel>, path: &std::path::Path) -> Re
Ok(())
}
/// `VOELIN_OPEN=channel-password`: join the current server's first locked
/// channel, which asks for its password; `wrong` as if the server had
/// refused one.
fn open_channel_password(app: &mut App, wrong: bool) {
let Some(session) = app.current else { return };
let locked = app
.view()
.and_then(|v| v.presence.channels.values().filter(|c| c.has_password).map(|c| c.id).min());
let Some(channel) = locked else { return };
if wrong {
if let Some(view) = app.view_mut() {
view.channel_passwords.insert(channel, "guess".into());
}
app.join_failed(session, channel, JoinFailure::Password);
} else {
app.join_channel(session, channel);
}
}
const DEMO: i64 = 9001;
fn channel(id: u64, parent: u64, order: u64, name: &str) -> ChannelInfo {
@@ -408,6 +574,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,
@@ -420,6 +587,13 @@ fn demo_ui(app: &mut App) {
bookmark(DEMO + 1, "Pixel Lounge", "pixel.example"),
bookmark(DEMO + 2, "Dev TS3", "127.0.0.1:9987"),
];
// Home's "Continue where you left off": a channel of a server without
// voice, so it shows Join.
app.settings.last_voice = Some(LastVoice {
bookmark: DEMO + 1,
address: "pixel.example".into(),
channel: vec!["Art Corner".into()],
});
app.current = Some(DEMO);
let session = DEMO as u64;
@@ -440,20 +614,26 @@ fn demo_ui(app: &mut App) {
let mut raid = channel(4, 3, 0, "Raid Night");
raid.banner_gfx_url = Some(DEMO_RAID_BANNER.into());
raid.banner_mode = BannerMode::KeepAspect;
// Only the raid leads speak there: Zeph cannot (the members panel's hand).
raid.needed_talk_power = 50;
let mut music = channel(5, 0, 3, "Music");
music.icon = DEMO_MUSIC_ICON;
music.banner_gfx_url = Some(DEMO_MUSIC_BANNER.into());
music.banner_mode = BannerMode::NoAdjust;
let mut locked = channel(7, 0, 6, "Officers");
let mut locked = channel(7, 0, 9, "Officers");
locked.has_password = true;
// Spacers as servers name them: a centred heading, one on the right and
// a line.
for c in [
channel(1, 0, 0, "Lobby"),
chill,
channel(3, 0, 2, "[cspacer0]Gaming"),
raid,
music,
channel(6, 0, 5, "AFK"),
channel(9, 0, 5, "[rspacer2]Staff"),
locked,
channel(8, 0, 7, "[*spacer1]---"),
channel(6, 0, 8, "AFK"),
] {
p.channels.insert(c.id, c);
}
@@ -492,6 +672,9 @@ fn demo_ui(app: &mut App) {
clients[5].server_groups = vec![GROUP_MEMBER];
clients[6].server_groups = vec![GROUP_GUEST];
clients[7].server_groups = vec![GROUP_GUEST];
// myTeamSpeak badges; their pictures arrive below.
clients[0].badges = DEMO_BADGES[..2].iter().map(|g| g.to_string()).collect();
clients[1].badges = DEMO_BADGES[2..].iter().map(|g| g.to_string()).collect();
for c in clients {
p.clients.insert(c.id, c);
}
@@ -539,6 +722,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(),
@@ -784,14 +968,19 @@ fn demo_social(app: &mut App) {
neon.message.author_id = None;
app.social.dm.stored.push(("demo-dev".into(), neon));
app.social.dm.bookmark_of.insert("demo-dev".into(), DEMO + 2);
// Unread: Mira's and Lumen's messages came while away.
if let Some(view) = app.sessions.get_mut(&DEMO) {
// The samples came one by one, as new ones do: all are read (no "New"
// line, which a gateway page on screen gets), but for Mira's and
// Lumen's messages, which came while away.
for view in app.sessions.values_mut() {
for tab in &mut view.tabs {
tab.divider = None;
tab.catch_up();
match &tab.target {
ChatTarget::Private(uid) if uid == "demo-4" => tab.unread = 1,
ChatTarget::Private(uid) if uid == "demo-2" => tab.unread = 2,
_ => {}
_ => continue,
}
tab.read = None;
}
}
// A poke from Kairo, shown among the messages and in the bell.
@@ -980,17 +1169,25 @@ fn demo_social(app: &mut App) {
},
});
// Notifications: a mention, a message, an event, a friend online (and
// the poke above).
// Notifications: two mentions (unread: home shows them), a message, an
// event, a friend online (and the poke above).
use crate::social::{NoticeKind, NoticeTarget};
app.notify(
NoticeKind::Mention,
"Talon mentioned you".into(),
"Nova, can you open the raid at 20:00? — #Chill Zone · Nightfall Guild".into(),
"Nova, can you open the raid at 20:00? — Chill Zone · Nightfall Guild".into(),
NoticeTarget::Chat(DEMO, ChatTarget::Channel(2)),
"Talon".into(),
Some("demo-6".into()),
);
app.notify(
NoticeKind::Mention,
"Zeph mentioned you".into(),
"Nova, are you healing tonight? — Raid Night · Nightfall Guild".into(),
NoticeTarget::Chat(DEMO, ChatTarget::Channel(4)),
"Zeph".into(),
Some("demo-7".into()),
);
app.notify(
NoticeKind::Event,
"Late Night Lofi & Chat starts in 50 min".into(),
@@ -1002,7 +1199,7 @@ fn demo_social(app: &mut App) {
app.notify(
NoticeKind::Friend,
"Ivy is online".into(),
"on Pixel Lounge · #Art Corner".into(),
"on Pixel Lounge · Art Corner".into(),
NoticeTarget::Contact("demo-ivy".into()),
"Ivy".into(),
Some("demo-ivy".into()),
@@ -1017,7 +1214,7 @@ fn demo_social(app: &mut App) {
);
for (i, n) in app.social.notices.iter_mut().enumerate() {
n.ts_ms = now - (i as i64 * 9 + 2) * min;
n.unread = i < 3;
n.unread = i < 3 || n.kind == NoticeKind::Mention;
}
app.refresh_notices();
@@ -1047,13 +1244,26 @@ const DEMO_HOST_BANNER: &str = "https://nightfall.example/banner.png";
const DEMO_CHILL_BANNER: &str = "https://nightfall.example/chill.png";
const DEMO_MUSIC_BANNER: &str = "https://nightfall.example/music.png";
const DEMO_RAID_BANNER: &str = "https://nightfall.example/raid.png";
/// A picture a message shows (`[img]`).
const DEMO_LOOT_PICTURE: &str = "https://nightfall.example/loot.png";
/// The sample's masked link (`VOELIN_OPEN=link-confirm`).
const DEMO_RAID_BOARD: &str = "https://nightfall.example/raids";
const DEMO_SERVER_ICON: u32 = 3_120_211_001;
const DEMO_ADMIN_ICON: u32 = 3_120_211_002;
const DEMO_MOD_ICON: u32 = 3_120_211_003;
const DEMO_MUSIC_ICON: u32 = 3_120_211_004;
/// Real badge GUIDs: 20th Anniversary, TeamSpeak Jedi (Nova's), Gamescom
/// 2019, Pride and Year of the Tiger 2022 (Lumen's).
const DEMO_BADGES: [&str; 5] = [
"4b27be5a-b92a-4b30-8b2d-14b59653f427",
"64221fd1-706c-4bb2-ba55-996c39effa79",
"b82a45a5-b235-4926-be77-de102222e5eb",
"ceee2445-4fbf-4f06-9421-286f0f4e875a",
"92356386-0451-4a97-87d9-10ff4f43260c",
];
/// Avatars, icons and banners as the engine reports them once they are in
/// its cache (here a folder of synthetic pictures in the temporary
/// Avatars, icons, banners and badges as the engine reports them once they
/// are in its cache (here a folder of synthetic pictures in the temporary
/// directory).
fn demo_pictures(app: &mut App) {
let session = DEMO as u64;
@@ -1077,6 +1287,7 @@ fn demo_pictures(app: &mut App) {
(DEMO_CHILL_BANNER, demo_picture(900, 120, 11)),
(DEMO_RAID_BANNER, demo_picture(240, 240, 5)),
(DEMO_MUSIC_BANNER, demo_picture(180, 36, 7)),
(DEMO_LOOT_PICTURE, demo_picture(640, 300, 9)),
] {
let path = save(url.rsplit('/').next().unwrap_or(url), picture);
events.push(Event::PictureReady { session, url: url.into(), path });
@@ -1090,6 +1301,19 @@ fn demo_pictures(app: &mut App) {
let path = save(&icon.to_string(), demo_icon(color, shape));
events.push(Event::IconReady { session, icon, path });
}
// Stand-ins for the badges' pictures on TeamSpeak's server.
let badge_looks = [
([242, 178, 44], Shape::Ring),
([90, 170, 255], Shape::Moon),
([45, 196, 132], Shape::Diamond),
([240, 110, 160], Shape::Disc),
([255, 140, 90], Shape::Diamond),
];
for (guid, (color, shape)) in DEMO_BADGES.into_iter().zip(badge_looks) {
let Some(url) = voelin_model::badges::icon_url(guid) else { continue };
let path = save(&format!("badge-{guid}"), demo_icon(color, shape));
events.push(Event::PictureReady { session, url, path });
}
// Some people have pictures, the rest initials.
for (sample_session, uid, seed) in [
(session, "demo-2", 1),
@@ -1370,6 +1594,45 @@ fn demo_chat(app: &mut App, session: u64) {
None,
),
(DEMO, "dex", 5, "🎉🎉".into(), 10, false, Vec::new(), false, None),
// Formatting as TeamSpeak clients send it (BBCode).
(
DEMO,
"Nova",
1,
format!(
"[b]Raid night[/b] moves from [s]20:00[/s] to [color=#ff8a3d]20:30[/color], \
sign up on the [url={DEMO_RAID_BOARD}]raid board[/url]."
),
9,
false,
vec![react("👍", 4, true)],
true,
None,
),
(
DEMO,
"Kairo",
3,
"[quote=Nova]bring elixirs[/quote]\nAlready stocked up 🧪".into(),
8,
false,
Vec::new(),
false,
None,
),
(
DEMO,
"Mira",
4,
"Roles for tonight:\n[list]\n[*][b]Tank:[/b] Kairo\n[*][b]Healer:[/b] Mira\n\
[*][i]Everyone else:[/i] damage[/list]\nPull timer: [code]/pull 10[/code]"
.into(),
7,
false,
Vec::new(),
false,
None,
),
(
DEMO,
"Ari",
@@ -1381,6 +1644,17 @@ fn demo_chat(app: &mut App, session: u64) {
false,
None,
),
(
DEMO,
"Talon",
6,
format!("Last week's loot [img]{DEMO_LOOT_PICTURE}[/img]"),
6,
false,
Vec::new(),
false,
None,
),
(DEMO + 1, "Ivy", 0, "Welcome to the lounge!".into(), 30, false, Vec::new(), false, None),
(
DEMO + 1,
@@ -1582,3 +1856,122 @@ fn demo_topic(app: &mut App) {
},
});
}
/// The sample messages before the sample chats' first ones: how many, how
/// many a page, and their ids (the sample chats use ids below 500).
const OLDER: i64 = 30;
const OLDER_PAGE: i64 = 15;
const OLDER_ID: i64 = 500;
/// The page before `oldest` of a sample chat, as the engine answers
/// `Command::LoadOlderHistory`: older small talk, a page at a time, the last
/// one `complete`. The first page goes back from `oldest` (from `now_ms` in
/// an empty chat), the next ones from the sample message before.
pub(crate) fn demo_older(
target: &ChatTarget,
oldest: Option<&HistoryMessage>,
now_ms: i64,
) -> (Vec<HistoryMessage>, bool) {
const PEOPLE: [(&str, u16); 6] =
[("Nova", 1), ("Kairo", 3), ("Mira", 4), ("dex", 5), ("Talon", 6), ("Lumen", 2)];
const TEXTS: [&str; 10] = [
"Anyone still around?",
"Patch notes are up, the healer changes look good.",
"Who has the key for the vault run?",
"I can do Thursday, not Friday.",
"Lag spike on my side, back in a sec.",
"gg everyone, that was close 😅",
"Is the new map in the rotation yet?",
"Uploading the clip from last night.",
"Coffee first, then raids ☕",
"Same time next week?",
];
let (first, from_ms) = match oldest {
Some(m) if m.id >= OLDER_ID => (m.id - OLDER_ID + 1, m.message.ts_ms),
Some(m) => (0, m.message.ts_ms),
None => (0, now_ms),
};
let last = (first + OLDER_PAGE).min(OLDER);
let messages = (first..last)
.map(|n| {
// Two in a row by each person.
let (author, client) = PEOPLE[(n / 2 % 6) as usize];
HistoryMessage {
id: OLDER_ID + n,
message: ChatMessage {
target: target.clone(),
author_name: author.into(),
author_uid: Some(format!("demo-{client}")),
author_id: Some(client),
text: TEXTS[(n % 10) as usize].into(),
ts_ms: from_ms - (n - first + 1) * 23 * 60_000,
via_relay: false,
blocked: false,
},
source: MessageSource::Voice,
remote_id: Some(OLDER_ID + n),
topic_id: None,
reactions: Vec::new(),
pinned: false,
rev: 1,
}
})
.collect();
(messages, last >= OLDER)
}
/// Answer [`App::load_older`] in demo mode (no engine runs) with
/// [`demo_older`], a moment later as a server would.
pub(crate) fn answer_older(session: i64, target: ChatTarget, oldest: Option<HistoryMessage>) {
slint::Timer::single_shot(Duration::from_millis(600), move || {
let now = chrono::Utc::now().timestamp_millis();
let (messages, complete) = demo_older(&target, oldest.as_ref(), now);
with_app(|app| {
app.handle_event(Event::ChatHistory {
session: session as u64,
target,
messages,
source: HistorySource::Gateway,
complete,
});
});
});
}
#[cfg(test)]
mod tests {
use super::*;
/// Two pages back from the sample chat's first message, each older than
/// the one before, the second one the last.
#[test]
fn demo_older_pages_in_order_and_completes() {
let target = ChatTarget::Channel(2);
let (first, complete) = demo_older(&target, None, 1_000_000_000);
assert_eq!(first.len(), OLDER_PAGE as usize);
assert!(!complete, "a second page follows");
let ids: Vec<i64> = first.iter().map(|m| m.id).collect();
assert_eq!(ids, (OLDER_ID..OLDER_ID + OLDER_PAGE).collect::<Vec<_>>());
assert!(first.windows(2).all(|w| w[1].message.ts_ms < w[0].message.ts_ms));
assert!(
first.iter().all(|m| m.message.target == target && m.message.ts_ms < 1_000_000_000)
);
let oldest = first.last().unwrap();
let (second, complete) = demo_older(&target, Some(oldest), 0);
assert!(complete);
assert_eq!(second.len(), (OLDER - OLDER_PAGE) as usize);
assert_eq!(second[0].id, oldest.id + 1);
assert!(second.iter().all(|m| m.message.ts_ms < oldest.message.ts_ms));
// A sample chat's own message: back from it.
let sample = HistoryMessage { id: 3, ..oldest.clone() };
let (again, _) = demo_older(&target, Some(&sample), 0);
assert_eq!(again[0].id, OLDER_ID);
assert!(again[0].message.ts_ms < sample.message.ts_ms);
// Nothing after the last page.
let (rest, complete) = demo_older(&target, second.last(), 0);
assert!(rest.is_empty() && complete);
}
}
+23 -22
View File
@@ -1,7 +1,7 @@
//! Twemoji as images. The software renderer draws no colour glyphs, so the
//! UI shows emoji as pictures: this module reads the packed archive
//! (`assets/twemoji.bin`, made by `scripts/pack-twemoji.py`), finds the
//! picture of a grapheme cluster, splits text into runs of text and emoji,
//! picture of a grapheme cluster, splits text into runs of words and emoji,
//! and lists emoji for the picker. Decoding the SVGs into images is
//! `images.rs`' job.
@@ -307,27 +307,22 @@ pub struct Run {
pub emoji: Option<String>,
}
/// Text split into runs for a wrapping layout: a run per word (with the
/// space after it) and per emoji. `None` if the text has no emoji (show it
/// as one text). Line breaks become spaces.
pub fn runs(text: &str) -> Option<Vec<Run>> {
if !text.chars().any(may_be_emoji) {
return None;
}
/// A line of text split into runs for a wrapping layout: a run per word
/// (with the space after it) and per emoji. A line break is a space: lines
/// are blocks of their own (`vm::bbcode`).
pub fn split(text: &str) -> Vec<Run> {
let emoji = text.chars().any(may_be_emoji);
let mut out: Vec<Run> = Vec::new();
let mut word = String::new();
let mut any = false;
for g in text.graphemes(true) {
if let Some(key) = key_for(g) {
if let Some(key) = emoji.then(|| key_for(g)).flatten() {
if !word.is_empty() {
out.push(Run { text: std::mem::take(&mut word), emoji: None });
}
out.push(Run { text: g.to_owned(), emoji: Some(key) });
any = true;
continue;
}
let space = g.chars().all(char::is_whitespace);
if space {
if g.chars().all(char::is_whitespace) {
// Spaces stay with the word before them (or stand alone after
// an emoji).
word.push(' ');
@@ -339,7 +334,7 @@ pub fn runs(text: &str) -> Option<Vec<Run>> {
if !word.is_empty() {
out.push(Run { text: word, emoji: None });
}
any.then_some(out)
out
}
/// One to three emoji and nothing else but spaces: shown large.
@@ -391,15 +386,21 @@ mod tests {
#[test]
fn text_runs() {
assert_eq!(runs("plain text, no emoji"), None);
assert_eq!(runs("em — dash"), None);
let r = runs("hi 👋 there").unwrap();
let texts: Vec<_> = r.iter().map(|r| (r.text.as_str(), r.emoji.as_deref())).collect();
assert_eq!(texts, [("hi ", None), ("👋", Some("1f44b")), (" ", None), ("there", None)]);
let texts = |text: &str| -> Vec<(String, Option<String>)> {
split(text).into_iter().map(|r| (r.text, r.emoji)).collect()
};
let word = |w: &str| (w.to_owned(), None);
assert_eq!(texts("plain text, no"), [word("plain "), word("text, "), word("no")]);
assert_eq!(texts("em — dash"), [word("em "), word("— "), word("dash")]);
let r = split("hi 👋 there");
assert_eq!(
texts("hi 👋 there"),
[word("hi "), ("👋".into(), Some("1f44b".into())), word(" "), word("there")]
);
assert!(!is_jumbo(&r));
let r = runs("🔥🔥 ").unwrap();
assert!(is_jumbo(&r));
assert!(!is_jumbo(&runs("🔥🔥🔥🔥").unwrap()));
assert!(is_jumbo(&split("🔥🔥 ")));
assert!(!is_jumbo(&split("🔥🔥🔥🔥")));
assert!(!is_jumbo(&split("no emoji")));
}
#[test]
+6 -2
View File
@@ -126,12 +126,16 @@ impl App {
self.refresh_events();
}
/// Channels an event can be in: server-wide first.
/// Channels an event can be in: server-wide first; no lines or empty
/// spacers.
fn event_channels(&self) -> Vec<(Option<u64>, String)> {
let mut out = vec![(None, "Server-wide".to_owned())];
if let Some(view) = self.view() {
out.extend(
view.presence.channels.values().map(|c| (Some(c.id), format!("#{}", c.name))),
view.presence
.channels
.values()
.filter_map(|c| Some((Some(c.id), vm::tree::listed_title(c)?.to_owned()))),
);
}
out
+70 -24
View File
@@ -1,15 +1,20 @@
//! The home page (design mockup 01): live streams on our servers, what is
//! happening there (events, scheduled streams, server news), and the
//! Library of recordings and clips. Friends are in `social.rs`, the recent
//! chats in `messages.rs`.
//! The home page (design mockup 01): where we were with voice last, live
//! streams on our servers, what is happening there (events, scheduled
//! streams, server news), and the Library of recordings and clips.
//! Friends and the unread mentions are in `social.rs`, the recent chats in
//! `messages.rs`.
use std::path::{Path, PathBuf};
use slint::ComponentHandle;
use voelin_core::VoiceState;
use crate::app::{App, Bridge, HappeningItem, LiveItem, Page, RecordingItem};
use crate::app::{
App, Bridge, HappeningItem, LiveItem, Page, RecordingItem, ResumeItem, ServerItem,
};
use crate::settings::LastVoice;
use crate::vm;
use crate::vm::home::ResumeAction;
use crate::vm::social::{event_when, plain};
/// What a "What's Happening" entry opens.
@@ -19,26 +24,19 @@ pub(crate) enum Happening {
News(i64),
}
/// "screen" → "Screen".
fn kind_label(kind: &str) -> String {
let mut chars = kind.chars();
chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
}
impl App {
/// Streams on our servers: those the server lists (any channel; we can
/// watch them at once), the gateways' directories, and clients flagged
/// streaming.
fn live_rooms(&self) -> Vec<LiveItem> {
let mut rooms = Vec::new();
for b in &self.bookmarks {
for (b, backdrop) in self.bookmarks.iter().zip(vm::servers::tints(&self.bookmarks)) {
let Some(view) = self.sessions.get(&b.id) else { continue };
let channel_of = |cid: Option<u64>| {
cid.and_then(|c| view.presence.channels.get(&c))
.map(|c| c.name.clone())
.map(|c| vm::tree::channel_title(c).0.to_owned())
.unwrap_or_default()
};
let backdrop = vm::avatar::tint(&b.name);
let item = |id: String,
title: String,
client: Option<u16>,
@@ -71,13 +69,7 @@ impl App {
let mut room = item(s.id.clone(), title, Some(s.streamer.0), None, name);
room.channel = channel_of(view.channel_of(s.streamer.0)).into();
room.viewers = view.stream_viewers.get(&s.id).map_or(0, |v| *v as i32);
room.kind = match s.kind {
voelin_core::stream::StreamKind::Screen => "Screen",
voelin_core::stream::StreamKind::Window => "Window",
voelin_core::stream::StreamKind::Camera => "Camera",
voelin_core::stream::StreamKind::Other(_) => "",
}
.into();
room.kind = vm::streams::kind_label(&s.kind).into();
room.watchable = view.state.own_client != Some(s.streamer.0);
covered.push(s.streamer.0);
rooms.push(room);
@@ -101,7 +93,7 @@ impl App {
);
room.channel = channel_of(e.channel).into();
room.viewers = e.viewers.map_or(0, |v| v as i32);
room.kind = kind_label(&e.kind).into();
room.kind = vm::streams::directory_kind_label(&e.kind).into();
covered.extend(e.client_id);
rooms.push(room);
}
@@ -240,6 +232,62 @@ impl App {
self.connect_voice();
}
fn last_resume(&self) -> Option<vm::home::Resume> {
let voice = |id| self.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice);
vm::home::resume(self.settings.last_voice.as_ref(), &self.bookmarks, voice)
}
/// Home's "Continue where you left off", its server as the rail shows
/// it (`servers`).
pub(crate) fn last_place(&self, servers: &[ServerItem]) -> ResumeItem {
let Some(resume) = self.last_resume() else { return ResumeItem::default() };
let Some(server) = servers.iter().find(|s| i64::from(s.id) == resume.bookmark) else {
return ResumeItem::default();
};
ResumeItem {
shown: true,
server_id: server.id,
server: server.name.clone(),
initials: server.initials.clone(),
tint: server.tint,
icon: server.icon.clone(),
channel: resume.title().into(),
open: resume.action == ResumeAction::Open,
connecting: server.status == "connecting",
}
}
/// The last place's button: its server, connected into the channel
/// unless voice is there already.
pub(crate) fn resume(&mut self) {
let Some(resume) = self.last_resume() else { return };
self.show_server(resume.bookmark);
if resume.action == ResumeAction::Join {
self.connect_voice_to(Some(resume.path.join("/")), None, None);
}
}
/// Keep where we are with voice in `session` as the last place
/// (`ui.last_voice`); whether it changed. Not for the sample sessions.
pub(crate) fn remember_voice(&mut self, session: i64) -> bool {
if self.demo_ui {
return false;
}
let Some(view) = self.sessions.get(&session) else { return false };
let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else {
return false;
};
let channel = vm::tree::channel_path(&view.presence, cid);
let Some(b) = self.bookmark(session).filter(|_| !channel.is_empty()) else { return false };
let last = LastVoice { bookmark: session, address: b.address.clone(), channel };
if self.settings.last_voice.as_ref() == Some(&last) {
return false;
}
self.settings.last_voice = Some(last);
self.store_settings();
true
}
/// The folder of recordings and clips.
fn recordings_dir(&self) -> PathBuf {
voelin_core::studio::recording_dir(&self.prefs)
@@ -324,7 +372,5 @@ mod tests {
assert!(items.iter().any(|i| i.clip && i.detail.starts_with("2 B")));
assert!(recordings_in(&dir.join("missing")).is_empty());
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(kind_label("screen"), "Screen");
assert_eq!(kind_label(""), "");
}
}
+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"));
}
}
+13 -5
View File
@@ -1,7 +1,8 @@
//! Requests from the platform around the window: on Android a tapped
//! notification or something shared to the app ("Share to Voelin"). They
//! can come from any thread and before the window runs; [`request`] keeps
//! them until the window takes them on its thread.
//! notification or something shared to the app ("Share to Voelin"), and a
//! TeamSpeak link to open. They can come from any thread and before the
//! window runs; [`request`] keeps them until the window takes them on its
//! thread.
use std::path::PathBuf;
use std::sync::{Mutex, PoisonError};
@@ -21,6 +22,9 @@ pub enum Request {
/// should not post into a chat), the files are uploaded to the current
/// channel and linked there, as the composer's attach button does.
Share { text: Option<String>, files: Vec<PathBuf> },
/// Open a TeamSpeak link (`ts3server://`, `teamspeak://`, `tmspk.gg`):
/// the server dialog filled in from it, or a move in voice.
OpenLink(String),
}
static PENDING: Mutex<Vec<Request>> = Mutex::new(Vec::new());
@@ -52,6 +56,9 @@ pub(crate) fn take() {
nav.invoke_show(Page::Server);
with_app(|app| app.share(&nav, text, files));
}
Request::OpenLink(url) => {
with_app(|app| app.open_link(&url));
}
}
}
}
@@ -67,8 +74,9 @@ impl App {
_ => view.state.own_channel,
}
.map(|c| {
let name = view.presence.channels.get(&c).map(|c| c.name.as_str());
(c, name.map_or_else(|| "the channel".to_owned(), |n| format!("#{n}")))
let name =
view.presence.channels.get(&c).map(|c| crate::vm::tree::channel_title(c).0);
(c, name.map_or_else(|| "the channel".to_owned(), str::to_owned))
});
Some((id, tab.title.clone(), channel))
});
+2
View File
@@ -13,10 +13,12 @@ mod hotkey;
mod identities;
mod images;
mod inbox;
mod links;
mod members;
mod messages;
#[cfg(not(target_os = "android"))]
mod myts;
mod popout;
mod previews;
mod servers;
mod settings;
+70
View File
@@ -0,0 +1,70 @@
//! TeamSpeak links opened in the app (`ts3server://`, `teamspeak://` and
//! `tmspk.gg`), from a message or the platform.
use slint::ComponentHandle;
use voelin_core::VoiceState;
use voelin_model::{Link, ServerLink};
use crate::app::{App, Nav};
use crate::vm;
impl App {
/// Open a TeamSpeak link. In voice on its server: show it and move into
/// the link's channel (a locked one asks for its password if the link
/// has none or a wrong one). Otherwise the server dialog, filled in from
/// the link (the saved server's when there is one): nothing connects
/// before its Connect.
pub(crate) fn open_link(&mut self, url: &str) {
let link = match Link::parse(url) {
Some(Link::Server(link)) => link,
Some(Link::Invite(_)) => {
self.set_status(
"TeamSpeak invite codes (tmspk.gg/…) can't be opened yet; ask for the server address",
);
return;
}
None => {
self.set_status("Not a TeamSpeak server link");
return;
}
};
let in_voice = |id: i64| {
self.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected)
};
match vm::servers::link_server(&self.bookmarks, &link.address(), self.current, in_voice) {
Some((id, true)) => self.move_by_link(id, &link),
saved => self.open_link_form(saved.map(|(id, _)| id), &link),
}
}
/// In voice on the link's server: show it, and move into its channel.
fn move_by_link(&mut self, session: i64, link: &ServerLink) {
self.show_server(session);
let Some(path) = &link.channel else { return };
let Some(view) = self.sessions.get_mut(&session) else { return };
let Some(channel) = vm::servers::channel_by_path(&view.presence, path) else {
let server = self.bookmark(session).map(|b| b.name.clone()).unwrap_or_default();
self.set_status(format!("{server} has no channel \u{201c}{path}\u{201d}"));
return;
};
if view.state.own_channel == Some(channel) {
return;
}
// As if typed into the password dialog: a wrong one asks again.
if let Some(password) = &link.channel_password {
view.channel_passwords.insert(channel, password.clone());
}
self.join_channel(session, channel);
}
/// The server dialog, filled in from the link over the saved server's
/// form, or a new server's.
fn open_link_form(&mut self, saved: Option<i64>, link: &ServerLink) {
let form = self.bookmark_form(saved.unwrap_or(-1));
let form = vm::servers::link_form(link, form, &self.default_nickname());
let Some(ui) = self.ui.upgrade() else { return };
let nav = ui.global::<Nav>();
nav.set_bookmark_form(form);
nav.set_bookmark_open(true);
}
}
+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()
+30 -11
View File
@@ -4,9 +4,8 @@
use slint::ComponentHandle;
use voelin_core::{Command, Contact, Relation};
use voelin_model::ChatTarget;
use crate::app::{App, Bridge, MemberCard};
use crate::app::{App, Bridge, MemberCard, Nav};
use crate::settings::ClientPlayback;
use crate::vm;
@@ -53,6 +52,7 @@ impl App {
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
.map(|g| g.name.clone().into())
.collect();
let badges = vm::tree::badge_items(&client.badges, &view.pictures);
Some(MemberCard {
open: true,
id: i32::from(id),
@@ -63,6 +63,7 @@ impl App {
status: vm::tree::status_of(client, view.talking.contains(&id)).into(),
description: client.description.clone().unwrap_or_default().into(),
groups: crate::app::model(groups),
badges: crate::app::model(badges),
country: client.country.clone().unwrap_or_default().into(),
talk_power: client.talk_power,
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
@@ -86,24 +87,18 @@ impl App {
};
let (client_id, nickname, uid) = (client.id, client.nickname.clone(), client.uid.clone());
match action {
// Private chats are on the messages page.
"message" => {
if let Some(uid) = uid {
self.open_chat(ChatTarget::Private(uid), true);
self.open_member(-1);
self.open_dm_with(Some(id), &uid);
}
}
"watch" => {
self.open_member(-1);
self.watch_client(client_id);
}
"poke" => {
self.command(|session| Command::Poke {
session,
client: client_id,
message: String::new(),
});
self.set_status(format!("Poked {nickname}"));
}
"poke" => self.ask_poke(id, client_id),
"friend" | "blocked" => {
let Some(uid) = uid else { return };
let wanted = if action == "friend" { Relation::Friend } else { Relation::Blocked };
@@ -126,6 +121,30 @@ impl App {
}
}
/// Open the poke dialog for a client (the member card, a contact).
pub(crate) fn ask_poke(&mut self, session: i64, client: u16) {
let Some(view) = self.sessions.get(&session) else { return };
let name = view.nickname(client);
self.poke_target = Some((session, client, name.clone()));
let Some(ui) = self.ui.upgrade() else { return };
let nav = ui.global::<Nav>();
nav.set_poke_name(name.into());
nav.set_poke_open(true);
}
/// The poke dialog's Send, with its message (may be empty).
pub(crate) fn send_poke(&mut self, text: &str) {
let Some((session, client, name)) = self.poke_target.take() else { return };
if !self.demo_ui {
self.engine.send(Command::Poke {
session: session as u64,
client,
message: vm::social::poke_message(text),
});
}
self.set_status(format!("Poked {name}"));
}
/// The card's volume slider, in percent.
pub(crate) fn member_volume(&mut self, percent: f32) {
let Some(view) = self.view() else { return };
+108 -25
View File
@@ -1,13 +1,17 @@
//! Direct messages (design mockup 02) and the recent chats of the home
//! page: every chat the sessions hold and the newest ones in the history
//! store, across servers; the open private chat with who it is with; TS3
//! and TS6 offline messages (mail the server keeps).
//! page and its sidebar: every chat the sessions hold and the newest ones
//! in the history store, across servers; the open private chat with who it
//! is with; TS3 and TS6 offline messages (mail the server keeps).
//!
//! A private chat is a chat tab of its session (`ChatTarget::Private`
//! stored under the peer's unique id), so opening one selects its server
//! and its tab: the chat view's machinery (history pages, the composer)
//! serves it. A chat only in the store (its server is not connected, or no
//! longer a bookmark) is read from there and shown read-only.
//! serves it. The chat strip of the server page leaves these tabs out, so
//! leaving the messages page makes the strip's chat current again
//! ([`App::close_messages`]), and coming back the open one
//! ([`App::messages_shown`]). A chat only in the store (its server is not
//! connected, or no longer a bookmark) is read from there and shown
//! read-only.
use std::collections::HashMap;
@@ -16,7 +20,9 @@ use voelin_core::{Command, HistoryMessage, OfflineMessage, OfflineMessageInfo, V
use voelin_model::ChatTarget;
use voelin_store::PageQuery;
use crate::app::{App, Bridge, ConversationItem, DmPeer, FileItem, Nav, OfflineForm, Page, later};
use crate::app::{
App, Bridge, ConversationItem, DmPeer, FileItem, Nav, OfflineForm, Page, SessionView, later,
};
use crate::vm;
use crate::vm::social::{ago, list_time, matches, plain, preview};
@@ -76,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);
@@ -195,7 +198,10 @@ impl App {
let name = session
.and_then(|s| self.sessions.get(&s))
.and_then(|v| v.presence.channels.get(cid))
.map_or_else(|| format!("#channel {cid}"), |c| format!("#{}", c.name));
.map_or_else(
|| format!("Channel {cid}"),
|c| vm::tree::channel_title(c).0.to_owned(),
);
(name, slint::Image::default(), false, 1)
}
ChatTarget::Server => (server.clone(), slint::Image::default(), false, 0),
@@ -223,7 +229,11 @@ impl App {
ago: ago(ts).into(),
unread: chat.unread,
initials: vm::avatar::initials(&title).into(),
tint: vm::avatar::tint(&title),
// A server's chat in the server's colour.
tint: match (kind, session) {
(0, Some(s)) => self.server_tint(s),
_ => vm::avatar::tint(&title),
},
avatar,
online,
selected: open.is_some_and(|o| {
@@ -234,7 +244,8 @@ impl App {
}
}
/// The DM list, the recent chats of home and the unread counts.
/// The DM list, the recent chats of home, the private chats of its
/// sidebar and the unread counts.
fn refresh_conversations(&self) {
let Some(ui) = self.ui.upgrade() else { return };
let bridge = ui.global::<Bridge>();
@@ -248,6 +259,15 @@ impl App {
.map(|(i, c)| self.conversation_item(i, c))
.collect();
vm::list::sync(&self.models.social.recent, &recent);
// Shown beside other pages: none is the open one.
let sidebar: Vec<ConversationItem> = vm::social::sidebar_dms(&dm.chats, 5)
.into_iter()
.map(|i| ConversationItem {
selected: false,
..self.conversation_item(i, &dm.chats[i])
})
.collect();
vm::list::sync(&self.models.social.sidebar_dms, &sidebar);
let private = |c: &&ChatRef| matches!(c.target, ChatTarget::Private(_));
let items: Vec<ConversationItem> = if dm.tab == 2 {
dm.inbox
@@ -288,11 +308,77 @@ impl App {
.collect()
};
vm::list::sync(&self.models.social.conversations, &items);
let unread: i32 = dm.chats.iter().filter(private).map(|c| c.unread).sum();
bridge.set_dm_unread(unread);
bridge.set_dm_unread(self.dm_unread());
bridge.set_inbox_unread(dm.inbox.iter().filter(|(_, m)| !m.read).count() as i32);
}
/// Unread messages in the private chats of every server (the rail and
/// the chat strip leave them out).
pub(crate) fn dm_unread(&self) -> i32 {
self.bookmarks
.iter()
.filter_map(|b| self.sessions.get(&b.id))
.map(SessionView::private_unread)
.sum()
}
/// The messages page is shown: the open private chat a session holds is
/// the current chat again (leaving the page made the strip's current).
pub(crate) fn messages_shown(&mut self) {
let Some(Open { session: Some(id), uid, mail: None, stored: false, .. }) =
self.social.dm.open.clone()
else {
return;
};
let target = ChatTarget::Private(uid);
// Not for a session that is gone (its server was deleted).
let Some(view) = self.sessions.get(&id) else { return };
if !view.tabs.iter().any(|t| t.target == target)
|| (self.current == Some(id)
&& view.tabs.get(view.current_tab).is_some_and(|t| t.target == target))
{
return;
}
self.focus_private(id, target);
}
/// Make the private chat `target` session `id`'s current chat, and that
/// server the current one. The tab first: selecting the server reads
/// the chat it shows, which must not be the strip's.
fn focus_private(&mut self, id: i64, target: ChatTarget) {
let index = self.chat_tab(id, target.clone());
self.sessions.entry(id).or_default().set_current_tab(index);
if self.current != Some(id) {
self.select_server(id);
}
self.open_chat(target, true);
}
/// The messages page was left: a session whose current chat is a
/// private one goes back to the chat strip's
/// ([`SessionView::channel_tab`]).
pub(crate) fn close_messages(&mut self) {
let mut changed = false;
for view in self.sessions.values_mut() {
changed |= view.leave_private();
}
if !changed {
return;
}
self.refresh_chat();
self.refresh_servers();
// What is read after the callback: a server picked on the rail
// (`Nav.select-server` leaves the page first) is selected by then,
// and the chat that came back here was never on screen.
later(|app| {
if let Some(id) = app.current {
app.fetch_previews(id);
}
app.prefetch_counts();
app.chat_shown_changed();
});
}
pub(crate) fn dm_tab(&mut self, tab: i32) {
self.social.dm.tab = tab;
if tab == 2 {
@@ -380,10 +466,7 @@ impl App {
vm::list::sync(&self.models.social.dm_lines, &[]);
let target = ChatTarget::Private(uid.to_owned());
if let (true, Some(id)) = (live, session) {
if self.current != Some(id) {
self.select_server(id);
}
self.open_chat(target, true);
self.focus_private(id, target);
} else if let Some(server_uid) = server_uid.filter(|_| !self.demo_ui) {
let history = self.engine.history();
let uid = uid.to_owned();
@@ -463,8 +546,8 @@ impl App {
Some(s) => match &s.away {
Some(m) if !m.is_empty() => format!("Away: {m} · {}", s.server),
Some(_) => format!("Away · {}", s.server),
None if s.channel_name.is_empty() => format!("Online · {}", s.server),
None => format!("Online · {} · #{}", s.server, s.channel_name),
None if s.channel_title.is_empty() => format!("Online · {}", s.server),
None => format!("Online · {} · {}", s.server, s.channel_title),
},
None => match contact.filter(|c| c.last_seen_ms > 0) {
Some(c) => format!("Offline · last seen {}", ago(c.last_seen_ms)),
@@ -494,10 +577,10 @@ impl App {
spots
.iter()
.map(|s| {
if s.channel_name.is_empty() {
if s.channel_title.is_empty() {
s.server.clone().into()
} else {
format!("{} · #{}", s.server, s.channel_name).into()
format!("{} · {}", s.server, s.channel_title).into()
}
})
.collect()
+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]
+140
View File
@@ -0,0 +1,140 @@
//! The stream we watch in a window of its own (desktop): the player alone,
//! optionally over the other windows, while the main window goes on. Its
//! Bridge global is filled like the main window's (`viewer_each`); the
//! pictures go only to the window that shows the player, as each window
//! scales them again. Closing it brings the stream back into the main
//! window.
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use tracing::warn;
use crate::app::{App, Bridge, Page, ViewerWindow, later};
/// The window, while there is one.
#[derive(Default)]
pub(crate) struct Popout {
pub window: Option<ViewerWindow>,
/// The last window stayed over the others: the next does too.
on_top: bool,
}
impl App {
/// `f` on the Bridge of the main window and of the viewer's window.
pub(crate) fn viewer_each(&self, f: impl Fn(&Bridge)) {
if let Some(ui) = self.ui.upgrade() {
f(&ui.global::<Bridge>());
}
if let Some(window) = &self.popout.window {
f(&window.global::<Bridge>());
}
}
/// `f` on the Bridge and the window that show the player: the viewer's
/// own while it has one, else the main window.
pub(crate) fn with_player(&self, f: impl FnOnce(&Bridge, &slint::Window)) {
match (&self.popout.window, self.ui.upgrade()) {
(Some(window), _) => f(&window.global::<Bridge>(), window.window()),
(None, Some(ui)) => f(&ui.global::<Bridge>(), ui.window()),
_ => {}
}
}
/// The player into a window of its own.
pub(crate) fn viewer_pop_out(&mut self) {
// One window on Android.
if cfg!(target_os = "android") || self.popout.window.is_some() || self.watch.is_none() {
return;
}
// The main window's full screen was the player's.
self.set_fullscreen(false);
let window = match ViewerWindow::new() {
Ok(window) => window,
Err(e) => {
self.set_status(format!("Cannot open the stream's window: {e}"));
return;
}
};
let bridge = window.global::<Bridge>();
crate::bind::streams::wire(&bridge);
self.models.attach(&bridge);
bridge.set_desktop(true);
bridge.set_viewer_on_top(self.popout.on_top);
window.window().on_close_requested(|| {
// After this event: the window goes away then.
later(|app| app.viewer_dock());
slint::CloseRequestResponse::HideWindow
});
// Without its window the stream stays in the main window.
if let Err(e) = window.show() {
warn!("cannot show the stream's window: {e}");
self.set_status(format!("Cannot open the stream's window: {e}"));
return;
}
// The picture moves with the player.
if let Some(ui) = self.ui.upgrade() {
let main = ui.global::<Bridge>();
bridge.set_viewer_frame(main.get_viewer_frame());
main.set_viewer_frame(slint::Image::default());
}
self.popout.window = Some(window);
self.theme_windows();
self.refresh_viewer();
// Our channel's people no longer lead the members panel.
self.refresh_tree();
}
/// The player back into the main window, on the stream's server page.
pub(crate) fn viewer_dock(&mut self) {
let Some(window) = self.close_popout() else { return };
if let Some(watch) = &mut self.watch {
watch.shown = true;
}
if let Some(ui) = self.ui.upgrade() {
ui.global::<Bridge>().set_viewer_frame(window.global::<Bridge>().get_viewer_frame());
}
// The main window may have gone to another server meanwhile: else
// the stream would play on, unseen.
let session =
self.watch.as_ref().and_then(|w| w.session).filter(|id| self.sessions.contains_key(id));
if let Some(id) = session
&& self.current != Some(id)
{
self.select_server(id);
}
self.refresh_viewer();
self.refresh_streams();
self.refresh_tree();
if self.watch_here() {
// Showing the page runs Nav code that calls back into the app.
self.navigate(|nav| nav.invoke_show(Page::Server));
}
}
/// Hide the viewer's window and forget it (leaving the stream, docking).
pub(crate) fn close_popout(&mut self) -> Option<ViewerWindow> {
let window = self.popout.window.take()?;
self.popout.on_top = window.global::<Bridge>().get_viewer_on_top();
let _ = window.hide();
Some(window)
}
/// The pointer over the player's window shows or hides (it hides with
/// the controls in full screen).
pub(crate) fn viewer_cursor(&self, shown: bool) {
self.with_player(|_, window| crate::streams::show_cursor(window, shown));
}
/// A picture of the viewer's window (screenshots, dev.rs).
pub(crate) fn viewer_snapshot(&self) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
self.popout.window.as_ref()?.window().take_snapshot().ok()
}
/// The main window closes: the studio's and the stream's windows go
/// with it, so the app ends.
pub(crate) fn close_windows(&mut self) {
if let Some(window) = self.studio.window.take() {
let _ = window.hide();
}
self.close_popout();
}
}
Loaded 100 of 165 files, more files were not shown because too many files have changed in this diff. Show more