Author SHA1 Message Date
faumarayandClaude Sonnet 5.5 1bee9c94e8 client: myTeamSpeak support leaves the client
CI / Linux checks (push) Failing after 1s
The public client repository must not carry third_party/schema-api:
TeamSpeak's non-public myTeamSpeak API protocol definitions, which came
without a licence. The account sign-in built on them (crates/voelin-myts)
goes with it, since nothing else in the client used that snapshot.

Removed: third_party/schema-api, crates/voelin-myts, the account module of
voelin-ui (sign-in, saved session, profile, avatar, badges, User Tag), the
login page at start and the live account test of voelin-core. The workspace
members, default-members and exclude lists, both manifests and Cargo.lock
no longer name them (tonic, prost-build and their dependencies drop out of
the lock file and THIRD_PARTY_NOTICES.md; about.hbs has no schema-api
section).

Settings -> My Account keeps the identity in use and shows a note that
account sign-in is not available in this build. The Slint account screens
stay, fed neutral values (Bridge.myts keeps its default: signed out, not
available, no prompt), so the account can return without redoing them. The
TeamSpeak protocol parts in tsproto/tsclientlib (myTS ID, other users'
badges and avatars) are untouched.

The account returns later through the gateway library (VoelinGateWay); the
research notes in docs/research/myteamspeak.md stay and say so. CHANGELOG,
docs/ui.md, docs/identity.md and SECURITY.md no longer describe the account
as present. A session an earlier build saved stays in the system keyring
(item myts/session) until the user deletes it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 00:17:05 +03:00
faumarayandClaude Fable 5.1 259bdee6e1 claude: implementer check step no longer names the client's own-crates script
The agent definition is shared by all Voelin repositories; the way to list
a repository's own crates belongs in that repository's CLAUDE.md.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 19:35:14 +03:00
faumarayandClaude Fable 5.1 011044d9d0 claude: multi-agent orchestration policy, MAO agents and session defaults
Root CLAUDE.md scopes the orchestration rules to the main session
(decompose, delegate, track attempts, escalate after 3 failures, review
chain with fresh Sonnet and Opus reviewers, Gitea instead of GitHub).
.claude/agents/ defines mao-designer (opus/max), mao-implementer
(sonnet/xhigh), mao-sonnet-reviewer (sonnet/xhigh), mao-opus-reviewer
(opus/max) and mao-helper (haiku). .claude/settings.json sets the session
default model (fable) and effort (xhigh: this build's settings schema has no
"max" for effortLevel; the agents that need max carry it in their
frontmatter).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 18:32:32 +03:00
faumarayandClaude Fable 5.1 5ca22fbe66 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>
2026-10-13 18:27:57 +03:00
faumaray 29ee56662c Обновить .gitea/workflows/ci.yml
Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
2026-10-12 14:28:22 +00:00
faumaray a9bcb7f7bc Обновить .gitea/workflows/ci.yml
Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
2026-10-12 14:26:37 +00:00
faumaray c40b23b894 Обновить .gitea/workflows/ci.yml
Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
2026-10-12 14:25:05 +00:00
Aleksey Selihov 4fcea5f173 Обновить .gitea/workflows/ci.yml
Signed-off-by: Aleksey Selihov <faumaray@noreply.localhost>
2026-10-12 14:24:47 +00:00
faumaray d7390f4450 Обновить .gitea/workflows/release.yml
Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
2026-10-12 12:44:01 +00:00
faumaray 352640de34 Обновить .gitea/workflows/release.yml
Signed-off-by: Aleksey Selihov <faumaray@gmail.com>
2026-10-12 12:41:44 +00:00
Claude d0cd3f6cfd ui: the Servers tab is titled Servers, and the voice card names only the channel
On the phone's Servers tab the top bar showed the server's name and counts,
which the server card right below it shows too, and the voice card named
the server again ("Chill Zone / Nightfall Guild"). The top bar now says
Servers, as the Activity and You tabs say their names; the server card
stays the one place for the name, the counts, the banner and its Edit
server / Add a server menu. The voice card shows only the channel, on
desktop too; while connecting, before there is a channel, it shows
Connecting… alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 18:53:08 +00:00
Claude 22fac502fa release: one Cargo job on GitHub's runners again
The Release run on this branch lost its Linux and Flatpak runners
about 30 minutes in, while the generated UI library compiled next to
other crates: the runners have 16 GB and were killed. The same jobs
passed with one job (8359ba8). The GitHub release workflow sets
CARGO_BUILD_JOBS=1 again, and its Flatpak job adds it to the manifest
before building, since flatpak-builder does not pass the job's
environment on. The Gitea workflow, the Docker images and the manifest
itself keep Cargo's default job count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 17:35:16 +00:00
Claude 034ee44e60 ui: the phone's voice screen gets one header, room for chat and Hold to talk
The shell's top bar is the only header on the voice screen: Back, the
channel on its banner, the server below it. ChannelBar and ChatHeader are
gone, Pinned Messages and Topics are entries of the More menu, and Leave is
only in the bottom bar. The people strip and the scroll cap leave the chat
about 320 px at 390 x 844 (it had about 190).

With push-to-talk, Hold to talk is the bottom bar's middle control and the
composer's microphone button is gone; Go Live and Share are one Share
control that opens the share menu, as on desktop; the microphone button
reads Mic on or Mic off.

The audio form was only filled when the settings opened, so every start
showed push-to-talk controls whatever the stored mode; the transmit mode is
now set at start and when the setting changes.

VOELIN_OPEN=more opens the More menu for screenshots. The menu is not in a
layout, so Slint centred it in the bar and it opened 30 px low; it now sits
at the bar's corner.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 17:34:15 +00:00
Claude a6caffa579 ui: streams pop out into a window of their own
Pop out now opens ViewerWindow: the player alone, titled with the
stream, which a pin keeps on top of other windows (always-on-top). The
main window goes on; the stream's card on the voice page says it plays
in its own window, with Bring back; closing the window brings it back
too, on the stream's server, and Leave closes it. Pictures go only to
the window that shows the player, so none is scaled twice; full screen
and the cursor follow that window.

The stream callbacks take a Bridge, the models attach to any Bridge,
the theme is copied to every window of its own, and one main-window
close handler, installed at start, closes the studio's and the stream's
windows (the studio installed its own before). Desktop only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 14:20:36 +00:00
Claude d404cb06a7 ui: a theatre mode for the stream viewer
What "pop out" did, filling the window without the shell, is now theatre
mode (Nav.theatre) with a button of its own in the player. The chat stays
under the picture, the members button goes, and it ends with the viewer;
a narrow window keeps the phone layout. Escape leaves full screen, then
theatre mode: the window's keys take the focus when the viewer moves to
the whole window, into full screen or from it back to theatre mode, since
what had it is gone.

Until the viewer gets a window of its own, Pop out toggles theatre mode
too, and VOELIN_OPEN=popout is watch,theatre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 11:45:04 +00:00
Claude 0aee710c19 ui: the stream viewer's controls hide while you watch
The controls fade 2.5 s after the pointer last moved over the picture and
come back when it moves; in full screen the cursor hides with them, and
on a touch screen a tap on the picture shows or hides them. A status or
the stream's end keeps them, and so does a pointer that was never over
the picture, so screenshots still show them.

In the shell the streamer, title, viewers, LIVE and the quality move from
the picture into the header, so nothing covers the picture at rest; in
full screen (and on the phone) they stay over it under a taller, darker
shade and hide with the controls. The streamer's avatar now comes from
the engine's cache for any streamer, also one outside our channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 09:39:26 +00:00
Claude e1b4a207c5 ui: stream cards show the streamer's avatar on a painted scene
TeamSpeak streams carry no thumbnail, and a peek would be a join request
the streamer sees, so a stream card not being watched now shows the
streamer: their avatar, ringed, with what they share, on the art scene
tinted with their colour (Art moves from home.slint to components). The
compact rows and the phone's Activity cards show the avatar too, and our
own stream from the Stream Studio shows the studio's picture while live.
StreamItem gets avatar, initials, tint and studio; the kind label is the
pure vm::streams::kind_label, used by Home as well.

In the demo, the studio going live announces our stream, and studio:live
starts the studio itself, so studio:live,server,voice shows the card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 07:21:20 +00:00
Claude 26c7d9c97c ui: a call bar on the voice page, and a smaller stage for the chat
The desktop voice view gets mute, deafen, share, the voice settings and
Leave under the people and streams (VoiceButtons gains round and filled);
Voice Settings and Leave leave the header, which gets a Smaller stage /
Larger stage button. The smaller stage, one row of compact people and the
streams as rows, gives the chat about 200 px back and is stored as
ui.voice_compact. Windows under 800 px tall always use it: the larger
stage and the bar left no room for the chat or the composer there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 04:57:53 +00:00
Claude 923f119ff6 ui: one Participant and StreamCard for desktop and phone voice
Participant and StreamCard move into screens/voice-parts.slint with a
`compact` look that replaces the phone's VoiceMember and StreamPrompt, so
the compact stage and the phone's voice screen can share them. The phone's
VoiceControl goes: IconButton and ActionButton get `alarm`, the filled red
Leave, and `edge`; ActionButton also gets `icon-size` and `checkable`.

The screenshots are unchanged. The phone's voice-bar buttons now behave
like the You page's: hover, keyboard focus, surface-4 while pressed, and
an accent caption while Sharing.

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 02:14:08 +00:00
Claude 48bc99a594 ui: private chats on the Direct Messages page, not in the chat tabs
The server's chat strip shows the server chat and the channel chats.
Private chats stay tabs of their session, so history, the composer and
previews keep working, but the strip leaves them out (vm::chat::strip)
and a private chat is current only while the Direct Messages page shows
it; leaving the page goes back to the strip's last chat. The rail and the
Chats tab count only the server's and channels' unread messages; private
ones count on Direct Messages and, on the phone, on the Home tab.

Closing a tab left of the selected one no longer selects the next chat.
Voice connecting while a private chat is open keeps that conversation
(it became the voice channel's chat, and the composer sent there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-08 00:57:26 +00:00
Claude 2e3ddc11ec ui: pins and topics as icon buttons with a count in the chat header
The labelled Pinned Messages and Topics buttons took about 300 px of the
header, so the channel's topic was cut first. They are icon buttons now,
named in their tooltip, with how many pins and topics the chat has
(Bridge.pins-count and topics-count, -1 until the gateway answered).

The counts are asked for when a chat comes on screen (a tab, a server, a
gateway that connects, another server after a delete), not only when a
drawer opens, so they show before. An answer for a chat that was closed
meanwhile is dropped, instead of reopening it as a tab named Server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 22:03:43 +00:00
Claude 14ea206521 ui: a colour per server, one letter in small avatars, one channel icon
Servers took their colour from a palette of people's colours by a hash
of the name, so two of the three sample servers were the same blue.
vm::servers::tints gives each server, in the rail's order, a colour
from ten hues around the wheel: its name's, or the next free one when
an earlier server has it. The rail, Home, search, live rooms and the
server chats in the chat lists use it. A server icon at most half as
wide as its avatar (TeamSpeak's 16 px ones) is drawn at twice its size,
sharp, on that colour instead of stretched.

Avatars under 28 px show one letter (Images.first-letter, as Slint
cannot cut a string). Channels show the speaker (Icons.channel)
everywhere the hash or the volume icon stood for one, and tab titles,
notifications and subtitles name them without a '#' (vm::chat::tab_title;
private chats keep '@').

Member rows showed everyone's talk power as a bare number. They now show
a muted hand, "Needs talk power to speak", only on those whose channel
needs more than they have and who are no talker (vm::tree::cannot_talk);
the member card keeps the number. The sample's Raid Night needs 50.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 20:06:16 +00:00
Claude 65ff5f6693 ui: TeamSpeak links open the server dialog, or move you in voice
Links to ts3server://, teamspeak:// and tmspk.gg in chat were only
copied. voelin_model::Link reads them, and invite_link now writes
through ServerLink::to_url, so a copied invite reads back the same (a
'/' in a channel's name stays %2F in the link, \/ in the path).
App::open_link (links.rs) finds the saved server with that address
(vm::servers::same_address; of several, the one in voice, else the one
shown: link_server). In voice on it, it moves into the link's
channel (channel_by_path) through join_channel, so a locked channel
asks for its password when the link's is missing or wrong. Otherwise
the server dialog opens filled in by link_form, over the saved
server's form when there is one: its nickname stays. Nothing connects
before Connect. Invite codes need a TeamSpeak service; a toast says
so. VOELIN_OPEN=link:<url> goes through inbox::Request::OpenLink,
where the platform's links will come in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 17:50:04 +00:00
Claude 7965187d2c ui: home continues where you left off, with unread mentions
The banner carousel repeated the servers below it, and the quick actions,
the friends and the sidebar art appeared twice. Home now shows the banner
only before the first server; after it a card with the last voice channel
(`ui.last_voice`, Join or Open) and up to three unread mentions. Friends
show once, and the sidebar lists the five newest private chats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 15:40:34 +00:00
Claude a3b61bca70 ui: a slimmer top bar, and the bell's panel under the bell
The top bar repeated what the rail and the pages show: the logo and the
app name, the page's name, a members button that only worked on the
server page, and About. It now holds the search, starting over the main
panel, and the bell, in 44 px (taller only when large text makes its
controls taller). The members button moved into the voice channel's
header, as the chat's header has one; About stays in Settings and on the
phone. The Stream Studio already names itself in its preview's header.

The bell's panel opens under the bell instead of 100 px to its left, and
is as tall as its notices up to 560 px: a ScrollView of all the rows (at
most 100) replaces the ListView that stretched to the full height. A
notice is never shorter than its text, so a long list scrolls instead of
squeezing the rows.

The user card loses its settings gear, which the rail has too
(VoiceButtons gets `gear` for the call bar to come); its avatar and name
are a button to Settings > My Account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 13:27:41 +00:00
Claude 95d86af627 ui: one dialog to add a server, with Save and Connect
Join a Server and Add a Server were the same dialog with other buttons,
and Join saved the server in Slint and then connected the one shown: when
saving failed, that was the server shown before. The dialog now has
Cancel, Save and Connect (also Enter in the address or password field).
Connect goes through Bridge.save-and-connect, which connects only the
server it saved (vm::servers::connect_to); it is hidden while the server
has voice, and Save is the main button then. On a phone Delete shows only
its icon, so the four buttons fit.

BookmarkForm carries a channel, its password and a privilege key for the
links to come: the dialog shows "Joins <channel>" and "This link grants a
server group", Connect connects into that channel, and connect_voice_to
passes the key on. Nav.join-server is gone; the dev switch join opens the
same dialog as bookmark. "Add server" reads "Add a server" everywhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 11:12:37 +00:00
Claude 4940966538 ui: a New line above the first unread message, and read markers kept on disk
Messages count as read only while their chat is on screen (Nav.chat-shown)
in the focused window: winit's focus events, through slint's
unstable-winit-030 on the desktop; Android counts a chat on screen as
read. A tab keeps the newest message read and counts what came after it,
not our own. Entering a tab with new messages puts a red New line above
the first one until the tab is left (so does a stored or gateway page
that brings them while the tab is on screen), and while that line is
above the view a bar over the list counts them, with Jump and Mark as
read.

voelin-store migration 5 adds chat_reads (Store::chat_read, set_chat_read,
chat_reads). Markers are loaded once a session's server is known and
written when a tab is left, marked read, its session ends and on exit,
never per message; a restart counts what came while away again, gateway
pages included. Dev switch VOELIN_OPEN=unread[:end].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 09:01:15 +00:00
Claude 2f3c2433b4 ui: older messages load when scrolling up, the rows on screen staying put
Scrolling to within a screen of the top asks for the page before; the
list keeps the rows from the top of the view to the end and goes back to
them once the page is in (rows, as the list places them by an average
height, then up to two corrections by their real heights). After a page
that brought nothing it waits until the list was a screen away. The
Older messages button moves to the top of the list, above the oldest
message (a spinner while loading), for a chat too short to scroll. A
short chat after a longer one no longer starts with its first rows above
the view, and another server's chat at the same tab starts at its end
too (it kept the last chat's place, and now its loading state). Demo
mode answers with two sample pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 06:27:38 +00:00
Claude 1435d9c909 ui: links open, and Copy text and Quote on every message
Links in chat did nothing. classify_link (vm/bbcode.rs) sorts an address
into a web page, a TeamSpeak server, a channel file or no link, and only
those reach TextRun.link. A click on a web link opens it through
App::open_url, the one place a platform without xdg-open can hook; one
whose text is not its address first shows where it goes (LinkDialog).
TeamSpeak links are copied until Voelin opens them. A right-click on a
link opens or copies it.

The hover bar was there only for messages a gateway knows. Every message
now has it, with Quote ("> Author: …" lines at the start of the
composer; TeamSpeak clients show [quote] as it is) and Copy text, and a
right-click menu. After Quote the composer has the focus, its cursor
below the quote, and grows to show the quote's lines: its field is one
line high, so an answer typed after clicking into it went into the
quote's last line. The bar keeps itself shown while the pointer is on
it or on the message's links and reactions: it reaches above its row,
where the row's hover ended, so its buttons could not be clicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 03:47:03 +00:00
Claude 531334d826 ui: BBCode in chat, and the welcome message as the server chat's first line
Other clients format chat with BBCode, and it showed as raw tags; only
file links were taken out. One parser, vm/bbcode.rs, now reads every
message into a Doc of blocks (lines, quotes, code, list items, rules) of
styled spans, which the chat draws with one MessageText (also in the
pins drawer and the studio's chat), and which previews, notifications
and the home's news show on one line. Only known tags are read, so
relay prefixes such as [Nova] stay. Emoji are split per span, so a
message with emoji keeps its line breaks. [img] pictures on the web
come through the engine's picture cache (Command::FetchPicture), within
ui.image_preview_kb and only with cache.fetch_images; otherwise they
stay links. Built lines are kept per message and revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-07 00:56:14 +00:00
Claude 9e0f0e05ad ui: other people's badges, named on the member card and drawn after their name
Clients only send badge GUIDs. voelin-model names them from tsclientlib's
table plus the newer entries of TeamSpeak's own list, and the engine fetches
the first three pictures of each client from TeamSpeak's badge server
(<guid>/<filename>.svg, checked to answer) with the banners, under
cache.fetch_images.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 20:16:37 +00:00
Claude 68dd48d607 voelin-audio: dim everyone else while a priority speaker talks
The server sends virtualserver_priority_speaker_dimm_modificator (-18 dB
by default) but nothing read it. ServerDetails carries it now, the
session tells the audio thread the priority speakers when they or the
value change, and the mixer dims every other queue (watched streams too)
while an unmuted priority speaker has one, fading sample by sample over
5 frames.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 18:59:23 +00:00
Claude 79a12654c8 myTS avatar, badges and User Tag from a saved session; banners; gateway logs and speed
Own account on TeamSpeak 6 servers:
- With only a saved session, the account's avatar and its certificate come
  from myTeamSpeak's avatar service (requestContactsAvatar for the own myTS
  ID), the signed badges from getSignedBadges and the User Tag's token from
  /tschat requestSignedAllowedIdentifierList; no password sign-in needed.
- tsproto::myts::Certificate checks a certificate chain as the server does
  (block types 4-7, leaf type 6, validity, key from the root, cofactorless
  Ed25519); each part is sent with a certificate that verifies it, in
  separate updatemytsdata commands when they differ, and cleared on sign-out.
- client_user_tag is set as the official client sets it
  ({"myts_token","tag","updated"}) on TeamSpeak 6 servers, after a
  self-check of the token; cleared on sign-out or an account change.
- Settings -> My Account shows the User Tag and lets the user choose up to
  three badges to show. The log says what the server published.

Banners:
- The URL (without query) is logged on the first failure; stalls, connect
  failures and missing answers are named; 400/404/410 are retried after
  15 minutes, then hourly; 429/503 honour Retry-After.
- Cached pictures are revalidated (ETag, Last-Modified); at most 6
  downloads per host; a User-Agent with the app version.
- The desktop portal's proxy (Linux) and the system proxy (Windows, macOS)
  are used, SOCKS included; redirects are followed hop by hop.

Gateway, client side:
- Only a refused login stops observing; retries after 1, 2, 5, 10, 20, then
  30 s with jitter, at once when voice connects; a 30 s keepalive.
- Discovery asks DNS and the well-known endpoints at once; observing is not
  restarted when the found list still holds the gateway in use.
- Info logs for discovery, attempts (with the stage that hung), connections,
  losses and the first presence.

tsgw:
- Logging setup (log.level, log.file with size rotation, colour only on a
  terminal) and lifecycle logs: startup summary, the address the server
  sees for queries, WebSocket connections, logins, refusals, slow requests,
  ServerQuery failures, relays and the observer.
- The lookup query connection reconnects after a TeamSpeak restart; query
  connects time out after 10 s; a silent server cannot wedge a connection;
  SIGTERM, startup while TeamSpeak is down and /health are handled.
- TCP_QUICKACK and one write per line: ~45 ms -> <2 ms per SSH command.
- One flood guard shared by all query connections (9 per 3 s, SSH auth
  counted, every connection holds on a 524).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-06 18:28:09 +00:00
Claude 42639fd206 ui: a password dialog for locked channels, and pokes with a message
Joining a locked channel sent no password, so the server refused it and
nothing said so; pokes always went out empty. Every join (a double-click
in the tree, joining a friend) now goes through App::join_channel: a
locked channel asks for its password first (join_password), which is
kept for the session until voice disconnects, and it is used when
connecting into the channel too. Event::JoinFailed asks again under
"Wrong password", or says the channel is full or why the server refused.
Without voice, a double-click connects into the channel, as joining a
friend did.

Connecting into a channel names it by id (`/<cid>`): by name the server
finds only a top-level channel, so a subchannel's name connected into
the default channel. A wrong password when connecting also puts us into
the default channel without a word, so the channel is joined again once
it shows in the presence (after_connect), and that move asks again.
Both seen on the dev TS3 and TS6 servers.

Poking opens a dialog with an optional message, its length counted up
to 100 characters; the UI trims and cuts it (poke_message), and the
engine cuts it on characters too. Both dev servers take 100 characters
of any width (400 bytes of emoji) and refuse 101 (seen through
ServerQuery). Dev switches channel-password[:wrong] and poke.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 17:46:43 +00:00
Claude 7e43178e04 ui: every kind of spacer channel, and its text wherever a channel is named
Only [cspacerN] was recognized, so [spacer], [rspacer] and [*spacer]---
rows showed their raw names, and so did chat tabs, search results,
notifications and the other screens that name a channel. parse_spacer
(in voelin-model, so the Android voice notification uses it too) reads
them all, with any suffix (it only keeps names unique); a line repeats
its text across the row and is cut at its end. The tree search, Ctrl+K
and the event form leave out lines and empty spacers. Names that go to
the server (the invite link, joining a friend's channel) stay raw; the
toast after copying an invite shows the text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 13:27:12 +00:00
Claude e441156ee6 voelin-core: channel moves report why they fail; password and token on connect
A move went out without asking for an answer, so a wrong password or a
full channel came back as nothing. It is sent with a return code now,
and a refusal comes as Event::JoinFailed: Password, Full, or a sentence
for anything else. Moving to the channel we are in says nothing. The UI
does not show it yet; the channel password dialog will.

VoiceOptions gets channel_password and token, for joining a channel
when connecting and for links with a privilege key; tsclientlib's
ConnectOptions gets default_token for the latter (UPSTREAM.md patch 15).
Live tests on both dev servers check the password and the key on
connect, and the refused moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 10:25:41 +00:00
Claude 61636b23c8 ui: one clipboard path, and Copy invite link in the voice header
Copying went through a hidden text field on the phone's voice screen
only. It moves into MainWindow: any screen calls Nav.copy(text), and
Bridge.copied() confirms it in one toast, shown again when its text is
the same as the last copy's. The invite leaves its own message for that
toast (the channel and the link) instead of a status of its own, so a
copy never shows two. The desktop voice channel view gets the same
Invite as a Copy invite link button next to Chat only.

Icons.channel is the speaker, for the channel spots that use it later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 08:44:29 +00:00
Claude 3c47bc682f ui: a clearer edge on pop-ups, and a light scrim behind them
Pop-ups, menus and tooltips had the border-strong edge, which barely
shows against the panels under them. They get a new border-popup token;
the Select and Stream Studio drop-downs too, being the same kind of menu.
The member card, the emoji picker and the bell's panel now dim the
window behind them with a new scrim-light, lighter than the modals'
scrim; a click on it still closes them. The toast moves above them, so
that scrim does not dim it (a poke from the member card is confirmed
there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 07:34:00 +00:00
Claude cdedb86b9c ui: tooltips on icon buttons, and a count
IconButton names itself in a tooltip after a moment of hover, also while
it is disabled (mute or deafen when not connected), and can show a
neutral count at its top right (for pins and topics later). Tooltips are
desktop only: the new Bridge.desktop is false in the Android app.

Tooltip showed once (its Timer turned off its own binding) and stayed
open after the pointer left. Both now use Slint's Tooltip element with
our TooltipBubble: it opens at the pointer, closes when the pointer
leaves, and lets clicks and hover through, which a PopupWindow of our own
does not while it is open. A press closes it until the pointer leaves.
The bubble sets its own preferred width, up to 400px, so long text wraps:
the tooltip's popup takes that width, and a max-width would not narrow it.

IconButton's look moves onto an inner rectangle: with an opacity and an
animation on its root, Slint inlined it at each of its 100-odd uses, and
the tooltip and count alone added 3.3 MB of generated code to a crate
whose compile already peaks near 14 GB. Now the generated code is 1.1 MB
smaller than before (70.7 MB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-06 04:57:51 +00:00
Claude 1c2d5efd3a changelog: myTeamSpeak avatars both ways, gateway fallback, banners
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 23:10:41 +00:00
Claude 47f5e2d9aa review: fix what the review of the gateway, avatar and banner changes found
- voelinctl observes with the new gateway list and checks avatar hashes
  only when they are MD5s (a myTeamSpeak avatar's hash is its link).
- Gateway discovery keeps to the most specific name that publishes a
  record; another server's gateway is no fallback. The admin guide says so.
- The observer's resync keeps the avatars clientlist does not tell
  (they come with the enter and update notifications).
- A server avatar given up on counts for that picture only: a new one is
  tried again, and one that arrives after all is shown again.
- updatemytsdata goes again after tsclientlib reconnects (the server
  forgets it), and once, not twice, when signing in.
- SVG is told by its prolog: a page with an svg in it (HTML, XHTML) is a
  page, refused and logged as one; the UI tells it the same way.
- Cursors (CUR) are no longer taken for pictures; MP4 and MOV are named
  videos, not AVIF.
- The UI decodes at most 128 MiB of pixels on its thread, drops the full
  picture before copying the small one, logs what it cannot decode, and
  remembers pictures it cannot show instead of decoding them on every
  refresh; a banner that reloads unchanged is not decoded again.
- The early refusal of a long error page is tested again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 23:09:34 +00:00
Claude 07038c58c3 images: the decoded-image budget's test follows the new default (256 MB)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 22:36:29 +00:00
Claude db94e21e27 banners: tell why one is missing, accept more, bigger defaults
Failures are in the log with the host and the reason, never the whole
address: HTTP status, the whole chain of causes (TLS, DNS, timeouts), what
came instead of a picture (an HTML page, AVIF); banner addresses that
cannot be fetched at all once; avatars and icons in the server's files
when they give up (a closed file transfer port shows here).

More is shown: BMP and ICO, SVG after a comment or a DOCTYPE, addresses
with blanks around them; pictures larger than 4096 px are scaled down
instead of refused (only above 512 MiB of pixels). Banners keep being
tried while shown (after 1, 4, 16, 60, 300, 900 s, then every 15 min).

Defaults: connect 20 s, read 60 s, slow start 120 s, 16 downloads at
once, 20 redirects, pictures up to 128 MiB at 8 KiB/s at least, file
transfer negotiation 30 s and a minute plus size, cache.max_mb 1024,
ui.image_cache_mb 256.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 22:05:12 +00:00
Claude 259a23a165 account: show servers the account's avatar
As the official TeamSpeak 6 client does once connected and after a
sign-in, Voelin sends updatemytsdata with the account's certificate and
its avatar (LoginSession.mytsid_user_cert.cert and user_avatar, raw bytes
with TeamSpeak's escaping only; \a and \b now escaped too). The avatar
is sliced out of the login response as it came: its signature covers it.

Both come from a password sign-in; they are kept per account next to the
avatar picture (public data, outside the keyring) and published to every
voice connection that presents the account (Command::SetMytsData, beside
the identity). A refusal is only logged. Accounts signed in before need
one password sign-in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 22:00:34 +00:00
Claude c2e345c67f avatars: show other clients' myTeamSpeak avatars
TeamSpeak 6 tells a client's myTeamSpeak avatar as
client_myteamspeak_avatar "<state>,<url>;...". The book now keeps it,
and the model reads it as the official client does (one bad entry, an
empty one too, spoils the value; the online picture first, else away, do
not disturb, offline; HTTPS links only).

The engine downloads it from the web (4 MiB at most, cached by link)
where the server's avatar is not shown: the client has none, there is no
voice connection to get it over (observing), or its download gave up
(the server's files unreachable). The server's avatar comes first, as in
the official client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 21:53:38 +00:00
Claude f9243d3cad gateway: try every published gateway in turn
Discovery returns every gateway the server publishes, best first: the
most specific name, at a name _tsgws before _tsgw, by priority, then
tsgw's own /.well-known answer (only when a plain record or nothing is
published, so a TLS-only server is never reached without TLS). The
engine tries them in turn, each for up to 20 s, and uses the first that
logs in; only a round that fails waits before the next. The bookmark
keeps the published list and the one in use.

A TLS proxy that answers 404 (Zoraxy without a rule for the host) no
longer keeps the gateway away when tsgw's plain port is published too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 21:48:47 +00:00
Claude d114444c04 docs: UI review, and what to take from TeamSpeak 6 and Discord
A review of the desktop and phone UI (from the code and the screenshots),
the classic and TS6 client features Voelin lacks, the Discord ideas that
fit a TeamSpeak client (client-only, gateway or existing TS features), and
an order of work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVRENKftQqGoEeswiR9TDQ
2026-10-05 20:51:06 +00:00
faumaray 656bc5f6dd Merge pull request #9 from Faumaray/claude/great-allen-rw6re7
Login page, myTeamSpeak profile, stream fps, invisible gateway, relay as author, TS6 version, packaging, logs
2026-10-05 23:35:28 +03:00
Claude 266148d9cd gateway: invisible to users, and tried again when away
Users never hear of the gateway:
- relayed messages look like everyone else's (no "via relay", no accent
  colour) and group with the author's other messages;
- a gateway that cannot be reached or drops is tried again by itself
  (after 2, 5, 15, 30, then every 60 s) with the open chats opened again
  and messages written meanwhile sent, instead of a WebSocket error
  ("connection refused") on screen; it is logged with its URL, once per
  cause;
- a server whose gateway is away is offline, not connecting, so it can
  always be joined;
- failed requests the app made by itself are quiet; what the user did and
  failed is told in plain words; query relay errors are logged;
- no status line about a found gateway; events and streams texts do not
  mention it.

The gateway is looked up once per run even when one is stored: what the
server publishes takes the place of a stored URL (one that moved, or one
typed into an older version that showed the field, which cannot be
edited any more).

The admin guide says a _tsgws record must point at TLS, not at tsgw's own
plain port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 20:09:59 +00:00
Claude f8dcfaf0f5 logs: leave out zbus's warnings about portal requests
zbus warns when a desktop portal's request or session object is gone
before it reads the object's properties, at every start; harmless. Its
errors stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 20:09:59 +00:00
Claude 019f5be81c account: download the avatar from its own link
The official TS6 client fetches the avatar map's names as they are
(MyTeamSpeak::Account::request_own_myts_avatar hands each name to
Avatar_Cache::request_avatar_from_urls, which GETs it without headers).
requestAvatarSignedUrl signs upload links: its reply only goes to
upload_avatar, an Http_Client::put. Voelin fetched such a link with a GET
and was refused with HTTP 403.

A refused download is now its own error ("avatar download returned HTTP
..."), apart from the account service's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-05 20:09:59 +00:00
Claude 7cd258d9a5 settings: log_text before the test module (clippy)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 23:18:32 +00:00
Claude c212e07665 notices: regenerate (dav1d now in every build; ring gone since aws-lc-rs)
The notices were already stale on main: ring left the dependency graph when
schema-api moved tonic to aws-lc-rs. dav1d, dav1d-sys and av-data come in
with the av1 feature. Also drops an unused helper of the gateway's fake
server (clippy).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:59:42 +00:00
Claude 0b9164cc4c ui: login artwork covers its panel; no empty rows; one-line dialog subtitle
The login page's artwork is the tall night landscape of the home sidebar,
covering the panel from the bottom, under a single smooth fade. Notices
and session actions only take room when they have something to show.
The server dialog keeps its one-line subtitle, so Advanced is not cut off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:43:45 +00:00
Claude 69fbc374b9 voelin-media: the decoder order test with dav1d built in
AV1 comes first in the viewer's order, so with the av1 feature on by
default the first decoders are not VP9 and VP8 any more; the test checks
their order among themselves and what leads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:19:48 +00:00
Claude aa12c653f1 changelog: the unreleased changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:12:17 +00:00
Claude ac187fe39e packages: every codec backend, and the libraries the app needs
voelin-media builds dav1d (AV1 decoding) by default, like every other
codec backend: Linux images already had libdav1d-dev; Windows CI takes it
from vcpkg next to libvpx and the MinGW image builds it static (dav1d
1.5.4, pinned commit; checked to cross-compile).

Windows packages ship FFmpeg's LGPL DLLs (BtbN's 8.1 shared build,
checked against the release's checksums by scripts/fetch-ffmpeg-windows.sh)
next to voelin.exe, where the app looks first, with their license and a
note on the build and its source; the installer installs and removes them.

The Linux .tar.gz carries libvpx and libdav1d in lib/ (RUNPATH
$ORIGIN/../lib, set with patchelf), whose sonames differ between
distributions, and bin/voelin-install-deps, which installs FFmpeg, VA-API
drivers, PipeWire, the desktop portal and a keyring with apt, dnf, pacman
or zypper. The .deb recommends those packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:12:17 +00:00
Claude eafa67cfe9 streams: decode VP8 on one thread, convert pictures off the decoder
Watching was slow because FFmpeg's VP8 decoder ran on slice threads: they
split frames by token partitions, and our 4- and 8-partition streams (from
senders with 6 cores or more) took 18-21 ms per 1440p picture against 10 on
one thread, so the decoder fell behind, dropped its queue and waited for
keyframes (35-49 of 60 fps shown). VP8 now decodes on one thread.

The decode thread also converted every picture to RGBA into a new zeroed
buffer (3.6 ms at 1080p, 5.1 at 1440p). It now hands its newest frame to a
converter thread, which converts only what the window can show into
buffers reused three pictures later (0.8 and 1.0 ms).

libvpx's decoder spins its threads (4 threads: 23 and 11 fps on those
streams with a core busy, 2: 143 and 129): at most 2. dav1d with a frame
delay of one gets a quarter of the cores, 1 to 4.

docs/research/stream-fps.md has the measurements and what is left (the
sender's encode rate and bitrate, H.264 frame threads, texture uploads).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:12:07 +00:00
Claude a88d267937 logs: write a log file per run, keep the previous four
voelin-platform::logs writes <state>/voelin/logs/voelin.log (the previous
runs as voelin.1.log ... voelin.4.log; a run past 20 MiB starts a fresh
file). The desktop app logs our crates' information there (VOELIN_LOG
overrides the filter) and warnings to the terminal as before; release
builds on Windows have no terminal. Settings -> Advanced names the file
and opens its folder; crash reports keep their own Open button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:12:07 +00:00
Claude 7433b5a568 account: new login page, kept away while signed in; profile and avatar
The login page no longer opens when a session is saved: the session is
checked in the background and only an expired one brings the page back.
Continue without an account is remembered (ui.skip_account_prompt) until
the next sign-in.

The page is redesigned: the night artwork with what an account gives
beside the form on wide windows, the form alone on narrow ones; email,
password with a show button, the one-time code when asked, notices as
banners. Settings -> My Account shows the profile instead of a list of
notes.

voelin-myts asks the user service (/user, the route of the official
client) for getAccountData (description, registration, previous sign-in,
badges, devices, avatar file names) and requestAvatarSignedUrl, then
fetches the avatar (HTTPS only, at most 4 MiB). The UI keeps the profile
in the session's keyring bundle and the picture in <data>/account/avatar,
fetches it again only when its name changes, and uses it as the sidebar's
profile picture where a server has none for us.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 22:12:07 +00:00
Claude 219e554efe versions: claim the newest signed TeamSpeak 6 build; 122 more rows
Versions.csv gains the 121 verified rows of upstream tsdeclarations it was
missing (TeamSpeak 5 betas, 3.6.x) and 6.0.0-beta4.1 [Build: 1779880475]
for Linux, captured from the official Linux client's clientinit. Every row
verifies against TeamSpeak's version-signing key. They are appended, so
the generated Version variants and the indexes keep their names.

native_version() now claims the newest 6.x build signed for the native
platform (Linux 6.0.0-beta4.1, Windows 6.0.0-beta2), so the client shows
as a TeamSpeak 6 client instead of 3.?.?; platforms without one (macOS,
Android, iOS) keep the generic tuple. --client-version generic (and a
bookmark's client_version) claims the old tuple.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 21:26:15 +00:00
Claude 60b8e95661 ui: servers observe on selection; no gateway or query fields
Selecting a server (or saving one) observes it invisibly through its
gateway, else a query login an older version stored; without a gateway it
is looked up from the address (SRV, then /.well-known/tsgw) and observing
starts once found. The Observe button and the menu entry are gone.

The add/edit server dialog no longer asks for a gateway URL or ServerQuery
login: Advanced keeps the name and nickname. A new address drops the
gateway and query login of the old server, so they are looked up again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 21:10:59 +00:00
Claude 4d04c992a3 relay: post under the author's own nickname
A relay (and the gateway's lookup session, for server chat) takes the
author's nickname for each post, sends the text as written and takes its
own name back, so messages read as written by the user in TeamSpeak.
While someone has the nickname it uses Nick1 to Nick3, as TeamSpeak names
a second client of the same name; relay.format ([Nick] text) is only the
fallback when it can take none of them. Posts through one session are
serialized, since each borrows a nickname.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 21:00:38 +00:00
Claude a69b465886 release: build packages with Cargo's default job count
The release workflows (GitHub and Gitea), the Docker images they build in
and the Flatpak manifest no longer set CARGO_BUILD_JOBS=1 and
CARGO_INCREMENTAL=0. CI checks keep the serial build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
2026-10-04 20:51:52 +00:00
198 changed files with 21914 additions and 5741 deletions

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
---
name: mao-designer
description: Produces designs and acceptance criteria for a task, and handles escalations from mao-implementer after 3 failed attempts. Use before delegating non-trivial work and whenever an implementation is stuck.
model: opus
effort: max
---
You are **mao-designer**, the design and escalation role of the Voelin
multi-agent workflow. You do not implement features yourself unless the
orchestrator asks for a spike; you produce the artefacts others build from.
## Your job
1. **Design.** For the task you are given, read the relevant code first,
then deliver: the approach (what changes, where, why this way), the
module/type/function names to create or change, the data flow, the
failure modes, and the **acceptance criteria**: the exact checks that must
pass (`cargo fmt --check`, `cargo clippy -D warnings` for the touched
crates, named tests, integration or smoke scenarios, manual checks) and
the behaviour that must hold. Name the files to touch and the files that
must not change.
2. **Escalations.** When `mao-implementer` reports 3 failed attempts, read
the evidence (what was tried, failing output, diff). Diagnose the root
cause and give a corrected design or a narrowed task. Each correction you
issue is one *design attempt*. After **3 unsuccessful design/correction
attempts of your own**, stop and escalate to the main orchestrator with
the evidence and a recommendation (change approach, narrow scope, or ask
the user).
## Rules
- You perform this role; you do not delegate it or spawn further
orchestration. Project hosting is Gitea (`https://git.faumaray.com`) via the
Gitea MCP connector, never GitHub.
- Separate observations (what the code does, cited as `path:line`),
inferences, and open questions.
- Keep designs small enough to implement in one attempt where possible; split
otherwise and say in which order.
- Communication: use `SendMessage` to reach `mao-implementer` or the
orchestrator when it is available; otherwise put everything in your report.
Use `ListAgents` only if it is actually exposed.
## Report format
**Result** (design ready / corrected design / escalated), **Design** (approach,
files, names, data flow), **Acceptance criteria** (checks + behaviour),
**Risks and open questions**, **Attempt count** (design attempts used on this
task), **Unavailable tools or agents** and the fallback used.
+38
View File
@@ -0,0 +1,38 @@
---
name: mao-helper
description: Fast helper for focused file searches, short summaries of files or logs, and routine git operations the user has authorized (status, log, diff, fetch, branch listing, staging, straightforward commits when told to). Use for small, well-defined chores so larger agents keep their context.
model: haiku
effort: medium
---
You are **mao-helper**, the utility role of the Voelin multi-agent workflow.
You do small, well-defined chores quickly and report precisely.
## What you do
- **Searches:** find files, symbols, call sites, config keys; return
`path:line` tables, not prose, and say what you searched (patterns,
directories) so negative results are bounded.
- **Summaries:** condense a file, a log, a diff or a test output into the
facts the caller asked for; quote exact error text; never invent detail.
- **Routine git:** `status`, `log`, `diff`, `fetch`, branch and tag listing,
staging, and commits or pushes **only when the task explicitly authorizes
them**, with the attribution trailer the session prescribes. Never force
push, rewrite history, delete branches or change remotes unless the task
says so verbatim. Hosting is Gitea (`https://git.faumaray.com`); repository
operations beyond plain git go through the Gitea MCP connector, never
`gh` or GitHub.
## Rules
- Stay within the task; do not fix code or redesign. If a chore turns out to
need judgement, stop and report what you found.
- You perform this role; you do not delegate it.
- Use `SendMessage` to answer the agent that asked when it is available;
otherwise report to the orchestrator.
## Report format
**Result**, **Findings or changed files**, **Commands actually run** (with
outcome), **Unresolved issues**, **Attempt count** (normally 1),
**Unavailable tools** and the fallback.
+50
View File
@@ -0,0 +1,50 @@
---
name: mao-implementer
description: Implements a designed task, runs the relevant checks, self-reviews, and reports; escalates to mao-designer after 3 unsuccessful attempts. Use for all code changes once objective, scope, acceptance criteria and files are defined.
model: sonnet
effort: xhigh
---
You are **mao-implementer**, the implementation role of the Voelin
multi-agent workflow. You receive an objective, a scope, acceptance criteria,
the relevant files and the expected report. If any of these is missing, ask
the orchestrator (or `mao-designer`) before writing code.
## How you work
1. Read the design and the files in scope. Reuse existing utilities and
patterns in the repository; do not add new abstractions the design did
not ask for.
2. Implement within scope only. Do not touch files assigned to another agent.
3. **Run the checks** named in the acceptance criteria, at least: `cargo fmt
--check`, `cargo clippy -D warnings` for the crates you touched (the
crates this repository owns; its CLAUDE.md says how to list them), and the tests of every
crate you touched. Run the integration or smoke scenarios the task names.
4. **Self-review** the diff as a reviewer would: correctness, error paths,
concurrency, unchanged public behaviour, docs/comments that now lie.
5. Report.
## Attempts and escalation
- An *attempt* is a complete proposed solution checked against the
acceptance criteria. Tool calls, compiles and test runs inside one attempt
do not count separately.
- Keep an explicit attempt counter for the task. After **3 unsuccessful
attempts**, stop. Do not try a fourth variation. Escalate to
`mao-designer` (via `SendMessage` when available, otherwise through your
report to the orchestrator) with the evidence: what each attempt changed,
the failing check output verbatim, and the current diff.
## Rules
- Hosting is Gitea (`https://git.faumaray.com`) through the Gitea MCP
connector; never use `gh` or GitHub. Commit only when the task says so,
with the attribution trailer the session prescribes.
- You perform this role; you do not delegate it or orchestrate others.
- Never claim a check passed that you did not run; paste the relevant output.
## Report format
**Result** (done / partially done / escalated), **Changed files** (paths),
**Checks actually run** (command + outcome, failures verbatim), **Unresolved
issues**, **Attempt count**, **Unavailable tools or agents** and the fallback.
+45
View File
@@ -0,0 +1,45 @@
---
name: mao-opus-reviewer
description: Final, fresh and independent review of substantive code changes for correctness, architecture and unresolved risks. Reports concrete defects; does not fix code. Use after the sonnet review, in a new agent, never in the design agent's conversation.
model: opus
effort: max
tools: Read, Grep, Glob, Bash
---
You are **mao-opus-reviewer**, the final independent reviewer of the Voelin
multi-agent workflow. You review; you do not design, implement or edit. You
start with no shared context on purpose: form your own model of the change
from the code.
## How you review
1. Establish what the change is supposed to do (task, acceptance criteria)
and what it actually does (diff plus the code it touches and the callers
it affects). Trace at least one end-to-end path through the change.
2. Judge **correctness** (logic, invariants, error and edge paths,
concurrency and ordering, resource lifetimes, protocol/wire compatibility,
data migration), **architecture** (does it fit the crate boundaries and
the project's direction: client speaks only the Voelin protocol, TS types
stay in the gateway, no Slint/Android in client crates; duplicated logic;
leaky abstractions; dependencies that should not exist), and **unresolved
risks** (untested paths, performance on the hot audio/video paths,
security, licensing, operational impact).
3. Re-run the decisive checks yourself when feasible rather than trusting
earlier reports.
4. Report concrete findings with `path:line`, the failure scenario and the
fix direction. Rank by severity. Say explicitly what you did **not**
verify.
## Rules
- Read-only on the code base; running checks is fine, editing is not.
- You perform this role; you do not delegate it or orchestrate.
- Use `SendMessage` to reach the orchestrator when available; otherwise
report.
## Report format
**Verdict** (ship / do not ship / ship with listed follow-ups), **Findings**
(severity, location, scenario, fix direction), **Architecture notes**,
**Unresolved risks**, **Checks actually run**, **Not verified**,
**Unavailable tools** and the fallback.
+41
View File
@@ -0,0 +1,41 @@
---
name: mao-sonnet-reviewer
description: Fresh, independent review of an implementation against its acceptance criteria. Reports concrete defects with file and line; does not fix code. Use after mao-implementer reports done.
model: sonnet
effort: xhigh
tools: Read, Grep, Glob, Bash
---
You are **mao-sonnet-reviewer**, the first independent reviewer of the
Voelin multi-agent workflow. You review; you do not edit, redesign or
implement. You start fresh: do not assume the implementer's report is
accurate; verify it.
## How you review
1. Read the task's objective, scope and acceptance criteria, then the diff
(`git diff`, or the files named) and the surrounding code it depends on.
2. Check, in this order: does it meet the acceptance criteria; correctness
(logic, error paths, concurrency, resource cleanup, unchanged public
behaviour); scope (nothing outside the task changed); tests (do the named
checks exist and cover the change; re-run them yourself when feasible);
clarity of names and comments; docs that must change with the code.
3. Report **concrete defects** only: `path:line`, what is wrong, why it
matters, how it fails (input/state -> wrong outcome), and the fix
direction in one sentence. No praise, no style nits that do not change
meaning.
## Rules
- Read-only on the code base. Running `cargo test`, `cargo clippy` or the
smoke scripts is encouraged; editing files is not your role.
- You perform this role; you do not delegate it.
- Address the implementer or orchestrator with `SendMessage` when it is
available; otherwise everything goes in the report.
## Report format
**Verdict** (accept / changes needed), **Defects** (ordered by severity, each
with location, failure scenario, fix direction), **Checks actually run**
(command + outcome), **Acceptance criteria status** (met / not met, per
criterion), **Unresolved risks**, **Unavailable tools** and the fallback.
+5
View File
@@ -0,0 +1,5 @@
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"model": "fable",
"effortLevel": "xhigh"
}
+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 -5
View File
@@ -9,8 +9,6 @@ on:
env:
CARGO_TERM_COLOR: always
CARGO_BUILD_JOBS: "1"
CARGO_INCREMENTAL: "0"
RUST_BACKTRACE: "0"
jobs:
@@ -74,8 +72,6 @@ jobs:
--build-arg "SIGNING_CACHE_BUST=$(basename "$signing")" \
--secret "id=keystore,src=$signing/release.jks" \
--secret "id=signing,src=$SIGNING_ENV"
- name: Flatpak bundle
run: scripts/flatpak-build.sh dist/flatpak
- name: Gateway container image
run: |
set -euo pipefail
@@ -88,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
+23 -6
View File
@@ -1,12 +1,13 @@
name: System dependencies
description: >
Native libraries and tools the workspace builds against: apt packages on
Linux; NASM and libvpx (vcpkg, cached) on Windows, exporting VPX_LIB_DIR,
VPX_INCLUDE_DIR, VPX_VERSION and VPX_STATIC for libvpx-native-sys.
Linux; NASM, libvpx and dav1d (vcpkg, cached) on Windows, exporting
VPX_LIB_DIR, VPX_INCLUDE_DIR, VPX_VERSION and VPX_STATIC for
libvpx-native-sys and SYSTEM_DEPS_DAV1D_* for dav1d-sys.
inputs:
vpx-triplet:
description: vcpkg triplet for libvpx on Windows (static library, dynamic CRT like Rust's default)
description: vcpkg triplet for libvpx and dav1d on Windows (static libraries, dynamic CRT like Rust's default)
default: x64-windows-static-md
runs:
@@ -47,8 +48,8 @@ runs:
uses: actions/cache@v4
with:
path: ${{ runner.temp }}\vcpkg-archives
key: vcpkg-libvpx-${{ inputs.vpx-triplet }}-${{ steps.vcpkg.outputs.commit }}
restore-keys: vcpkg-libvpx-${{ inputs.vpx-triplet }}-
key: vcpkg-libvpx-dav1d-${{ inputs.vpx-triplet }}-${{ steps.vcpkg.outputs.commit }}
restore-keys: vcpkg-libvpx-dav1d-${{ inputs.vpx-triplet }}-
- name: libvpx
if: runner.os == 'Windows'
@@ -60,7 +61,7 @@ runs:
$ErrorActionPreference = 'Stop'
$vcpkg = Join-Path $env:VCPKG_INSTALLATION_ROOT 'vcpkg.exe'
New-Item -ItemType Directory -Force (Join-Path $env:RUNNER_TEMP 'vcpkg-archives') | Out-Null
& $vcpkg install "libvpx:$env:TRIPLET"
& $vcpkg install "libvpx:$env:TRIPLET" "dav1d:$env:TRIPLET"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# "libvpx:x64-windows-static-md 1.15.2#1 The reference ..."
@@ -85,3 +86,19 @@ runs:
"VPX_VERSION=$version" >> $env:GITHUB_ENV
"VPX_STATIC=1" >> $env:GITHUB_ENV
Write-Host "libvpx $version from $libdir"
# dav1d-sys (AV1 decoding) through system-deps, without pkg-config:
# the static library, linked as dav1d.lib.
$davdir = Join-Path $root 'lib'
if (-not (Test-Path (Join-Path $davdir 'dav1d.lib'))) {
$lib = Get-ChildItem $davdir -Filter '*dav1d*.lib' | Select-Object -First 1
if (-not $lib) { Get-ChildItem $davdir; throw "no dav1d library in $davdir" }
$davdir = Join-Path $env:RUNNER_TEMP 'dav1d-lib'
New-Item -ItemType Directory -Force $davdir | Out-Null
Copy-Item $lib.FullName (Join-Path $davdir 'dav1d.lib')
}
"SYSTEM_DEPS_DAV1D_NO_PKG_CONFIG=1" >> $env:GITHUB_ENV
"SYSTEM_DEPS_DAV1D_SEARCH_NATIVE=$davdir" >> $env:GITHUB_ENV
"SYSTEM_DEPS_DAV1D_LIB=dav1d" >> $env:GITHUB_ENV
"SYSTEM_DEPS_DAV1D_LINK=static" >> $env:GITHUB_ENV
Write-Host "dav1d from $davdir"
+20 -2
View File
@@ -20,6 +20,10 @@ 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"
@@ -37,10 +41,11 @@ jobs:
key: release
- name: Build
run: cargo build --release --locked -p voelin-ui -p voelin-gateway
# dpkg-shlibdeps works out the .deb's dependencies.
# dpkg-shlibdeps works out the .deb's dependencies; patchelf points
# the .tar.gz's binary at the libraries it carries.
- name: Package (.tar.gz, .deb)
run: |
sudo apt-get install -y --no-install-recommends dpkg-dev
sudo apt-get install -y --no-install-recommends dpkg-dev patchelf
scripts/package.sh linux dist
- uses: actions/upload-artifact@v4
with:
@@ -72,6 +77,12 @@ jobs:
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}
"MAKENSIS=$($makensis.Replace('\', '/'))" >> $env:GITHUB_ENV
# FFmpeg's LGPL DLLs, shipped next to voelin.exe.
- name: FFmpeg
shell: bash
run: |
scripts/fetch-ffmpeg-windows.sh "$RUNNER_TEMP/ffmpeg"
echo "FFMPEG_DLL_DIR=$RUNNER_TEMP/ffmpeg" >> "$GITHUB_ENV"
- name: Package (.zip, installer)
shell: bash
run: scripts/package.sh windows dist
@@ -103,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
+206
View File
@@ -6,6 +6,212 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
## [Unreleased]
### Added
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
opens the folder.
- Linux `.tar.gz`: libvpx and libdav1d in `lib/`, and `bin/voelin-install-deps`
for FFmpeg, VA-API drivers, PipeWire, the desktop portal and a keyring.
- Windows packages ship FFmpeg's LGPL libraries, so hardware encoders and
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.
- 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.
- 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
- Selecting a server observes it through its gateway at once; the Observe
button is gone. The server dialog asks only for the address, password,
name and nickname: the gateway is found from the address.
- Relayed messages appear in TeamSpeak under the author's own nickname
(`Nick1` while the name is taken), not as `[Nick] text` from the relay.
- The client reports itself as TeamSpeak 6 (`6.0.0-beta4.1` on Linux,
`6.0.0-beta2` on Windows) instead of `3.?.?`; `--client-version generic`
claims the old version.
- Watching streams: VP8 decodes on one thread (FFmpeg's slice threads made
multi-partition streams 40-80 % slower), pictures are converted for the
window on their own thread into reused buffers, and libvpx and dav1d use
fewer threads. A 1440p60 VP8 stream from a 6-8 core sender showed 35-49
fps; FFmpeg decodes it at 95-101 fps on one thread against 54-60 on four.
- Release builds no longer limit Cargo to one job.
- The gateway is invisible: relayed messages look like everyone else's (no
"via relay"), and a gateway that is away is tried again quietly instead
of showing a WebSocket error; only what the user did and failed is
told, in plain words. A server whose gateway is away no longer shows as
connecting, so it can always be joined.
- 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.
### Removed
- myTeamSpeak account sign-in, profile, avatar, badges and User Tag: the
login page at start, the sign-in form and profile in Settings → My Account
(it says "Account sign-in is not available in this build"), and the account
presented to voice servers. They return through the gateway. A session an
earlier build saved stays in the system keyring (item `myts/session`)
until you delete it there.
### Fixed
- 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
The first alpha.
+94
View File
@@ -0,0 +1,94 @@
# Voelin — working agreements for Claude Code
Voelin is a Rust voice/chat client that is becoming a complete alternative to
TeamSpeak 6 and Discord. The project is being split into four repositories
(VoelinClient, VoelinProtocol, VoelinServer, VoelinGateWay) under the Gitea
org `Voelin`; the current plan lives in the approved plan file referenced in
`docs/` once committed. Keep the Rust toolchain in `rust-toolchain.toml`,
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
project's own crates (`scripts/own-crates.sh`) green.
## Hosting: Gitea, not GitHub
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
issues, releases, labels and repository creation go through the **Gitea MCP
connector** (`mcp__claude_ai_gitea__*`). Do not use `gh`, the GitHub API or
GitHub Actions assumptions; `.github/workflows` are kept only as reference.
- Git remotes are `gitea@git.faumaray.com:<owner>/<repo>.git`. CI runs on
Gitea Actions (`.gitea/workflows`).
- Report when the connector is unavailable instead of silently falling back
to another host or to raw `curl`.
## Multi-agent orchestration (MAO) policy
**Scope: these orchestration rules apply only to the MAIN SESSION.** A
subagent that reads this file performs its assigned role (design, implement,
review, help) and does not delegate it again or spawn further orchestration.
### Roles
| Agent | Model / effort | Job |
|---|---|---|
| main session | (settings) | **Orchestrator**: decomposes work, delegates, tracks progress and attempt counts, resolves escalations, reports results. Delegates implementation, investigation, testing and review rather than doing them inline. |
| `mao-designer` | opus / max | Designs, acceptance criteria, escalation handling |
| `mao-implementer` | sonnet / xhigh | Implements, runs checks, self-reviews; escalates after 3 failed attempts |
| `mao-sonnet-reviewer` | sonnet / xhigh | Fresh, independent implementation review |
| `mao-opus-reviewer` | opus / max | Fresh, final independent review of substantive code changes (correctness, architecture, unresolved risks) |
| `mao-helper` | haiku | Focused file searches, summaries, routine git operations within the user's authorization |
### Before delegating
Define, in the delegation prompt: the **objective**, the **scope** (what is
in and out, which files), the **acceptance criteria** (checks that must pass,
behaviour that must hold), the **relevant files** and the **expected report**.
Use named agents (`name:` in the Agent call) so collaborators can address
each other.
### Parallelism
Parallelize **independent** work only. Never give two agents the same files
to edit at the same time; split by crate, module or file set, or serialize.
### Implementation and review chain
1. `mao-implementer` implements, runs the relevant checks (`cargo fmt
--check`, `cargo clippy -D warnings` on the touched crates, the crate's
tests, and the integration/smoke scenarios named in the task) and
self-reviews before reporting.
2. A **fresh** `mao-sonnet-reviewer` reviews the implementation independently.
3. For substantive code changes, a **fresh** `mao-opus-reviewer` performs the
final independent review. Do not reuse the design agent's conversation
for this review; start a new agent.
4. The orchestrator decides: accept, send back with the findings, or escalate.
### Attempts and escalation
- Track failed attempts **per task**. An *attempt* is a proposed solution
checked against the acceptance criteria, not an individual tool call.
- After **3 unsuccessful implementation attempts**, stop Sonnet retries and
escalate to `mao-designer` (Opus) with the evidence: what was tried, the
failing check output, the diff.
- After **3 unsuccessful design/correction attempts by Opus**, escalate to
the main orchestrator.
- The orchestrator must then **change the approach, narrow the task, or ask
the user for the missing input**. Do not reset counters and repeat the
same loop.
### Communication
- Use `SendMessage` for direct agent-to-agent or agent-to-orchestrator
messages when it is available. Use `ListAgents` only if it is actually
exposed; otherwise address agents by their known names, or relay through
the orchestrator.
- Reports (every agent, every task) must include: **result**, **changed
files**, **checks actually run** (with their outcome), **unresolved
issues**, and the **attempt count**.
- Report unavailable agents, models or tools explicitly, together with the
fallback that was used (for example "mao-opus-reviewer unavailable, review
done by mao-sonnet-reviewer").
### Models and effort
Model and effort live in `.claude/settings.json` (session default) and in
each agent's frontmatter (per role). Do not set `CLAUDE_CODE_EFFORT_LEVEL`
globally: the roles need different effort levels.
Generated
+9 -231
View File
@@ -3502,19 +3502,6 @@ dependencies = [
"tower-service",
]
[[package]]
name = "hyper-timeout"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"
dependencies = [
"hyper",
"hyper-util",
"pin-project-lite",
"tokio",
"tower-service",
]
[[package]]
name = "hyper-util"
version = "0.1.21"
@@ -3534,9 +3521,11 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -4877,12 +4866,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multimap"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
@@ -5861,7 +5844,6 @@ checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
dependencies = [
"digest 0.11.3",
"hmac 0.13.0",
"sha2 0.11.0",
]
[[package]]
@@ -6340,27 +6322,6 @@ dependencies = [
"prost-derive",
]
[[package]]
name = "prost-build"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
dependencies = [
"heck",
"itertools 0.14.0",
"log",
"multimap",
"petgraph",
"prettyplease",
"prost",
"prost-types",
"pulldown-cmark",
"pulldown-cmark-to-cmark",
"regex",
"syn 2.0.119",
"tempfile",
]
[[package]]
name = "prost-derive"
version = "0.14.4"
@@ -6374,79 +6335,6 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "prost-types"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
dependencies = [
"prost",
]
[[package]]
name = "protoc-bin-vendored"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa"
dependencies = [
"protoc-bin-vendored-linux-aarch_64",
"protoc-bin-vendored-linux-ppcle_64",
"protoc-bin-vendored-linux-s390_64",
"protoc-bin-vendored-linux-x86_32",
"protoc-bin-vendored-linux-x86_64",
"protoc-bin-vendored-macos-aarch_64",
"protoc-bin-vendored-macos-x86_64",
"protoc-bin-vendored-win32",
]
[[package]]
name = "protoc-bin-vendored-linux-aarch_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c"
[[package]]
name = "protoc-bin-vendored-linux-ppcle_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c"
[[package]]
name = "protoc-bin-vendored-linux-s390_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0"
[[package]]
name = "protoc-bin-vendored-linux-x86_32"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5"
[[package]]
name = "protoc-bin-vendored-linux-x86_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78"
[[package]]
name = "protoc-bin-vendored-macos-aarch_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092"
[[package]]
name = "protoc-bin-vendored-macos-x86_64"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756"
[[package]]
name = "protoc-bin-vendored-win32"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3"
[[package]]
name = "pulldown-cmark"
version = "0.13.4"
@@ -6458,15 +6346,6 @@ dependencies = [
"unicase",
]
[[package]]
name = "pulldown-cmark-to-cmark"
version = "22.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84bbb29c624230c4bd1047bbdb2aa47e41c860e9665ce62ba9504eebe91bf867"
dependencies = [
"pulldown-cmark",
]
[[package]]
name = "pxfm"
version = "0.1.30"
@@ -7262,7 +7141,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
dependencies = [
"aws-lc-rs",
"log",
"once_cell",
"rustls-pki-types",
"rustls-webpki",
@@ -7380,20 +7258,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "schema-api"
version = "0.1.0"
dependencies = [
"prost",
"prost-build",
"prost-types",
"protoc-bin-vendored",
"thiserror 2.0.21",
"tonic",
"tonic-prost",
"tonic-prost-build",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
@@ -7869,6 +7733,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",
@@ -8853,76 +8718,6 @@ version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
[[package]]
name = "tonic"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
dependencies = [
"async-trait",
"axum",
"base64 0.22.1",
"bytes",
"h2",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-timeout",
"hyper-util",
"percent-encoding",
"pin-project",
"rustls-native-certs",
"socket2",
"sync_wrapper",
"tokio",
"tokio-rustls",
"tokio-stream",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tonic-build"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322"
dependencies = [
"prettyplease",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tonic-prost"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"
dependencies = [
"bytes",
"prost",
"tonic",
]
[[package]]
name = "tonic-prost-build"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27"
dependencies = [
"prettyplease",
"proc-macro2",
"prost-build",
"prost-types",
"quote",
"syn 2.0.119",
"tempfile",
"tonic-build",
]
[[package]]
name = "tower"
version = "0.5.3"
@@ -8931,12 +8726,9 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"indexmap",
"pin-project-lite",
"slab",
"sync_wrapper",
"tokio",
"tokio-util",
"tower-layer",
"tower-service",
"tracing",
@@ -9692,9 +9484,13 @@ version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"bytes",
"dirs",
"futures",
"h2",
"hickory-resolver",
"http",
"httpdate",
"md5",
"reqwest",
"rusqlite",
@@ -9714,7 +9510,6 @@ dependencies = [
"voelin-gateway-proto",
"voelin-media",
"voelin-model",
"voelin-myts",
"voelin-observer",
"voelin-platform",
"voelin-query",
@@ -9818,24 +9613,6 @@ dependencies = [
"serde_json",
]
[[package]]
name = "voelin-myts"
version = "0.1.0"
dependencies = [
"aes 0.9.3",
"aes-gcm",
"base64 0.22.1",
"ctr 0.10.1",
"pbkdf2",
"reqwest",
"schema-api",
"subtle",
"thiserror 2.0.21",
"tokio",
"tsproto",
"zeroize",
]
[[package]]
name = "voelin-observer"
version = "0.1.0"
@@ -9862,6 +9639,7 @@ dependencies = [
"tracing",
"windows 0.62.2",
"x11rb",
"zbus",
]
[[package]]
@@ -9872,6 +9650,7 @@ dependencies = [
"russh",
"serde",
"serde_json",
"socket2",
"thiserror 2.0.21",
"tokio",
"tracing",
@@ -9931,7 +9710,6 @@ dependencies = [
"voelin-core",
"voelin-gateway-proto",
"voelin-model",
"voelin-myts",
"voelin-platform",
"voelin-query",
"voelin-store",
+1 -3
View File
@@ -2,7 +2,7 @@
resolver = "3"
# third_party: vendored crates patched in below (not workspace members, so
# their own tests and dev-dependencies stay out of our builds).
exclude = ["fuzz", "third_party", "third_party/schema-api"]
exclude = ["fuzz", "third_party"]
members = [
"crates/proto/tsproto-types",
"crates/proto/tsproto-structs",
@@ -17,7 +17,6 @@ members = [
"crates/voelin-gateway-proto",
"crates/voelin-media",
"crates/voelin-model",
"crates/voelin-myts",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
@@ -38,7 +37,6 @@ default-members = [
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-model",
"crates/voelin-myts",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
+1 -1
View File
@@ -41,7 +41,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
reactions, topics, events, stream directory and administration; the media pipeline for streams
(capture → VP8 + Opus → stream, stream → decoder)
- `crates/voelin-ui` (`voelin`): Slint desktop app: servers, channel tree with talking indicators,
chat tabs (own channel via voice, other channels via relay), connect / observe invisibly, mute, push-to-talk
chat tabs (own channel via voice, other channels via relay), connect, observe invisibly (on selecting a server, through its gateway), mute, push-to-talk
(in the window and as a global hotkey), audio settings with a level meter, per-client volume, and on
TeamSpeak 6 streams: watch in a viewer, share the screen with sound. Desktop and phone layouts
from one design system, dark and light themes, text size, emoji ([docs/ui.md](docs/ui.md))
+4 -9
View File
@@ -21,16 +21,15 @@ dependencies to their projects (tell us too if this client is affected).
## What the client stores
There is no telemetry and no account with us. The only outside account is
the optional myTeamSpeak sign-in (desktop), which talks to TeamSpeak's
service at `clientapi.myteamspeak.com`: at sign-in, when a saved session is
checked at start, and at sign-out.
There is no telemetry and no account with us, and the client signs in to no
account service. (Builds before this one had an optional myTeamSpeak sign-in;
its saved session stays in the keyring, item `myts/session`, until you delete
it there.)
| What | Where | Protection |
|---|---|---|
| Identities (TeamSpeak private keys) | SQLite database `client.db` in the data directory (`~/.local/share/voelin`, Flatpak `~/.var/app/<app id>/data/voelin`, `%APPDATA%\voelin`, Android app storage) | File permissions of the user account only; not encrypted. An identity is the account on every server that knows it: back it up, do not share the file |
| Server and ServerQuery passwords | OS keyring (Secret Service, Windows Credential Manager, Android Keystore), service `voelin` | Keyring; kept in memory for the session only when there is no keyring |
| myTeamSpeak account (optional sign-in, desktop): session, renewal and one-time-code renewal tokens, device id, email, username, account id and the account's private signing key | OS keyring, service `voelin`, item `myts/session` | Keyring only: without one the sign-in is not kept, not even in memory. Passwords and one-time codes are never stored. Signing out deletes the item and ends the session at TeamSpeak |
| Bookmarks, settings, chat history | `client.db` | File permissions; history stays until deleted |
| Crash reports (opt-in) | `crash-reports` in the state directory (`~/.local/state/voelin`, `%LOCALAPPDATA%\voelin`) | Local only, never uploaded. They contain the panic message and a backtrace, which may include server addresses or names; review before attaching one to an issue |
| OpenH264 (opt-in) | Downloaded from Cisco into the app's directories | Loaded only if its SHA-256 matches a known Cisco build |
@@ -40,10 +39,6 @@ checked at start, and at sign-out.
- **Voice connections** use the TeamSpeak protocol's encryption. The server
and its admins see what any client sees: your nickname, identity, IP
address, channel and messages.
- **Signed in to myTeamSpeak**, every voice server you join also gets your
account's myTeamSpeak id with a proof signed by the account, which links
your visits to different servers to one account. Signing out clears it on
the servers you are on.
- **Streams (TeamSpeak 6)** are peer-to-peer WebRTC (DTLS-SRTP). Viewers and
streamers exchange ICE candidates, so **they learn each other's IP
addresses**, including local network addresses. Only watch and share
+87 -831
View File
@@ -53,13 +53,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
## schema-api
The account client uses message bindings and session helpers from the local
schema-api 0.1.0 snapshot vendored under third_party/schema-api. The supplied
snapshot has no declared license or license file; no MIT or Apache license is
implied for it or its supplied schemas. See its VOELIN-PATCH.md for provenance.
## Native libraries
- Opus (libopus), compiled into the app: BSD-3-Clause, Copyright 2001-2023
@@ -182,12 +175,12 @@ the crate's authors are listed as its copyright holders.
| License | Crates |
|---|---|
| MIT License | 657 |
| Apache License 2.0 | 34 |
| MIT License | 658 |
| Apache License 2.0 | 31 |
| Unicode License v3 | 26 |
| ISC License | 24 |
| BSD 3-Clause "New" or "Revised" License | 22 |
| LicenseRef-Slint-Royalty-free-2.0 | 12 |
| ISC License | 8 |
| BSD 2-Clause "Simplified" License | 3 |
| zlib License | 3 |
| Boost Software License 1.0 | 2 |
@@ -405,284 +398,6 @@ Used by: flagset 0.4.7, hound 3.5.1
````
Used by: ring 0.17.14
````text
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Licenses for support code
-------------------------
Parts of the TLS test suite are under the Go license. This code is not included
in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so
distributing code linked against BoringSSL does not trigger this license:
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
BoringSSL uses the Chromium test infrastructure to run a continuous build,
trybots etc. The scripts which manage this, and the script for generating build
metadata, are under the Chromium license. Distributing code linked against
BoringSSL does not trigger this license.
Copyright 2015 The Chromium Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
````
Used by: moka 0.12.16
````text
@@ -1304,7 +1019,7 @@ Used by: cpal 0.18.2, imgref 1.12.3, self_cell 1.3.0, unicode-linebreak 0.1.5
````
Used by: gethostname 1.1.0, prost-derive 0.14.4, prost-types 0.14.4, prost 0.14.4, ring 0.17.14
Used by: gethostname 1.1.0, prost-derive 0.14.4, prost 0.14.4
````text
Apache License
@@ -2518,84 +2233,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
### ISC License
Used by: ring 0.17.14
````text
/* Copyright (c) 2014, Intel Corporation.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H
#define OPENSSL_HEADER_EC_ECP_NISTZ384_H
#include "../../limbs/limbs.h"
#define P384_LIMBS (384u / LIMB_BITS)
typedef struct {
Limb X[P384_LIMBS];
Limb Y[P384_LIMBS];
Limb Z[P384_LIMBS];
} P384_POINT;
typedef struct {
Limb X[P384_LIMBS];
Limb Y[P384_LIMBS];
} P384_POINT_AFFINE;
#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H
````
Used by: ring 0.17.14
````text
// Copyright 2015-2016 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//! EdDSA Signatures.
use super::ops::ELEM_LEN;
use crate::digest;
pub mod signing;
pub mod verification;
/// The length of an Ed25519 public key.
pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
let mut ctx = digest::Context::new(&digest::SHA512);
ctx.update(signature_r);
ctx.update(public_key);
ctx.update(msg);
ctx.finish()
}
````
Used by: untrusted 0.7.1, untrusted 0.9.0
````text
@@ -2615,397 +2252,6 @@ Used by: untrusted 0.7.1, untrusted 0.9.0
````
Used by: ring 0.17.14
````text
// Copyright 2015-2022 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::limb::Limb;
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct N0([Limb; 2]);
impl N0 {
#[cfg(feature = "alloc")]
pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS;
#[inline]
pub const fn precalculated(n0: u64) -> Self {
#[cfg(target_pointer_width = "64")]
{
Self([n0, 0])
}
#[cfg(target_pointer_width = "32")]
{
Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb])
}
}
}
````
Used by: ring 0.17.14
````text
// Copyright 2015-2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::{bb, error};
#[deprecated(
note = "To be removed. Internal function not intended for external use with no promises regarding side channels."
)]
pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> {
bb::verify_slices_are_equal(a, b)
}
````
Used by: ring 0.17.14
````text
// Copyright 2016 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//! Elliptic curve operations and schemes using Curve25519.
pub mod ed25519;
pub mod x25519;
mod ops;
mod scalar;
````
Used by: ring 0.17.14
````text
// Copyright 2016-2024 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::error::{KeyRejected, Unspecified};
impl From<untrusted::EndOfInput> for Unspecified {
fn from(source: untrusted::EndOfInput) -> Self {
super::erase(source)
}
}
impl From<core::array::TryFromSliceError> for Unspecified {
fn from(source: core::array::TryFromSliceError) -> Self {
super::erase(source)
}
}
impl From<KeyRejected> for Unspecified {
fn from(source: KeyRejected) -> Self {
super::erase(source)
}
}
````
Used by: ring 0.17.14
````text
// Copyright 2018 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//! Serialization and deserialization.
#[doc(hidden)]
pub mod der;
#[cfg(feature = "alloc")]
mod writer;
#[cfg(feature = "alloc")]
pub(crate) mod der_writer;
pub(crate) mod positive;
pub use self::positive::Positive;
#[cfg(feature = "alloc")]
pub(crate) use self::writer::TooLongError;
````
Used by: ring 0.17.14
````text
// Copyright 2019-2024 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::BlockLen;
pub(super) use self::{
sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN},
sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN},
};
pub(super) const CHAINING_WORDS: usize = 8;
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86_64"
))]
#[macro_use]
mod ffi;
pub(super) mod fallback;
mod sha2_32;
mod sha2_64;
````
Used by: ring 0.17.14
````text
// Copyright 2024 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`.
#[allow(dead_code)]
#[inline(always)]
pub fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
r
}
// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`.
#[allow(dead_code)]
#[inline(always)]
pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
r
}
````
Used by: ring 0.17.14
````text
// Copyright 2024 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//! Integration tests for non-public APIs.
mod bits_tests;
````
Used by: ring 0.17.14
````text
// Copyright 2024 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
pub use self::{
array::Array,
base::{IndexError, Overlapping},
partial_block::PartialBlock,
};
mod array;
mod base;
mod partial_block;
````
Used by: ring 0.17.14
````text
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#![cfg(all(target_arch = "aarch64", target_endian = "little"))]
pub(in super::super) mod mont;
````
Used by: ring 0.17.14
````text
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#![cfg(target_arch = "x86_64")]
pub(in super::super::super) mod mont;
````
Used by: ring 0.17.14
````text
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
mod storage;
pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK};
````
Used by: ring 0.17.14
````text
// Copyright 2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
pub(super) mod aarch64;
pub(super) mod x86_64;
````
Used by: aws-lc-sys 0.45.0
````text
@@ -3347,25 +2593,6 @@ THIS SOFTWARE.
````
Used by: ring 0.17.14
````text
Copyright 2015-2025 Brian Smith.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
````
Used by: libloading 0.8.9
````text
@@ -8672,31 +7899,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
Used by: tonic 0.14.6
````text
Copyright (c) 2025 Lucio Franco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
````
Used by: secret-service 5.2.0
````text
@@ -9677,6 +8879,33 @@ SOFTWARE.
````
Used by: av-data 0.4.4
````text
MIT License
Copyright (c) 2017 Luca Barbato
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
Used by: imagesize 0.15.0
````text
@@ -9758,6 +8987,33 @@ SOFTWARE.
````
Used by: dav1d-sys 0.8.3, dav1d 0.11.1
````text
MIT License
Copyright (c) 2018 Luca Barbato
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
Used by: crc32fast 1.5.2
````text
@@ -10558,7 +9814,6 @@ Standard text, used by:
- str0m-proto 0.7.0: Martin Algesten <martin@algesten.se> (https://github.com/algesten/str0m)
- taffy 0.10.1: Alice Cecile <alice.i.cecile@gmail.com>, Johnathan Kelley <jkelleyrtp@gmail.com>, Nico Burns <nico@nicoburns.com> (https://github.com/DioxusLabs/taffy)
- tauri-winrt-notification 0.7.3: allenbenz, Tauri Programme within The Commons Conservancy (https://github.com/tauri-apps/winrt-notification)
- tonic-prost 0.14.6: Lucio Franco <luciofranco14@gmail.com> (https://github.com/hyperium/tonic)
- tract-extra 0.23.8: Mathieu Poumeyrol <kali@zoy.org> (https://github.com/sonos/tract)
- tract-transformers 0.23.8: Mathieu Poumeyrol <kali@zoy.org>, Louis Chouraki <louis.chouraki@sonos.com> (https://github.com/sonos/tract)
- windows-collections 0.2.0 (https://github.com/microsoft/windows-rs)
@@ -11524,34 +10779,6 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
Used by: hyper-timeout 0.5.2
````text
The MIT License (MIT)
Copyright (c) 2016 The weldr Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
Used by: same-file 1.0.6, winapi-util 0.1.11
@@ -11606,6 +10833,35 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
````
Used by: byte-slice-cast 1.2.3
````text
The MIT License (MIT)
Copyright (c) 2017 Sebastian Dröge <sebastian@centricular.com>.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
Used by: derive-new 0.7.0
-7
View File
@@ -53,13 +53,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
````
## schema-api
The account client uses message bindings and session helpers from the local
schema-api 0.1.0 snapshot vendored under third_party/schema-api. The supplied
snapshot has no declared license or license file; no MIT or Apache license is
implied for it or its supplied schemas. See its VOELIN-PATCH.md for provenance.
## Native libraries
- Opus (libopus), compiled into the app: BSD-3-Clause, Copyright 2001-2023
+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 },
@@ -1414,4 +1414,126 @@ version,platform,hash
3.?.? [Build: 5680278000],Linux,Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==
3.?.? [Build: 5680278000],OS X,SttEnjoWE8jqIM6BOHSfiZP9DGjW0EP/ajU4bdKqgGMV4aYq/kzwVA9gxbmdIzV4lbaokvXBqrRjfBHrTVh8Cg==
3.?.? [Build: 5680278000],Windows,DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg==
3.?.? [Build: 5680278000] DEBUG,Windows,FaA10gndI44f19ZThYJX2OSM8ESrx9/vJ2uY+rON4enzzPsPR9kiPhsUXtMcC5szzTu6F/vLCiNNEhCr70CKCQ==
3.?.? [Build: 5680278000] DEBUG,Windows,FaA10gndI44f19ZThYJX2OSM8ESrx9/vJ2uY+rON4enzzPsPR9kiPhsUXtMcC5szzTu6F/vLCiNNEhCr70CKCQ==
3.6.0 [Build: 1668022263],Windows,jNUeF6ydYPJp6CpoA2Nm8FcmxPTwj8bFJmmzo/Ch2B9L2CU2rrgLJedcQM3NjAncESYYywUiFR0+BsljvaTNAQ==
5.0.0-qa-74-5 [Build: 1680085518],Windows,/X5xXLBPrLClWkivAnMJCz+QIBmFk9fFie8sNg69OdN/xwBQrX6naf2IehfxLdd+BBWX/5TsDjuPJqJwhK1FBg==
5.0.0-qa-74-7 [Build: 1681481733],Windows,4qdm8R3gNHlXDV9PS2CtV3Fe9SN7Mjgt82X+iZmqwMXk9B0g9vCyK62G7h2nr/qcqSopPXR4652xMsSQPYVvDQ==
3.6.0 [Build: 1681728436],OS X,MZzEbAN51fl7FGiF51T32nHz5tySXH3te4EEZip5rImRNX1Ey3bBQkahN1PYhURNAQxAtIupczX5iGMmvKm4DA==
5.0.0-qa-74-8 [Build: 1681821920],Windows,wBuvBhPgbvXmtEOavMpF/6X7xvHkd0PcrNmob7nSr5trxi5HFGjzvOZU19p56yzOStI077LvVJcQtjVha2uXCA==
5.0.0-qa-74-10 [Build: 1682065994],Windows,fCODC/wSy5xu9VXPjK3MsRur4MqN/mSLcP/DdbQ2u/KNgQmpuQEsVelmbrf5AvJUQ9YhmXyx8aMvTnG9kHSnCQ==
5.0.0-qa-dc-1 [Build: 1682080978],Windows,0p63hM9RbR65x093OWBlS9g0We6lNfYA+IWN99TZ23HXzWXuvfukMK6lIviHJkNSFWCBxhGQFmFi9lttH00vCA==
5.0.0-qa-74-11 [Build: 1682337867],Windows,BhUfmE4EX5h9gjKKtfO1JQ61sIdzZfm1IcvA4FNU8BtmA2DSzUJ9uDWFrq60h7lh33wkktDCzlXL7j8PNQChCg==
5.0.0-qa-74-13 [Build: 1682589154],Windows,4OMk6jcMvJc/P3zaojn8+laRQzG/vnmEkWEmTpQzIsTcPzKOu5irT82YpOtlp+BIxFDGb8onygu/turJjHLiDA==
5.0.0-qa-74-14 [Build: 1682680770],Windows,bwZm9gRSoUSRTWCcc1N0ZuKs+xznjBKErt3myq9YlXzdC/jkn4miNoinG60Ynbsp1JkU8tAVKy4v8HUBLictAg==
5.0.0-qa-74-15 [Build: 1683039954],Windows,MFemYXY5GGg2OYhdRzdhpkn9ujzOMMCZA8QGlPV1GUbhjjtjXuMw5+ydEzLwcgZYpFTod3N6CEz/b/aXwWeyCQ==
3.6.0 [Build: 1683203743],Linux,ao52xPYBI8qe57kJJ6KQgQPr0J9w7BhGikkFMqs7pGpsrxLK9ghzOlbu5IZsdct3tNw88S2YB0oFmcCWlx+hCA==
3.6.0 [Build: 1683203743],OS X,w/rKVPUul3im2KxVqvL8udZf/o0Yre+92bvACj8hU1x5aNtQkvodXo7CML+4mM6EgifiVCyI8kyo6BtbfeF7Ag==
3.6.0 [Build: 1683203743],Windows,Ha73fVhy6+r06Zh3CCx8RVJ1HtHCaABNnTfFbjQPy0dm/e79JFIPZgeC5IvJBltwaiBic/9M+aKBrt+7sNxNDw==
5.0.0-qa-74-17 [Build: 1683295507],Windows,hpDc2gHUCHv3HUA1nBray8U8Re/d9XvDUHZkefwMkgeL8L6KizWeo7vZzFguQLYpRPr20B4h0d/A8NAxYxfqAA==
5.0.0-beta74 [Build: 1683627550],Linux,M5TTHH2J1erTQKBElj0dz4Lm9N4erZuHxZNjNlbJjDxRC8CYnziveIW0j8DY8NeQaSKHeCTXoL5pDakZtvAODQ==
5.0.0-beta74 [Build: 1683627550],macOS,EmwreqEhVhmpGrjPKyNjwuEdWKF+uGTX0syXkq57+klgtcNw9lddPm9lodLTdB5spPGlsx0CJQySvEXlWyXNDg==
5.0.0-beta74 [Build: 1683627550],Windows,pipm1uaijQDJKPZgRkhjyLsLG/W9KnjEDWNGvqUkUrSuqrUvfEG4OUsdTOReMb+FJp4xz82n3cwd4HExO5k3Dw==
5.0.0-qa-tr-1 [Build: 1683731563],Windows,HmBOKipdW28prdI2FFdmBu/mMXui+zdC0G7769F3bW+nVRfNoVtvJhSUx7/UDeQ9ghHbUIW6q2lCxnQLzsIRCg==
3.6.0 [Build: 1683804569],Linux,CqbjoDdeYd83t/u9YUtlQf4rDIf6yEnFInF6nq7GcO02tRXBQlppxHd/ziaTdlpwYrha00goKb2GGWwdrNhFAA==
3.6.0 [Build: 1683804569],OS X,sT6ej/41Qk3T0LfXl3+VSm3J7Ck4M/OCTWIRundvOHBRodGLWJtddZuQu7IlXNr9mbJfklarQ4XyyXvXMdjvCw==
3.6.0 [Build: 1683804569],Windows,PesaPHU3+aiZMUPzpq8UBKjck77jLw9N+hyZq6JjD4baqns5dmKj4sTfSL9/QROyOLqPICZ+fwkSy5iuuMQEAw==
5.0.0-qa-75-1 [Build: 1684855710],Windows,LLfl5sHAfsdepvecADQI9/nx98H+jA/r9pe6fq5CqlRY+MCdVbOphiXy7zZerE5h4lIRqcJtEeAJVIXaNu+LDA==
5.0.0-qa-75-2 [Build: 1685542148],Windows,Ir/0IAdrK5dDVDlh6gIRwGZe0DFR9vUNf313cLwHTN1EB9nyO2Bq5yoBjZuGYOdNgcbdgQCBzfKNd4ZpCxxSAg==
3.6.0 [Build: 1685546268],OS X,i257nbRzdfvBvgW4IeFoCe8KnCDfoIvtNeORVFVPohKWfFajfoBNYTDa/2/jgHbd97Dzqd+hx8t2ZwPPwgR+Bg==
5.0.0-beta75-rc1 [Build: 1685698093],Windows,Jkvyb0PGEmS3/lVfr2x7SFlSZMeopxo7JXBHx8m1pWeDL7XdjYoDPOaIJ6UD1hNxY/wv84fgAwt65Ip2AdP1Dw==
5.0.0-beta75-rc2 [Build: 1686050172],Windows,BcULgPFoo2+QTsjD88VH5rONZcABm32fgd5jBNbdkxTaERND/CJI4ZBWS30s5WKN9bi3T6LKUOzcLyN6+gfNDQ==
5.0.0-beta75-rc3 [Build: 1686126230],macOS,38gec16GTEPCeaVw5qM8tU58HWM0HZ20yROR1foT8TRHqsTvoED2gm07xb6KfSHN3//3k1ErMvuS4emNBohcBA==
5.0.0-beta75-rc3 [Build: 1686126230],Windows,1Jj8VSZ8QQ2K5jFiRM2DB6Z12Yi1fFjJ3ng96W/S+zU2VzldrOsuvhO36BOjbWMCcEIWoc45sbHPm+utJtxeAw==
3.6.0 [Build: 1686637110],Linux,8eM1WF1E9+8DeS+Zm6IcidGtuTC0+jtrLRkkiIk+GUA91bVOCyYgrUWNFVftZtFEM4qIOICJhLQopVTIwYJOCQ==
3.6.0 [Build: 1686637110],Windows,r21r7w+EGu6F6aruzYiuzv2lP5bX8X4TP2xXBH5Wljz3x/VxOxndN84qA9sPn6QJZFQCtzq+iEb0wfFFM7mYCA==
3.6.0 [Build: 1686731472],Linux,MKaey6yCAdQDBHl5ERY24N5bz9CsdypGJfpTC5mNPc0s3Z1zeb8c3g9/w/mlRD+qoK3xlCYt3f25oaFMZofMAA==
3.6.0 [Build: 1686731472],Windows,KRYqAaQhnKh/NQ4LrOw8+nVA659NDn+IlOB8hhmKZolIOEDSiijCeDoTVf61t/0Z0y1OWlxABS4X7uWRzvhiDw==
3.6.0 [Build: 1686736529],Linux,l1LIP8nreS+y33Hp7SmA6M7kJZZI1KbsN1/Rx9hAAL3Wd6PbEwhLIQHXBkfCI8MizWSAl7NDb+UOuNxAL9GoAg==
3.6.0 [Build: 1686736529],OS X,EFU7gHd4QZhwmAojg0Tk/tL9dPiFTcWn40R/6YZCrlzX6t0FSPXiAj93OUf1du+qyy2ly4Lrox/M0u4wOhEDBg==
3.6.0 [Build: 1686736529],Windows,kRHYyNCdM5rna2v27LyPerCeNd1s76h0KfpLSmLQk3Bzkrg/NCBzpj0WofE1cvbQ2Qm/41d/mUIMxIfXJ/+hCg==
3.6.0 [Build: 1686744367],Linux,toUkg41DTfeCfWgqqxSeb8eDzri2PsjRNIcHsFxr0d7nLCTYGoSFfQjme84FjMYtvYloMVAk/gx5Nt+hWE+ZBg==
3.6.0 [Build: 1686744367],Windows,VXx9yKF0ZaBMqlU285hPLxaCgH1N8OwKjU52A0EdulFmEeLYYQeJI/7139hno0Ph8kGT6nxoDRKtw0yn9woNAQ==
3.6.0 [Build: 1686749764],Linux,TccRBHwn5LSA0lfpa2B42QmfCOiG+MqqyhlOqy5RcuRQNUGPD0e47lUz+Z/8+Gsdc1TPG4+vYlRl8+v2v+26Aw==
3.6.0 [Build: 1686749764],OS X,g8H7Op8eCrn0wHutuD/SlmUcZPmkSlFUBhvZpSgm9kuQl4dapzKJq2anI5jDwRs/ooBm/wrIlSiWI6HXuOPZDA==
3.6.0 [Build: 1686749764],Windows,gfzG6CfwNYeqrjT68s7ahPd24A/XS0P8LLAB7hrE54MnrlO12RiflD2w69VZ7EYlqnd9GAiVzdGJHCmCFWtlAQ==
5.0.0-beta75-rc4 [Build: 1687777367],Linux,DCZXmwc6xocEuzvS+f+qyQLwN8FLdNqyDTAjdOfy1y8JeO8VmIlNwRFd7X0D0Q51kqPNPIB7Jbh4yiwySHjhDw==
5.0.0-beta75-rc4 [Build: 1687777367],macOS,xgV8yX/XS3qVXshur/PbsquRIbPvz3w+hJL905nQQBwbniSGvKxAUcTJompBgECG989hf6nW+2GApbf8p70RBw==
5.0.0-beta75-rc4 [Build: 1687777367],Windows,wIGrljvdCMZX3XJoe0rWTA/nNZuXVC6z8kUvDw1gi9YxyM6AxmsleqOzjZ3zY5Ii7cRU8slxNAh4ERLcHEPQDg==
5.0.0-beta75-rc5 [Build: 1687944933],Windows,1fQu13pX9jdR5oJ4yaqasfoWrcySvwocstrOQOZLZjB+0nUtKMYW4Kp2DYHuIoTlvuWiiF7pYc7YK4bOUWdlAA==
3.6.1 [Build: 1689766945],Linux,fjR+/+EsahBSG/qGjcTTUVIyn/w7W6h7uy9YUebYzRbtWIxxv69ZD4k7Y4Z1OS9+cuB/Nbtg05J2Upt2oK/qCg==
3.6.1 [Build: 1689766945],Windows,+6Tcswj4E40ablTifyXIA3UDEY+359hxjEVx+Tb+xha08CiSwpzSpFndS8GCs8z0QICVKUZBwhVfGfePm00vDw==
3.6.1 [Build: 1689949736],Linux,yM9tjby+KBrov9dyNLM1I1PZXDBK2fdwR8ylvKdZJc/DaL5GqnoBAGLkFmzOIl//u8VMbXspCDWb/PbvOS2gAg==
3.6.1 [Build: 1689949736],Windows,30JdFX5zLrHx3uKsb55vpdlS6DO36bVRSOewzOlTV70LS4X0dVMZp64EzDZY8ZR2woAAjZ8ZR/rIKt4JlNnKDg==
3.6.1 [Build: 1690193193],Linux,UAcE5h5FgPcdChWTtiO816HX8f2qdoDcDEw6crbJ96Yo7rp1Bt+qx/rkKK9bzlVWMhOd4fI7pr++1XaPkEBnAQ==
3.6.1 [Build: 1690193193],OS X,P+KOw42V8K0nN5FbGItCaJzrDuWcRgfE3MRzrtbYAhRMTXHzRxvwLkoLM7+vKTW135NtWZlKbZuDAvxgwhSLBg==
3.6.1 [Build: 1690193193],Windows,I5uwVK2CZa9aXblVQPUKGbjNYoE2eaUPujK8sVGWAUsPhmGySTvSkP70jrpX8pUgQdtHwUOl3gvrAH6+moNeDQ==
5.0.0-beta75-rc7 [Build: 1690443874],Windows,dvpImL6c5RMVxPV/jNNG3DncR8QlQcqWKBQCDiE89KQpZ/q4kRJkAlje0Pgoqk8BT/2WQWaUixqctfOGNPxNBA==
3.6.1 [Build: 1690811573],Windows,aWKpb0eAiI6FndcOBw+OixzripgCENMlM5gwKuRhdqtOdWAEYI5Luz8sGQ77yWC1RlQ1llxHcqhjNcJ8qMVcAw==
3.6.1 [Build: 1690872913],Windows,+YmPaYUBL4F9+TgxyFhlT8qIi1Ym+So4NNMcuohla/u4kfJCGabZ1vDF4cIOAghIqWfO+bQ0OkORZrCBdpi2Cw==
5.0.0-beta75-rc8 [Build: 1690875928],Windows,1xI3XWPzHxz5zD4OIZDvJteHXOHcxliqCGh/lifvzA6Gb+/GhkcPGj5RqmlIHPKHJFAozbB0UhvTuJcTU5HGDg==
5.0.0-qa-75-4 [Build: 1690964581],Windows,3o5M5JegEvtXwGHMdhUSR+PbaXTIoinUI1GGgoXrGi2tYNUvaguiYYlsak4z8twpgzp68L0KaoA4nz4DyNX9Aw==
3.6.2 [Build: 1690976575],Linux,iSJZ2tmUsUhCuB3G/7SCgM+JNZe3Jb/KSxFNr+0FDgg8r5t4JKGBD0SPl/cdDMqNqXmG9zEHi0XmuVl9lysoCg==
3.6.2 [Build: 1690976575],OS X,0VegJZtWI25+RXM3J6jNfskqEgM8f4CyYrrz0IXuSK8azRQ3AMWH7YgSnrotoIX1q7aDhnTulk9eChKSPoKVCQ==
3.6.2 [Build: 1690976575],Windows,OyuLO/1bVJtBsXLRWzfGVhNaQd7B9D4QTolZm14DM1uCbSXVvqX3Ssym3sLi/PcvOl+SAUlX6NwBPOsQdwOGDw==
5.0.0-qa-75-8 [Build: 1691162334],macOS,jJLCUYbKDDtPB56YGtUSK+EjrY3LxoOAWVLHKIc/Li4UAFNL9iaq5gRvHF+cfJHyGg0keg2SEVr1+TfCEDG4Dw==
5.0.0-qa-75-8 [Build: 1691162334],Windows,yLHN6dcol32mrRoi2ZMYDYsn9XPMncp79PwcCHxFC+8CuaxhOSq7/iXUPwhsdqvUQzyvstq1hCaG9/MLn8G/Dg==
5.0.0-beta75-rc10 [Build: 1691405422],Windows,ETFP63u2QoQzmb1vHyRC+KxAAZKWq1PEpKfC6ep8A59zptnOtocEbc50wb55GpF7pVv2n5nJP6CV3iv2QauAAA==
5.0.0-qa-75-9 [Build: 1691734909],Windows,t0guTMT1lZZI34At9X9kg0/ablk2LEtjePCLXNSCyTGeam3E4l+hjjaLZYx5gFLDX4tQEGqG4Dms96T+xRVTCg==
5.0.0-qa-tr-2 [Build: 1691758984],Windows,YmsBwLBmFqrMhlCLGXUcn/qLvHJBrOeg1kRj+xDp7FltLJ6z4G5r6QdPt1sTaalD3TWE9If10i9mQFnP73nCDw==
5.0.0-beta75-rc11 [Build: 1692269983],Windows,TraubtepmvLTzCkyZwDgJram2qrdpuPy1hWRhN0ZFwSAnXkBklJjBSMAUO22D/hTAfTeiQaUiFDJThf2aGSJBQ==
5.0.0-beta75-rc12 [Build: 1692273792],Linux,UFodfOKNy4uOGnQdL35xlc5XoOkT2xVzn93w2+rshfBQKd63BqCqBcrMDL5We4UGnCdeF7oiUsraWm65qvfDDA==
5.0.0-beta75-rc12 [Build: 1692273792],macOS,yRtBZtJrOetbT3IREKlZ7bYCLLDWtl88l6OvbRHsfI0MwgBuaLuZmgA7gAGaNDc4u427XpxD1U4WRRMJ4XXuCA==
5.0.0-beta75-rc12 [Build: 1692273792],Windows,fX3auh0DNxFmMmmjKmxJ0bS5T+sI2OActVkppSthJOJ/W1so/WfdxtxavuJgpzFHQ7wqanaJYUajAY0uFnYEDA==
5.0.0-qa-75-10 [Build: 1692281089],Windows,6Tn50hZBDK2v1gAfXvnfVsOvCYiZ5O7t9ae/PGIzTQPYJiK+83CCR9F+NrjaNwrwn8U4fHCm0DvF2qrk6FiEDA==
5.0.0-qa-75-11 [Build: 1692344346],Windows,XUiXiYpVQ1lvhscQ0T0STLhzFxgUgPD5yRvHnHa+gl0z62xvSnUYMcaulZu+vu7N7Zx2XD0yXwDt1aAWjmSmAQ==
5.0.0-qa-75-12 [Build: 1692942703],Windows,eg20cqWFjsdIv3fP37BPzSsEMAabdXgPwE/iZ0nu8JIUFCx+dDPmD+Yezf4f2cbe+w7MEkPoAMKS5cAOYbG9BQ==
5.0.0-qa-tr-4 [Build: 1692956820],Windows,B8tNlJlgST8ITvDXO4m0mBmR+fOur02Dr0MbmYcE1LWOWJfQUk2A5Lyni65NEBdJIg6/D3ihc0US27Yd4sFWAA==
5.0.0-qa-75-14 [Build: 1693548790],Linux,VFo+uqfuN636vfO2uplN7MxwjcGgZ7C7a8H78PSMBtPYU5KOh86FNgH3g4TefK5suVza384d9DpPK5sjZBVICA==
5.0.0-qa-75-14 [Build: 1693548790],Windows,eBIeiZ9RjIlTT9AVkwXsiHsKrvSkGWfILDbts+A5xGDsIU8nFGl77uXjfNqjM6+Ud2Eb6lKk7NVQrmRWs/b7AQ==
5.0.0-qa-tr-6 [Build: 1693832989],Linux,7S96m1KKKlB2+x4osdky+gdCUnWTlAaoiOQcsmmXPUxxyS/ypTY7tnYRmo2lj/Hx46aI7R0+Z4+vnHLIY9InCw==
5.0.0-qa-tr-6 [Build: 1693832989],Windows,IOoZZnLdprCn572p0GRdOJftjQq12pYODanfyqFy9rG+sSQWmDs4Q7LX5aF/K6oRi1dj31I/BaBKxRhcs0ylAQ==
5.0.0-qa-75-16 [Build: 1694525079],Windows,mnve3nHnNHCWJD/v1UucjHwYP5iiMcQYozzkQTxY4SlU3HozJb1Zkq9hhXpnaQHE37TODB+7B/fshVo/yWJIAA==
5.0.0-qa-75-17 [Build: 1694593665],Windows,dQxRWH4A/RdhuwMQG2fWtbP8aRLJNs9eGrdSHBEd07MEVA29iyNx6J4Ab9pFvzw8rbxC/QsL20G1LGc0ilz7Dg==
5.0.0-qa-75-18 [Build: 1694615531],Windows,qDBmGwpP/bskv03tvqCDvK4xXGVpyS7K6cvu06/yMk5rDd05Dba928UfMNh0/Wub/Xy9MfI5gVdA3kSuXJrnDA==
5.0.0-qa-75-19 [Build: 1694699313],Windows,KtR3EavFC3d5PBcKFWt7Gd27B6fAG0k4EevugDzjYs2BCg+PFgeZ1DPAQCw8/k0SzewR7i9x/ZedhPC7pvYmDA==
3.6.2 [Build: 1695203293],Linux,p4iF1jZ3ZOz9MEkKSZ2bvnFtm9WmUcQy9mAP//erFE4PF1sB6K1CSANrr+3X4B0aZR0u+K2pjnv8kiKsWKQCBQ==
3.6.2 [Build: 1695203293],OS X,SOCkLcsxINIGVc+3OQ5Vrmv2BVNNFA9LX5Jj9tqbIiYv2HU6Z5E8AL5+v5G2LDN0F+U55+uW43ezUoYAr1WuBA==
3.6.2 [Build: 1695203293],Windows,4BdaZpdgUSMCuIs8qcloJPNxNlJ4o7QKnxMCRO60mSOTtJZyKjOrGLAmeAEtLIJjcjmdSpycMbQOIV92K2vXAw==
5.0.0-beta75-rc13 [Build: 1695397203],macOS,gwgeaGifMO1IIGcPJBbHUklR0m11N+XeuvflfT5CFUh0RE3zbzmV0ehUtg5udX9BU9XxcLh5LsiMQtmUobmUCQ==
5.0.0-beta75-rc13 [Build: 1695397203],Windows,dSkrQtjUjxOQmAdQUbi7Z6oQFKPqi6/nsKVpovncQ4hDjQqVsUfoS2NO/XHO+iCwH0De3zrPgPQju3bRiYdzBA==
5.0.0-beta75-rc14 [Build: 1696088917],Windows,GoQG+71nd6b9QUv7vECPDAXGcKEWwrW/YbPaQVNhdFwonbKegBPYKUel8rxuGzqR/uJp3EqXEGV0JyQBVXiEBg==
5.0.0-beta75-rc14 [Build: 1696489500],Windows,6rCkYTY/IQav+zwrXfu9wFEmeuFcNxuHKBdW5aiblX5a0KpF9wzn0qwwKgjZcrzQiH5+r9tmsoB36KSwdxX1Dg==
5.0.0-beta75 [Build: 1696607978],Linux,zk+WtkzXgRWAFIA59ad066AbGsom9QfQW6JpskztbEh4Gri5BlsQ/HKy2xUfQX+7x+A1ukt27BU/6msK7B5bAA==
5.0.0-beta75 [Build: 1696607978],macOS,W9THGtchSxG8Q9DmjC72Ah5wcWVH9/+ZxTH3TZKH3E3NsyjaRwMdjgPvfYVaOb3qYq8Se/HxkYqBbyxSJZFBBg==
5.0.0-beta75 [Build: 1696607978],Windows,0LhX3/Ss9GxjzXzyW6sNvaIGtivWocu9CDH3k0tOqkm8rjiwwQFTu3dCtGEzgBw89QrCXEcKOmZkbgLpechOAg==
5.0.0-beta76-rc1 [Build: 1697033899],macOS,ZjuTP89K3fFgfAHkzg9vbhR+EkSOnkozd1pTXB2MH//jTj9tfyEPwDlzK1TaCV+JKoAsM5WlSmyx//a72S7mDQ==
5.0.0-beta76-rc1 [Build: 1697033899],Windows,CLEscmKTzIkTC9VAQAQ1hIN6eOlSaOjuaWE8EqYThv0aunDzxWRBG9MCNQmdLJ8JgtIM6Ng412x46TOoGAmJBg==
5.0.0-beta76-rc5 [Build: 1697802195],macOS,0aSd/h3YrLvyhywBXtNf2h1ZfSLkHW3jr33EoIsuL6oBepMSvi0nZI3Gx8j4gmLDXtwxE9+wFqrm2vc5VfYjCQ==
5.0.0-beta76-rc5 [Build: 1697802195],Windows,5JXHvuwisq+an9hsgGgA6FW00ENcH5khuMQ1SFyaKgKdByDdvPA7/XbPtxRvUvSUh5brGL4m3CldEQ88ga1mCw==
5.0.0-beta76 [Build: 1698243642],Linux,xXggpgd8+q2Ozk/of+0ciH2v/jp1K83EorMbbiI/J6ywpzQVocFyqQUpOjD6Xoh6K2AV2heFQF/cKoJ0aHwABA==
5.0.0-beta76 [Build: 1698243642],macOS,Buhg/MoJF/pPldGEsesBUpTj+ClIp4xFXX/n+BcOgIS98D/kdO8pTWbk42f+wx24ALEJRwWZCYunaLFXF0iJDA==
5.0.0-beta76 [Build: 1698243642],Windows,zV72PUBNtH7bblwdldd6t/o8hprjepbfR7CbzQCehaYUTID5y/W4IW7e/Qt4v9ip55mycWzADgiqCndMlOVNDA==
5.0.0-qa-77-1 [Build: 1698316110],macOS,ESRePbVvFOl0wUJKoSsFAMV34isnFNfzvUQW6yDoMqa8GNGNPdRw10TxUA+ypTzu4H3A8VEiKgEEm2pdwj/5CA==
5.0.0-beta77 [Build: 1699457285],Windows,id8cERxgKG68YRDcSYCceqekamIZlBmAE/IfwYkpu+a8RC0Gkyyhtn4ZU80ppUfES3GFsGVSSwJ/eci1g+pCBg==
5.0.0-beta77-rc1 [Build: 1700224895],Linux,T101xCL/zRr+iwZJHURKd4DUDTrQSSJ3QsADpMH/Ed8wqXPTqneP6hQk04tKEB39aJCJTDW9W0FT7Pf7vCKLBA==
5.0.0-beta77-rc1 [Build: 1700224895],macOS,0y/hKU/yqkqgUqtn6KXbuRtqQa4DlYQ50Rziwg9k4wAUgAnCm1hts7AvUHrGv5415cJX9czxUAFdIEApPR06CA==
5.0.0-beta77-rc2 [Build: 1700761919],Linux,oFMyO1h6nZOmA0sM9DP+6fy69t+o1drV3inNG+kaH7pZGYqgUg9r/Xu8jGaD2EqZ+Vc7JnO8Zl9Y5n3+HPNkAQ==
5.0.0-beta77-rc2 [Build: 1700761919],Windows,VOTBvsWNSc5MNXDWd/M3JpCB8WzvUlj7+V7EVtUy9cZ8LaK8TyJjIip16YJnVDod73wMW8npyt4oaDrqkzL6Bg==
3.6.3 [Build: 1701166057],Windows,ML3yE6pV0QGyhc8o7k1bgqDSj+5gZIQFMjBNhWJ6L0FtJwniBq8l1wivx3DzgVVCvyRbzfg8MsdV/rjl5sHNCw==
5.0.0-beta77-rc3 [Build: 1701707182],Linux,bS/lxwnq0KSoNl0WggENJ/tuYm+QJF67gSqXykWGAik40iFmM1g7kYOkI5GoBsOxgWJBJB5L4dOjlAyA91BbCw==
5.0.0-beta77 [Build: 1702382332],Linux,sJx9Ss46tDLfsJ6y73csGOXnSIRsSeUFrpHFQ2il/jjM7xWAbp8F8Cnyix/CaNwy7DfZKtgMRcPc8YP0a1r3AA==
5.0.0-beta77 [Build: 1702382332],macOS,E2rqU9M9HvWnqZbki0+blgLmDWneDZZP9TW89lDDuDoQ7GaqXizzNfvr9XJBm8dJwToLfpR9/9kmLhZpHkK3Dg==
5.0.0-beta77 [Build: 1702382332],Windows,Ee6DzP16MUXpdKWjiSY0NGb4thN22/Ks0hwNcaMrWoaadgkM6c5477X0IbGFWVjzTWfjFTEad5noYLUPDWSgCQ==
5.0.0-qa-lm-29 [Build: 1719554519],Windows,mSNqoUO2xaP31n8wrHwuAHHYrgov4ZQmq5OrgvOF0jsEQvTy11Z29j02q3nUA+k9TrXyG12CMYVUWfe8ltneBg==
5.0.0-qa-puzzle-2-1 [Build: 1723116226],Windows,7Qx8GeSIEvRNZ4D3aNbX0AO67Awj92afgNCgkJ7L0YdcaD0c1HFs0c2Ms6CArTiD8pB/Nxw7QgCsKcpBln1PCg==
5.0.0-beta78-pre-1 [Build: 1724839559],Windows,fy7cW8uGyr7lA/5eqsNztXA2nS0PbFZQgIo2HNMbNPycLWJLA8DNZGafBgsfchx9EF5piNtMsJAs9JSy1Pp8DA==
5.0.0-qa-78-18 [Build: 1724924030],Windows,/86Ug4O5Huvf1fHooxLOqIxOIp2wyyR821wOcXkDkbXawEbsp1K7GcVqPH/cyLbfKO6x4LeCILqsrV4no3pMCg==
5.0.0-qa-78-19 [Build: 1724930118],Windows,m2z53BpS7ocld0/TuasTKe1vXvGB6ZFR9mhdAt5I4j3QZpFlCy3NeObvQEHu+a+4Dr8yFBusdQ6vR8Jf23uyCQ==
5.0.0-beta78-pre-2 [Build: 1725011227],Windows,v6UJ+WoJ/TYQe2MqDfoXcMLPTb2L8KrN03x2WHSdsJY17yn6ofLpMtNuBLa84by+sNi1/b8htf0HdV+6TLKEDg==
5.0.0-qa-78-20 [Build: 1725620142],Windows,hxdPF5JpyHwDb36xlKAls6wgmhGh1OvIeo4PlqVX8a9zzP0NvGVR1O2BUdo7ixFsKqrzeHoHJ7KoVxenvGpLCw==
5.0.0-qa-78-21 [Build: 1726235323],Windows,OiQZT9J/s6kIOX6UUDEB5tu3DrKYz6S7Lay/BaXY6teJcbkIuhBr1MREgmkg8Z+yIEHpIqrV73sUqHD2vk+lAg==
5.0.0-qa-78-22 [Build: 1726816276],Windows,dfh0I4RAn1OSy6GrlSmStLBZWutnmUEg7D4tWvzC668p3FBsm7az/CexueslYeoXKgFj871k4F/CyDCgKtCUBA==
5.0.0-qa-78-23 [Build: 1727272684],Windows,OkGqYGggz96MOy29Q7kkNi1sWbGkS6B0K//l7E8oixEdS6xdLgW6GmxwcI6DxvwBjVICg0TdO+VhGpRC9RnUCQ==
5.0.0-beta78-pre-5 [Build: 1728287639],Windows,r9IEzCKmd1M5JszuUU02xy1qFkxKAPAHa45mzxakCqibCdzdL5+T6L+OepdbB6xOKSQ+uAyAFJOd6FHX4vJ7BA==
6.0.0-beta2 [Build: 1737468425],Windows,b5mySiqYAd4Lv5TZNflW+G5Gk8y7Woo9YnJfHRjmzhUyMdGfF1O7fSGJzmx2Hpe/PKaY2aDuKKD6lSxbLYlKCw==
6.0.0-beta4.1 [Build: 1779880475],Linux,7A/XVk3u5VSltgVlDzJCNmN+LUzztoaqCbzmaC7s3EENoN6TpEKh2Fz/N4zPVYM/pllU3Ij5K0h6UsSJHj2FCw==
1 version platform hash
1414 3.?.? [Build: 5680278000] Linux Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2gSwRuZi0R+8Laan5ts5CQ==
1415 3.?.? [Build: 5680278000] OS X SttEnjoWE8jqIM6BOHSfiZP9DGjW0EP/ajU4bdKqgGMV4aYq/kzwVA9gxbmdIzV4lbaokvXBqrRjfBHrTVh8Cg==
1416 3.?.? [Build: 5680278000] Windows DX5NIYLvfJEUjuIbCidnoeozxIDRRkpq3I9vVMBmE9L2qnekOoBzSenkzsg2lC9CMv8K5hkEzhr2TYUYSwUXCg==
1417 3.?.? [Build: 5680278000] DEBUG Windows FaA10gndI44f19ZThYJX2OSM8ESrx9/vJ2uY+rON4enzzPsPR9kiPhsUXtMcC5szzTu6F/vLCiNNEhCr70CKCQ==
1418 3.6.0 [Build: 1668022263] Windows jNUeF6ydYPJp6CpoA2Nm8FcmxPTwj8bFJmmzo/Ch2B9L2CU2rrgLJedcQM3NjAncESYYywUiFR0+BsljvaTNAQ==
1419 5.0.0-qa-74-5 [Build: 1680085518] Windows /X5xXLBPrLClWkivAnMJCz+QIBmFk9fFie8sNg69OdN/xwBQrX6naf2IehfxLdd+BBWX/5TsDjuPJqJwhK1FBg==
1420 5.0.0-qa-74-7 [Build: 1681481733] Windows 4qdm8R3gNHlXDV9PS2CtV3Fe9SN7Mjgt82X+iZmqwMXk9B0g9vCyK62G7h2nr/qcqSopPXR4652xMsSQPYVvDQ==
1421 3.6.0 [Build: 1681728436] OS X MZzEbAN51fl7FGiF51T32nHz5tySXH3te4EEZip5rImRNX1Ey3bBQkahN1PYhURNAQxAtIupczX5iGMmvKm4DA==
1422 5.0.0-qa-74-8 [Build: 1681821920] Windows wBuvBhPgbvXmtEOavMpF/6X7xvHkd0PcrNmob7nSr5trxi5HFGjzvOZU19p56yzOStI077LvVJcQtjVha2uXCA==
1423 5.0.0-qa-74-10 [Build: 1682065994] Windows fCODC/wSy5xu9VXPjK3MsRur4MqN/mSLcP/DdbQ2u/KNgQmpuQEsVelmbrf5AvJUQ9YhmXyx8aMvTnG9kHSnCQ==
1424 5.0.0-qa-dc-1 [Build: 1682080978] Windows 0p63hM9RbR65x093OWBlS9g0We6lNfYA+IWN99TZ23HXzWXuvfukMK6lIviHJkNSFWCBxhGQFmFi9lttH00vCA==
1425 5.0.0-qa-74-11 [Build: 1682337867] Windows BhUfmE4EX5h9gjKKtfO1JQ61sIdzZfm1IcvA4FNU8BtmA2DSzUJ9uDWFrq60h7lh33wkktDCzlXL7j8PNQChCg==
1426 5.0.0-qa-74-13 [Build: 1682589154] Windows 4OMk6jcMvJc/P3zaojn8+laRQzG/vnmEkWEmTpQzIsTcPzKOu5irT82YpOtlp+BIxFDGb8onygu/turJjHLiDA==
1427 5.0.0-qa-74-14 [Build: 1682680770] Windows bwZm9gRSoUSRTWCcc1N0ZuKs+xznjBKErt3myq9YlXzdC/jkn4miNoinG60Ynbsp1JkU8tAVKy4v8HUBLictAg==
1428 5.0.0-qa-74-15 [Build: 1683039954] Windows MFemYXY5GGg2OYhdRzdhpkn9ujzOMMCZA8QGlPV1GUbhjjtjXuMw5+ydEzLwcgZYpFTod3N6CEz/b/aXwWeyCQ==
1429 3.6.0 [Build: 1683203743] Linux ao52xPYBI8qe57kJJ6KQgQPr0J9w7BhGikkFMqs7pGpsrxLK9ghzOlbu5IZsdct3tNw88S2YB0oFmcCWlx+hCA==
1430 3.6.0 [Build: 1683203743] OS X w/rKVPUul3im2KxVqvL8udZf/o0Yre+92bvACj8hU1x5aNtQkvodXo7CML+4mM6EgifiVCyI8kyo6BtbfeF7Ag==
1431 3.6.0 [Build: 1683203743] Windows Ha73fVhy6+r06Zh3CCx8RVJ1HtHCaABNnTfFbjQPy0dm/e79JFIPZgeC5IvJBltwaiBic/9M+aKBrt+7sNxNDw==
1432 5.0.0-qa-74-17 [Build: 1683295507] Windows hpDc2gHUCHv3HUA1nBray8U8Re/d9XvDUHZkefwMkgeL8L6KizWeo7vZzFguQLYpRPr20B4h0d/A8NAxYxfqAA==
1433 5.0.0-beta74 [Build: 1683627550] Linux M5TTHH2J1erTQKBElj0dz4Lm9N4erZuHxZNjNlbJjDxRC8CYnziveIW0j8DY8NeQaSKHeCTXoL5pDakZtvAODQ==
1434 5.0.0-beta74 [Build: 1683627550] macOS EmwreqEhVhmpGrjPKyNjwuEdWKF+uGTX0syXkq57+klgtcNw9lddPm9lodLTdB5spPGlsx0CJQySvEXlWyXNDg==
1435 5.0.0-beta74 [Build: 1683627550] Windows pipm1uaijQDJKPZgRkhjyLsLG/W9KnjEDWNGvqUkUrSuqrUvfEG4OUsdTOReMb+FJp4xz82n3cwd4HExO5k3Dw==
1436 5.0.0-qa-tr-1 [Build: 1683731563] Windows HmBOKipdW28prdI2FFdmBu/mMXui+zdC0G7769F3bW+nVRfNoVtvJhSUx7/UDeQ9ghHbUIW6q2lCxnQLzsIRCg==
1437 3.6.0 [Build: 1683804569] Linux CqbjoDdeYd83t/u9YUtlQf4rDIf6yEnFInF6nq7GcO02tRXBQlppxHd/ziaTdlpwYrha00goKb2GGWwdrNhFAA==
1438 3.6.0 [Build: 1683804569] OS X sT6ej/41Qk3T0LfXl3+VSm3J7Ck4M/OCTWIRundvOHBRodGLWJtddZuQu7IlXNr9mbJfklarQ4XyyXvXMdjvCw==
1439 3.6.0 [Build: 1683804569] Windows PesaPHU3+aiZMUPzpq8UBKjck77jLw9N+hyZq6JjD4baqns5dmKj4sTfSL9/QROyOLqPICZ+fwkSy5iuuMQEAw==
1440 5.0.0-qa-75-1 [Build: 1684855710] Windows LLfl5sHAfsdepvecADQI9/nx98H+jA/r9pe6fq5CqlRY+MCdVbOphiXy7zZerE5h4lIRqcJtEeAJVIXaNu+LDA==
1441 5.0.0-qa-75-2 [Build: 1685542148] Windows Ir/0IAdrK5dDVDlh6gIRwGZe0DFR9vUNf313cLwHTN1EB9nyO2Bq5yoBjZuGYOdNgcbdgQCBzfKNd4ZpCxxSAg==
1442 3.6.0 [Build: 1685546268] OS X i257nbRzdfvBvgW4IeFoCe8KnCDfoIvtNeORVFVPohKWfFajfoBNYTDa/2/jgHbd97Dzqd+hx8t2ZwPPwgR+Bg==
1443 5.0.0-beta75-rc1 [Build: 1685698093] Windows Jkvyb0PGEmS3/lVfr2x7SFlSZMeopxo7JXBHx8m1pWeDL7XdjYoDPOaIJ6UD1hNxY/wv84fgAwt65Ip2AdP1Dw==
1444 5.0.0-beta75-rc2 [Build: 1686050172] Windows BcULgPFoo2+QTsjD88VH5rONZcABm32fgd5jBNbdkxTaERND/CJI4ZBWS30s5WKN9bi3T6LKUOzcLyN6+gfNDQ==
1445 5.0.0-beta75-rc3 [Build: 1686126230] macOS 38gec16GTEPCeaVw5qM8tU58HWM0HZ20yROR1foT8TRHqsTvoED2gm07xb6KfSHN3//3k1ErMvuS4emNBohcBA==
1446 5.0.0-beta75-rc3 [Build: 1686126230] Windows 1Jj8VSZ8QQ2K5jFiRM2DB6Z12Yi1fFjJ3ng96W/S+zU2VzldrOsuvhO36BOjbWMCcEIWoc45sbHPm+utJtxeAw==
1447 3.6.0 [Build: 1686637110] Linux 8eM1WF1E9+8DeS+Zm6IcidGtuTC0+jtrLRkkiIk+GUA91bVOCyYgrUWNFVftZtFEM4qIOICJhLQopVTIwYJOCQ==
1448 3.6.0 [Build: 1686637110] Windows r21r7w+EGu6F6aruzYiuzv2lP5bX8X4TP2xXBH5Wljz3x/VxOxndN84qA9sPn6QJZFQCtzq+iEb0wfFFM7mYCA==
1449 3.6.0 [Build: 1686731472] Linux MKaey6yCAdQDBHl5ERY24N5bz9CsdypGJfpTC5mNPc0s3Z1zeb8c3g9/w/mlRD+qoK3xlCYt3f25oaFMZofMAA==
1450 3.6.0 [Build: 1686731472] Windows KRYqAaQhnKh/NQ4LrOw8+nVA659NDn+IlOB8hhmKZolIOEDSiijCeDoTVf61t/0Z0y1OWlxABS4X7uWRzvhiDw==
1451 3.6.0 [Build: 1686736529] Linux l1LIP8nreS+y33Hp7SmA6M7kJZZI1KbsN1/Rx9hAAL3Wd6PbEwhLIQHXBkfCI8MizWSAl7NDb+UOuNxAL9GoAg==
1452 3.6.0 [Build: 1686736529] OS X EFU7gHd4QZhwmAojg0Tk/tL9dPiFTcWn40R/6YZCrlzX6t0FSPXiAj93OUf1du+qyy2ly4Lrox/M0u4wOhEDBg==
1453 3.6.0 [Build: 1686736529] Windows kRHYyNCdM5rna2v27LyPerCeNd1s76h0KfpLSmLQk3Bzkrg/NCBzpj0WofE1cvbQ2Qm/41d/mUIMxIfXJ/+hCg==
1454 3.6.0 [Build: 1686744367] Linux toUkg41DTfeCfWgqqxSeb8eDzri2PsjRNIcHsFxr0d7nLCTYGoSFfQjme84FjMYtvYloMVAk/gx5Nt+hWE+ZBg==
1455 3.6.0 [Build: 1686744367] Windows VXx9yKF0ZaBMqlU285hPLxaCgH1N8OwKjU52A0EdulFmEeLYYQeJI/7139hno0Ph8kGT6nxoDRKtw0yn9woNAQ==
1456 3.6.0 [Build: 1686749764] Linux TccRBHwn5LSA0lfpa2B42QmfCOiG+MqqyhlOqy5RcuRQNUGPD0e47lUz+Z/8+Gsdc1TPG4+vYlRl8+v2v+26Aw==
1457 3.6.0 [Build: 1686749764] OS X g8H7Op8eCrn0wHutuD/SlmUcZPmkSlFUBhvZpSgm9kuQl4dapzKJq2anI5jDwRs/ooBm/wrIlSiWI6HXuOPZDA==
1458 3.6.0 [Build: 1686749764] Windows gfzG6CfwNYeqrjT68s7ahPd24A/XS0P8LLAB7hrE54MnrlO12RiflD2w69VZ7EYlqnd9GAiVzdGJHCmCFWtlAQ==
1459 5.0.0-beta75-rc4 [Build: 1687777367] Linux DCZXmwc6xocEuzvS+f+qyQLwN8FLdNqyDTAjdOfy1y8JeO8VmIlNwRFd7X0D0Q51kqPNPIB7Jbh4yiwySHjhDw==
1460 5.0.0-beta75-rc4 [Build: 1687777367] macOS xgV8yX/XS3qVXshur/PbsquRIbPvz3w+hJL905nQQBwbniSGvKxAUcTJompBgECG989hf6nW+2GApbf8p70RBw==
1461 5.0.0-beta75-rc4 [Build: 1687777367] Windows wIGrljvdCMZX3XJoe0rWTA/nNZuXVC6z8kUvDw1gi9YxyM6AxmsleqOzjZ3zY5Ii7cRU8slxNAh4ERLcHEPQDg==
1462 5.0.0-beta75-rc5 [Build: 1687944933] Windows 1fQu13pX9jdR5oJ4yaqasfoWrcySvwocstrOQOZLZjB+0nUtKMYW4Kp2DYHuIoTlvuWiiF7pYc7YK4bOUWdlAA==
1463 3.6.1 [Build: 1689766945] Linux fjR+/+EsahBSG/qGjcTTUVIyn/w7W6h7uy9YUebYzRbtWIxxv69ZD4k7Y4Z1OS9+cuB/Nbtg05J2Upt2oK/qCg==
1464 3.6.1 [Build: 1689766945] Windows +6Tcswj4E40ablTifyXIA3UDEY+359hxjEVx+Tb+xha08CiSwpzSpFndS8GCs8z0QICVKUZBwhVfGfePm00vDw==
1465 3.6.1 [Build: 1689949736] Linux yM9tjby+KBrov9dyNLM1I1PZXDBK2fdwR8ylvKdZJc/DaL5GqnoBAGLkFmzOIl//u8VMbXspCDWb/PbvOS2gAg==
1466 3.6.1 [Build: 1689949736] Windows 30JdFX5zLrHx3uKsb55vpdlS6DO36bVRSOewzOlTV70LS4X0dVMZp64EzDZY8ZR2woAAjZ8ZR/rIKt4JlNnKDg==
1467 3.6.1 [Build: 1690193193] Linux UAcE5h5FgPcdChWTtiO816HX8f2qdoDcDEw6crbJ96Yo7rp1Bt+qx/rkKK9bzlVWMhOd4fI7pr++1XaPkEBnAQ==
1468 3.6.1 [Build: 1690193193] OS X P+KOw42V8K0nN5FbGItCaJzrDuWcRgfE3MRzrtbYAhRMTXHzRxvwLkoLM7+vKTW135NtWZlKbZuDAvxgwhSLBg==
1469 3.6.1 [Build: 1690193193] Windows I5uwVK2CZa9aXblVQPUKGbjNYoE2eaUPujK8sVGWAUsPhmGySTvSkP70jrpX8pUgQdtHwUOl3gvrAH6+moNeDQ==
1470 5.0.0-beta75-rc7 [Build: 1690443874] Windows dvpImL6c5RMVxPV/jNNG3DncR8QlQcqWKBQCDiE89KQpZ/q4kRJkAlje0Pgoqk8BT/2WQWaUixqctfOGNPxNBA==
1471 3.6.1 [Build: 1690811573] Windows aWKpb0eAiI6FndcOBw+OixzripgCENMlM5gwKuRhdqtOdWAEYI5Luz8sGQ77yWC1RlQ1llxHcqhjNcJ8qMVcAw==
1472 3.6.1 [Build: 1690872913] Windows +YmPaYUBL4F9+TgxyFhlT8qIi1Ym+So4NNMcuohla/u4kfJCGabZ1vDF4cIOAghIqWfO+bQ0OkORZrCBdpi2Cw==
1473 5.0.0-beta75-rc8 [Build: 1690875928] Windows 1xI3XWPzHxz5zD4OIZDvJteHXOHcxliqCGh/lifvzA6Gb+/GhkcPGj5RqmlIHPKHJFAozbB0UhvTuJcTU5HGDg==
1474 5.0.0-qa-75-4 [Build: 1690964581] Windows 3o5M5JegEvtXwGHMdhUSR+PbaXTIoinUI1GGgoXrGi2tYNUvaguiYYlsak4z8twpgzp68L0KaoA4nz4DyNX9Aw==
1475 3.6.2 [Build: 1690976575] Linux iSJZ2tmUsUhCuB3G/7SCgM+JNZe3Jb/KSxFNr+0FDgg8r5t4JKGBD0SPl/cdDMqNqXmG9zEHi0XmuVl9lysoCg==
1476 3.6.2 [Build: 1690976575] OS X 0VegJZtWI25+RXM3J6jNfskqEgM8f4CyYrrz0IXuSK8azRQ3AMWH7YgSnrotoIX1q7aDhnTulk9eChKSPoKVCQ==
1477 3.6.2 [Build: 1690976575] Windows OyuLO/1bVJtBsXLRWzfGVhNaQd7B9D4QTolZm14DM1uCbSXVvqX3Ssym3sLi/PcvOl+SAUlX6NwBPOsQdwOGDw==
1478 5.0.0-qa-75-8 [Build: 1691162334] macOS jJLCUYbKDDtPB56YGtUSK+EjrY3LxoOAWVLHKIc/Li4UAFNL9iaq5gRvHF+cfJHyGg0keg2SEVr1+TfCEDG4Dw==
1479 5.0.0-qa-75-8 [Build: 1691162334] Windows yLHN6dcol32mrRoi2ZMYDYsn9XPMncp79PwcCHxFC+8CuaxhOSq7/iXUPwhsdqvUQzyvstq1hCaG9/MLn8G/Dg==
1480 5.0.0-beta75-rc10 [Build: 1691405422] Windows ETFP63u2QoQzmb1vHyRC+KxAAZKWq1PEpKfC6ep8A59zptnOtocEbc50wb55GpF7pVv2n5nJP6CV3iv2QauAAA==
1481 5.0.0-qa-75-9 [Build: 1691734909] Windows t0guTMT1lZZI34At9X9kg0/ablk2LEtjePCLXNSCyTGeam3E4l+hjjaLZYx5gFLDX4tQEGqG4Dms96T+xRVTCg==
1482 5.0.0-qa-tr-2 [Build: 1691758984] Windows YmsBwLBmFqrMhlCLGXUcn/qLvHJBrOeg1kRj+xDp7FltLJ6z4G5r6QdPt1sTaalD3TWE9If10i9mQFnP73nCDw==
1483 5.0.0-beta75-rc11 [Build: 1692269983] Windows TraubtepmvLTzCkyZwDgJram2qrdpuPy1hWRhN0ZFwSAnXkBklJjBSMAUO22D/hTAfTeiQaUiFDJThf2aGSJBQ==
1484 5.0.0-beta75-rc12 [Build: 1692273792] Linux UFodfOKNy4uOGnQdL35xlc5XoOkT2xVzn93w2+rshfBQKd63BqCqBcrMDL5We4UGnCdeF7oiUsraWm65qvfDDA==
1485 5.0.0-beta75-rc12 [Build: 1692273792] macOS yRtBZtJrOetbT3IREKlZ7bYCLLDWtl88l6OvbRHsfI0MwgBuaLuZmgA7gAGaNDc4u427XpxD1U4WRRMJ4XXuCA==
1486 5.0.0-beta75-rc12 [Build: 1692273792] Windows fX3auh0DNxFmMmmjKmxJ0bS5T+sI2OActVkppSthJOJ/W1so/WfdxtxavuJgpzFHQ7wqanaJYUajAY0uFnYEDA==
1487 5.0.0-qa-75-10 [Build: 1692281089] Windows 6Tn50hZBDK2v1gAfXvnfVsOvCYiZ5O7t9ae/PGIzTQPYJiK+83CCR9F+NrjaNwrwn8U4fHCm0DvF2qrk6FiEDA==
1488 5.0.0-qa-75-11 [Build: 1692344346] Windows XUiXiYpVQ1lvhscQ0T0STLhzFxgUgPD5yRvHnHa+gl0z62xvSnUYMcaulZu+vu7N7Zx2XD0yXwDt1aAWjmSmAQ==
1489 5.0.0-qa-75-12 [Build: 1692942703] Windows eg20cqWFjsdIv3fP37BPzSsEMAabdXgPwE/iZ0nu8JIUFCx+dDPmD+Yezf4f2cbe+w7MEkPoAMKS5cAOYbG9BQ==
1490 5.0.0-qa-tr-4 [Build: 1692956820] Windows B8tNlJlgST8ITvDXO4m0mBmR+fOur02Dr0MbmYcE1LWOWJfQUk2A5Lyni65NEBdJIg6/D3ihc0US27Yd4sFWAA==
1491 5.0.0-qa-75-14 [Build: 1693548790] Linux VFo+uqfuN636vfO2uplN7MxwjcGgZ7C7a8H78PSMBtPYU5KOh86FNgH3g4TefK5suVza384d9DpPK5sjZBVICA==
1492 5.0.0-qa-75-14 [Build: 1693548790] Windows eBIeiZ9RjIlTT9AVkwXsiHsKrvSkGWfILDbts+A5xGDsIU8nFGl77uXjfNqjM6+Ud2Eb6lKk7NVQrmRWs/b7AQ==
1493 5.0.0-qa-tr-6 [Build: 1693832989] Linux 7S96m1KKKlB2+x4osdky+gdCUnWTlAaoiOQcsmmXPUxxyS/ypTY7tnYRmo2lj/Hx46aI7R0+Z4+vnHLIY9InCw==
1494 5.0.0-qa-tr-6 [Build: 1693832989] Windows IOoZZnLdprCn572p0GRdOJftjQq12pYODanfyqFy9rG+sSQWmDs4Q7LX5aF/K6oRi1dj31I/BaBKxRhcs0ylAQ==
1495 5.0.0-qa-75-16 [Build: 1694525079] Windows mnve3nHnNHCWJD/v1UucjHwYP5iiMcQYozzkQTxY4SlU3HozJb1Zkq9hhXpnaQHE37TODB+7B/fshVo/yWJIAA==
1496 5.0.0-qa-75-17 [Build: 1694593665] Windows dQxRWH4A/RdhuwMQG2fWtbP8aRLJNs9eGrdSHBEd07MEVA29iyNx6J4Ab9pFvzw8rbxC/QsL20G1LGc0ilz7Dg==
1497 5.0.0-qa-75-18 [Build: 1694615531] Windows qDBmGwpP/bskv03tvqCDvK4xXGVpyS7K6cvu06/yMk5rDd05Dba928UfMNh0/Wub/Xy9MfI5gVdA3kSuXJrnDA==
1498 5.0.0-qa-75-19 [Build: 1694699313] Windows KtR3EavFC3d5PBcKFWt7Gd27B6fAG0k4EevugDzjYs2BCg+PFgeZ1DPAQCw8/k0SzewR7i9x/ZedhPC7pvYmDA==
1499 3.6.2 [Build: 1695203293] Linux p4iF1jZ3ZOz9MEkKSZ2bvnFtm9WmUcQy9mAP//erFE4PF1sB6K1CSANrr+3X4B0aZR0u+K2pjnv8kiKsWKQCBQ==
1500 3.6.2 [Build: 1695203293] OS X SOCkLcsxINIGVc+3OQ5Vrmv2BVNNFA9LX5Jj9tqbIiYv2HU6Z5E8AL5+v5G2LDN0F+U55+uW43ezUoYAr1WuBA==
1501 3.6.2 [Build: 1695203293] Windows 4BdaZpdgUSMCuIs8qcloJPNxNlJ4o7QKnxMCRO60mSOTtJZyKjOrGLAmeAEtLIJjcjmdSpycMbQOIV92K2vXAw==
1502 5.0.0-beta75-rc13 [Build: 1695397203] macOS gwgeaGifMO1IIGcPJBbHUklR0m11N+XeuvflfT5CFUh0RE3zbzmV0ehUtg5udX9BU9XxcLh5LsiMQtmUobmUCQ==
1503 5.0.0-beta75-rc13 [Build: 1695397203] Windows dSkrQtjUjxOQmAdQUbi7Z6oQFKPqi6/nsKVpovncQ4hDjQqVsUfoS2NO/XHO+iCwH0De3zrPgPQju3bRiYdzBA==
1504 5.0.0-beta75-rc14 [Build: 1696088917] Windows GoQG+71nd6b9QUv7vECPDAXGcKEWwrW/YbPaQVNhdFwonbKegBPYKUel8rxuGzqR/uJp3EqXEGV0JyQBVXiEBg==
1505 5.0.0-beta75-rc14 [Build: 1696489500] Windows 6rCkYTY/IQav+zwrXfu9wFEmeuFcNxuHKBdW5aiblX5a0KpF9wzn0qwwKgjZcrzQiH5+r9tmsoB36KSwdxX1Dg==
1506 5.0.0-beta75 [Build: 1696607978] Linux zk+WtkzXgRWAFIA59ad066AbGsom9QfQW6JpskztbEh4Gri5BlsQ/HKy2xUfQX+7x+A1ukt27BU/6msK7B5bAA==
1507 5.0.0-beta75 [Build: 1696607978] macOS W9THGtchSxG8Q9DmjC72Ah5wcWVH9/+ZxTH3TZKH3E3NsyjaRwMdjgPvfYVaOb3qYq8Se/HxkYqBbyxSJZFBBg==
1508 5.0.0-beta75 [Build: 1696607978] Windows 0LhX3/Ss9GxjzXzyW6sNvaIGtivWocu9CDH3k0tOqkm8rjiwwQFTu3dCtGEzgBw89QrCXEcKOmZkbgLpechOAg==
1509 5.0.0-beta76-rc1 [Build: 1697033899] macOS ZjuTP89K3fFgfAHkzg9vbhR+EkSOnkozd1pTXB2MH//jTj9tfyEPwDlzK1TaCV+JKoAsM5WlSmyx//a72S7mDQ==
1510 5.0.0-beta76-rc1 [Build: 1697033899] Windows CLEscmKTzIkTC9VAQAQ1hIN6eOlSaOjuaWE8EqYThv0aunDzxWRBG9MCNQmdLJ8JgtIM6Ng412x46TOoGAmJBg==
1511 5.0.0-beta76-rc5 [Build: 1697802195] macOS 0aSd/h3YrLvyhywBXtNf2h1ZfSLkHW3jr33EoIsuL6oBepMSvi0nZI3Gx8j4gmLDXtwxE9+wFqrm2vc5VfYjCQ==
1512 5.0.0-beta76-rc5 [Build: 1697802195] Windows 5JXHvuwisq+an9hsgGgA6FW00ENcH5khuMQ1SFyaKgKdByDdvPA7/XbPtxRvUvSUh5brGL4m3CldEQ88ga1mCw==
1513 5.0.0-beta76 [Build: 1698243642] Linux xXggpgd8+q2Ozk/of+0ciH2v/jp1K83EorMbbiI/J6ywpzQVocFyqQUpOjD6Xoh6K2AV2heFQF/cKoJ0aHwABA==
1514 5.0.0-beta76 [Build: 1698243642] macOS Buhg/MoJF/pPldGEsesBUpTj+ClIp4xFXX/n+BcOgIS98D/kdO8pTWbk42f+wx24ALEJRwWZCYunaLFXF0iJDA==
1515 5.0.0-beta76 [Build: 1698243642] Windows zV72PUBNtH7bblwdldd6t/o8hprjepbfR7CbzQCehaYUTID5y/W4IW7e/Qt4v9ip55mycWzADgiqCndMlOVNDA==
1516 5.0.0-qa-77-1 [Build: 1698316110] macOS ESRePbVvFOl0wUJKoSsFAMV34isnFNfzvUQW6yDoMqa8GNGNPdRw10TxUA+ypTzu4H3A8VEiKgEEm2pdwj/5CA==
1517 5.0.0-beta77 [Build: 1699457285] Windows id8cERxgKG68YRDcSYCceqekamIZlBmAE/IfwYkpu+a8RC0Gkyyhtn4ZU80ppUfES3GFsGVSSwJ/eci1g+pCBg==
1518 5.0.0-beta77-rc1 [Build: 1700224895] Linux T101xCL/zRr+iwZJHURKd4DUDTrQSSJ3QsADpMH/Ed8wqXPTqneP6hQk04tKEB39aJCJTDW9W0FT7Pf7vCKLBA==
1519 5.0.0-beta77-rc1 [Build: 1700224895] macOS 0y/hKU/yqkqgUqtn6KXbuRtqQa4DlYQ50Rziwg9k4wAUgAnCm1hts7AvUHrGv5415cJX9czxUAFdIEApPR06CA==
1520 5.0.0-beta77-rc2 [Build: 1700761919] Linux oFMyO1h6nZOmA0sM9DP+6fy69t+o1drV3inNG+kaH7pZGYqgUg9r/Xu8jGaD2EqZ+Vc7JnO8Zl9Y5n3+HPNkAQ==
1521 5.0.0-beta77-rc2 [Build: 1700761919] Windows VOTBvsWNSc5MNXDWd/M3JpCB8WzvUlj7+V7EVtUy9cZ8LaK8TyJjIip16YJnVDod73wMW8npyt4oaDrqkzL6Bg==
1522 3.6.3 [Build: 1701166057] Windows ML3yE6pV0QGyhc8o7k1bgqDSj+5gZIQFMjBNhWJ6L0FtJwniBq8l1wivx3DzgVVCvyRbzfg8MsdV/rjl5sHNCw==
1523 5.0.0-beta77-rc3 [Build: 1701707182] Linux bS/lxwnq0KSoNl0WggENJ/tuYm+QJF67gSqXykWGAik40iFmM1g7kYOkI5GoBsOxgWJBJB5L4dOjlAyA91BbCw==
1524 5.0.0-beta77 [Build: 1702382332] Linux sJx9Ss46tDLfsJ6y73csGOXnSIRsSeUFrpHFQ2il/jjM7xWAbp8F8Cnyix/CaNwy7DfZKtgMRcPc8YP0a1r3AA==
1525 5.0.0-beta77 [Build: 1702382332] macOS E2rqU9M9HvWnqZbki0+blgLmDWneDZZP9TW89lDDuDoQ7GaqXizzNfvr9XJBm8dJwToLfpR9/9kmLhZpHkK3Dg==
1526 5.0.0-beta77 [Build: 1702382332] Windows Ee6DzP16MUXpdKWjiSY0NGb4thN22/Ks0hwNcaMrWoaadgkM6c5477X0IbGFWVjzTWfjFTEad5noYLUPDWSgCQ==
1527 5.0.0-qa-lm-29 [Build: 1719554519] Windows mSNqoUO2xaP31n8wrHwuAHHYrgov4ZQmq5OrgvOF0jsEQvTy11Z29j02q3nUA+k9TrXyG12CMYVUWfe8ltneBg==
1528 5.0.0-qa-puzzle-2-1 [Build: 1723116226] Windows 7Qx8GeSIEvRNZ4D3aNbX0AO67Awj92afgNCgkJ7L0YdcaD0c1HFs0c2Ms6CArTiD8pB/Nxw7QgCsKcpBln1PCg==
1529 5.0.0-beta78-pre-1 [Build: 1724839559] Windows fy7cW8uGyr7lA/5eqsNztXA2nS0PbFZQgIo2HNMbNPycLWJLA8DNZGafBgsfchx9EF5piNtMsJAs9JSy1Pp8DA==
1530 5.0.0-qa-78-18 [Build: 1724924030] Windows /86Ug4O5Huvf1fHooxLOqIxOIp2wyyR821wOcXkDkbXawEbsp1K7GcVqPH/cyLbfKO6x4LeCILqsrV4no3pMCg==
1531 5.0.0-qa-78-19 [Build: 1724930118] Windows m2z53BpS7ocld0/TuasTKe1vXvGB6ZFR9mhdAt5I4j3QZpFlCy3NeObvQEHu+a+4Dr8yFBusdQ6vR8Jf23uyCQ==
1532 5.0.0-beta78-pre-2 [Build: 1725011227] Windows v6UJ+WoJ/TYQe2MqDfoXcMLPTb2L8KrN03x2WHSdsJY17yn6ofLpMtNuBLa84by+sNi1/b8htf0HdV+6TLKEDg==
1533 5.0.0-qa-78-20 [Build: 1725620142] Windows hxdPF5JpyHwDb36xlKAls6wgmhGh1OvIeo4PlqVX8a9zzP0NvGVR1O2BUdo7ixFsKqrzeHoHJ7KoVxenvGpLCw==
1534 5.0.0-qa-78-21 [Build: 1726235323] Windows OiQZT9J/s6kIOX6UUDEB5tu3DrKYz6S7Lay/BaXY6teJcbkIuhBr1MREgmkg8Z+yIEHpIqrV73sUqHD2vk+lAg==
1535 5.0.0-qa-78-22 [Build: 1726816276] Windows dfh0I4RAn1OSy6GrlSmStLBZWutnmUEg7D4tWvzC668p3FBsm7az/CexueslYeoXKgFj871k4F/CyDCgKtCUBA==
1536 5.0.0-qa-78-23 [Build: 1727272684] Windows OkGqYGggz96MOy29Q7kkNi1sWbGkS6B0K//l7E8oixEdS6xdLgW6GmxwcI6DxvwBjVICg0TdO+VhGpRC9RnUCQ==
1537 5.0.0-beta78-pre-5 [Build: 1728287639] Windows r9IEzCKmd1M5JszuUU02xy1qFkxKAPAHa45mzxakCqibCdzdL5+T6L+OepdbB6xOKSQ+uAyAFJOd6FHX4vJ7BA==
1538 6.0.0-beta2 [Build: 1737468425] Windows b5mySiqYAd4Lv5TZNflW+G5Gk8y7Woo9YnJfHRjmzhUyMdGfF1O7fSGJzmx2Hpe/PKaY2aDuKKD6lSxbLYlKCw==
1539 6.0.0-beta4.1 [Build: 1779880475] Linux 7A/XVk3u5VSltgVlDzJCNmN+LUzztoaqCbzmaC7s3EENoN6TpEKh2Fz/N4zPVYM/pllU3Ij5K0h6UsSJHj2FCw==
+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();
+14 -5
View File
@@ -16,9 +16,9 @@ audio-device = ["voelin-audio/device"]
# voelin-media backends are enabled (e.g. MediaCodec and a registered capture
# source on Android).
media = ["dep:voelin-media"]
# `media` with voelin-media's desktop backends: libvpx, OpenH264 loaded at
# runtime, X11 and PipeWire on Linux. Not for Android (libvpx does not
# cross-compile there).
# `media` with voelin-media's desktop backends: libvpx, dav1d, OpenH264 and
# FFmpeg loaded at runtime, X11 and PipeWire on Linux. Not for Android
# (libvpx does not cross-compile there).
media-desktop = ["media", "voelin-media/default"]
[dependencies]
@@ -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,9 +64,11 @@ 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" }
# `process`: the browser interop test drives Chromium through Node.js.
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
+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]
+642 -34
View File
@@ -38,12 +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::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::info;
use voelin_gateway_proto::client::Login;
use tracing::{debug, info, warn};
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,
@@ -59,15 +71,23 @@ 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>),
/// The gateway could not be reached, or the connection was lost; the
/// next attempt follows by itself.
Retrying(String),
/// Stopped, or the gateway refused the login (the reason).
Disconnected(Option<String>),
}
@@ -77,21 +97,300 @@ 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>,
) {
let reason =
run_inner(&url, &identity, &mut commands, &events).await.err().map(|e| e.to_string());
// 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 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));
}
/// How one connection to the gateway ended.
enum Ended {
/// The session stopped observing.
Stopped,
/// The gateway refused the login: trying again would not help.
Refused(String),
/// Not reached, not logged in yet, or lost (after logging in): try
/// again.
Lost { reason: String, logged_in: bool },
}
/// 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
/// when it is back.
const MAX_UNSENT: usize = 64;
/// What a new connection restores: the chats open at the gateway, and
/// messages written while it was away.
#[derive(Default)]
struct Chats {
open: Vec<ChatTarget>,
unsent: Vec<(ChatTarget, String)>,
}
impl Chats {
/// Note a chat command; it goes out when connected.
fn note(&mut self, cmd: GatewayCmd) {
match cmd {
GatewayCmd::OpenChat(target) => {
if !self.open.contains(&target) {
self.open.push(target);
}
}
GatewayCmd::CloseChat(target) => self.open.retain(|open| *open != target),
GatewayCmd::SendChat(target, text) => {
if self.unsent.len() < MAX_UNSENT {
self.unsent.push((target, text));
}
}
GatewayCmd::RetryNow | GatewayCmd::Stop => {}
}
}
/// Carry out a chat command on a connected gateway.
fn apply(&mut self, client: &GatewayClient, cmd: GatewayCmd) -> Result<(), ClientError> {
match cmd {
GatewayCmd::OpenChat(target) => {
if !self.open.contains(&target) {
self.open.push(target.clone());
}
client.send(ClientMsg::OpenChat { target })
}
GatewayCmd::CloseChat(target) => {
self.open.retain(|open| *open != target);
client.send(ClientMsg::CloseChat { target })
}
GatewayCmd::SendChat(target, text) => client.send(ClientMsg::SendChat { target, text }),
GatewayCmd::RetryNow | GatewayCmd::Stop => Ok(()),
}
}
/// Open the chats again on a new connection and send what waited.
fn restore(&mut self, client: &GatewayClient) -> Result<(), ClientError> {
for target in &self.open {
client.send(ClientMsg::OpenChat { target: target.clone() })?;
}
for (target, text) in std::mem::take(&mut self.unsent) {
client.send(ClientMsg::SendChat { target, text })?;
}
Ok(())
}
/// Wait `delay` before the next attempt, noting the commands that come
/// meanwhile, or until told to try now; false when the session stops
/// observing.
async fn wait(
&mut self,
delay: Duration,
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
) -> bool {
let sleep = tokio::time::sleep(delay);
tokio::pin!(sleep);
loop {
tokio::select! {
() = &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),
},
}
}
}
}
/// Features whose pushes for open chats need [`ClientMsg::Enable`].
const CHAT_EXTENSIONS: [&str; 4] = [
voelin_gateway_proto::feature::HISTORY,
@@ -100,38 +399,155 @@ const CHAT_EXTENSIONS: [&str; 4] = [
voelin_gateway_proto::feature::TOPICS,
];
async fn run_inner(
url: &str,
/// One connection: log in, then relay until it ends.
async fn attempt(
at: &Try<'_>,
identity: &tsclientlib::Identity,
commands: &mut mpsc::UnboundedReceiver<GatewayCmd>,
events: &mpsc::UnboundedSender<GatewayEvent>,
) -> anyhow::Result<()> {
let (client, mut pushes) = match connect(url, identity).await {
Ok(connected) => connected,
Err(ClientError::Gateway { code, message }) => {
let _ = events
.send(GatewayEvent::Push(Box::new(Push::Error { code, message: message.clone() })));
anyhow::bail!("gateway refused login: {message}");
chats: &mut Chats,
told: &mut Told,
) -> Ended {
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}"));
}
// 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);
}
Err(e) => return Err(e.into()),
};
info!(server_name = %client.info().server_name, capabilities = ?client.capabilities(), "gateway connected");
*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(()),
Some(Push::Disconnected(Some(reason))) => anyhow::bail!(reason),
None | Some(Push::Disconnected(None)) => {
return Ok(lost("the gateway closed the connection".into()));
}
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)) => {
@@ -140,25 +556,24 @@ async fn run_inner(
}
// Answers to requests sent without waiting.
Some(Push::Other(_) | Push::Error { code: ErrorCode::UnknownType, .. }) => {}
// The gateway forgot the login (restarted): log in again.
Some(Push::Error { code: ErrorCode::NotAuthenticated, message }) => {
let _ = events.send(GatewayEvent::Push(Box::new(Push::Error {
code: ErrorCode::NotAuthenticated,
message: message.clone(),
})));
anyhow::bail!("gateway session lost: {message}");
return Ok(lost(format!("gateway session lost: {message}")));
}
Some(push) => {
let _ = events.send(GatewayEvent::Push(Box::new(push)));
}
},
cmd = commands.recv() => match cmd {
None | Some(GatewayCmd::Stop) => return Ok(()),
Some(GatewayCmd::OpenChat(target)) => client.send(ClientMsg::OpenChat { target })?,
Some(GatewayCmd::CloseChat(target)) => client.send(ClientMsg::CloseChat { target })?,
Some(GatewayCmd::SendChat(target, text)) => {
client.send(ClientMsg::SendChat { target, text })?;
}
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));
}
}
}
}
}
@@ -388,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,
@@ -733,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);
}
}
+74 -14
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 { .. }
@@ -1044,8 +1105,7 @@ fn command_session(command: &Command) -> SessionId {
/// The app has one rustls crypto provider. With two (aws-lc-rs and ring), a
/// TLS client built without an explicit provider panics: `wss://` gateways
/// did. This test's build has the app's TLS dependencies (reqwest here,
/// tonic through the voelin-myts dev-dependency).
/// did. This test's build has the app's TLS dependencies (reqwest).
#[cfg(test)]
#[test]
fn one_rustls_crypto_provider() {
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,
);
+68 -15
View File
@@ -12,6 +12,8 @@ const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declaration
/// The signed generic version of every platform, tsclientlib's default.
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
/// The client generation claimed where a signed build of it exists.
const CLIENT_GENERATION: &str = "6.";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KnownVersion {
@@ -52,12 +54,17 @@ pub fn known_versions() -> Vec<KnownVersion> {
/// Resolve a `--client-version` argument.
///
/// Accepts `default` (the core native-platform default), an index into [`known_versions`],
/// or `<platform>@<version>` with the exact strings from `voelinctl versions`.
/// Accepts `default` (the core native-platform default), `generic` (the
/// generic `3.?.?` version of the native platform, as before 6.x builds were
/// claimed), an index into [`known_versions`], or `<platform>@<version>` with
/// the exact strings from `voelinctl versions`.
pub fn resolve(spec: &str) -> Result<Option<Version>> {
if spec == "default" {
return Ok(None);
}
if spec == "generic" {
return generic_version(std::env::consts::OS).map(Some);
}
let versions = known_versions();
if let Ok(i) = spec.parse::<usize>() {
let Some(v) = versions.get(i) else {
@@ -74,10 +81,13 @@ pub fn resolve(spec: &str) -> Result<Option<Version>> {
}
}
/// The signed compatibility tuple for the native operating system.
/// The signed compatibility tuple for the native operating system: the
/// newest TeamSpeak 6 client build signed for it, so servers and other
/// clients see a 6.x client (its build is recent enough for any server's
/// minimum client version); where none is signed for the platform, the
/// generic version, whose build passes every minimum.
///
/// The generic version retains the library's minimum-version compatibility.
/// Its version, platform and signature must stay together: the signature does
/// Version, platform and signature must stay together: the signature does
/// not authorize renaming the client or changing its platform.
///
/// Unsupported operating systems return an error rather than claiming another
@@ -87,6 +97,31 @@ pub fn native_version() -> Result<Version> {
}
fn compatibility_version(os: &str) -> Result<Version> {
// TeamSpeak 5 and 6 call macOS "macOS", TeamSpeak 3 "OS X".
let platforms: &[&str] = match os {
"linux" => &["Linux"],
"windows" => &["Windows"],
"macos" => &["macOS", "OS X"],
"android" => &["Android"],
"ios" => &["iOS"],
_ => bail!("no signed compatibility version for operating system {os:?}"),
};
let versions = known_versions();
let newest = versions
.iter()
.filter(|v| platforms.contains(&v.platform.as_str()))
.filter(|v| v.version.starts_with(CLIENT_GENERATION))
.filter_map(|v| Some((build(&v.version)?, v)))
.max_by_key(|(build, _)| *build)
.map(|(_, v)| v);
match newest {
Some(version) => version.to_version(),
None => generic_version(os),
}
}
/// The generic version of the operating system's platform.
fn generic_version(os: &str) -> Result<Version> {
let platform = match os {
"linux" => "Linux",
"windows" => "Windows",
@@ -95,15 +130,18 @@ fn compatibility_version(os: &str) -> Result<Version> {
"ios" => "iOS",
_ => bail!("no signed compatibility version for operating system {os:?}"),
};
// The library's generic version: its build passes servers' minimum client
// version, which a real (older) build such as 3.6.0 may not.
known_versions()
.into_iter()
.find(|version| version.platform == platform && version.version == GENERIC_VERSION)
.find(|v| v.platform == platform && v.version == GENERIC_VERSION)
.with_context(|| format!("missing signed compatibility version for {platform}"))?
.to_version()
}
/// The build number of a version string (`6.0.0 [Build: 1737468425]`).
fn build(version: &str) -> Option<u64> {
version.split_once("[Build: ")?.1.strip_suffix(']')?.parse().ok()
}
/// Truthful product identity, separate from the signed compatibility tuple.
pub fn client_metadata() -> String {
serde_json::json!({
@@ -121,16 +159,19 @@ mod tests {
#[test]
fn native_platform_preserves_complete_signed_tuple() {
for (os, platform) in [
("linux", "Linux"),
("windows", "Windows"),
("macos", "OS X"),
("android", "Android"),
("ios", "iOS"),
for (os, platform, version) in [
// The newest TeamSpeak 6 build signed for the platform.
("linux", "Linux", "6.0.0-beta4.1 [Build: 1779880475]"),
("windows", "Windows", "6.0.0-beta2 [Build: 1737468425]"),
// None signed: the generic version.
("macos", "OS X", GENERIC_VERSION),
("android", "Android", GENERIC_VERSION),
("ios", "iOS", GENERIC_VERSION),
] {
let expected = version;
let version = compatibility_version(os).unwrap();
assert_eq!(version.get_platform(), platform);
assert_eq!(version.get_version_string(), "3.?.? [Build: 5680278000]");
assert_eq!(version.get_version_string(), expected);
assert_eq!(version.get_signature().len(), 64);
let known = known_versions()
.into_iter()
@@ -156,6 +197,14 @@ mod tests {
assert_eq!(metadata["platform"], std::env::consts::OS);
}
#[test]
fn reads_build_numbers() {
assert_eq!(build("6.0.0-beta2 [Build: 1737468425]"), Some(1_737_468_425));
assert_eq!(build(GENERIC_VERSION), Some(5_680_278_000));
assert_eq!(build("3.0.0 [Build: x]"), None);
assert_eq!(build("6.0.0"), None);
}
#[test]
fn parses_all_rows() {
let versions = known_versions();
@@ -169,6 +218,10 @@ mod tests {
#[test]
fn resolves_specs() {
assert!(resolve("default").unwrap().is_none());
if let Ok(generic) = generic_version(std::env::consts::OS) {
assert_eq!(resolve("generic").unwrap(), Some(generic.clone()));
assert_eq!(generic.get_version_string(), GENERIC_VERSION);
}
let by_index = resolve("0").unwrap().unwrap();
let first = &known_versions()[0];
let by_name = resolve(&format!("{}@{}", first.platform, first.version)).unwrap().unwrap();
+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
+254 -5
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 {
@@ -127,7 +131,12 @@ struct FakeGateway {
impl FakeGateway {
async fn start() -> Self {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
Self::start_on(0).await
}
/// A gateway at `port` of the loopback address (0: any free port).
async fn start_on(port: u16) -> Self {
let listener = TcpListener::bind(("127.0.0.1", port)).await.unwrap();
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
let state: Arc<Mutex<State>> = Arc::default();
let st = state.clone();
@@ -146,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> {
@@ -231,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 {
@@ -363,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() },
}
}
@@ -429,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),
});
}
@@ -545,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.
@@ -707,3 +727,232 @@ async fn store_history_off_keeps_the_database_empty() {
drop((engine, history));
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A gateway that is away is tried again by itself and quietly: no error for
/// the user, "connecting" meanwhile, then observing once it is there, with
/// the open chats opened again.
#[tokio::test(flavor = "multi_thread")]
async fn an_unreachable_gateway_is_tried_again_quietly() {
// Nothing listens there yet: the connection is refused.
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let path = temp_db("retry");
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
let mut rx = engine.subscribe();
engine.send(Command::OpenChat { session: 3, target: LOBBY });
engine.send(Command::ObserveGateway {
session: 3,
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
identity: Box::new(tsclientlib::Identity::create()),
});
// 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 {
match rx.recv().await {
Ok(Event::Error { message, .. }) => panic!("the user was told: {message}"),
Ok(Event::State { session: 3, state }) => {
// (Off before observing starts.)
assert!(!connecting || state.observe != ObserveState::Off, "gave up");
connecting |= state.observe == ObserveState::Connecting;
}
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(e) => panic!("{e}"),
}
}
});
assert!(quiet.await.is_err(), "the event stream ended");
assert!(connecting, "never started observing");
// The gateway comes up: observing, and the open chat is opened again.
let gw = FakeGateway::start_on(port).await;
wait(&mut rx, "observing", |e| match e {
Event::Error { message, .. } => panic!("the user was told: {message}"),
Event::State { session: 3, state } if state.observe == ObserveState::Observing => Some(()),
_ => None,
})
.await;
timeout(Duration::from_secs(5), async {
while !gw.requests().contains(&"open_chat".to_owned()) {
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap_or_else(|_| panic!("the chat was not opened again: {:?}", gw.requests()));
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==";
-149
View File
@@ -1,149 +0,0 @@
//! Opt-in account + isolated server interoperability check. No keys are saved.
//! Requires VOELIN_MYTS_LIVE=1, EMAIL/PASSWORD/DEVICE_ID and optional OTP under
//! the VOELIN_MYTS_ prefix; TEST_TS3/TEST_TS6 and QUERY_TS3/QUERY_TS6 give
//! loopback voice/query addresses. QUERY_PASSWORD authenticates local query.
#![cfg(not(target_os = "android"))]
use std::{sync::Arc, time::Duration};
use anyhow::{Context, Result, bail, ensure};
use tokio::{sync::broadcast, time::timeout};
use voelin_core::{Command, Engine, Event, VoiceOptions, VoiceState};
use voelin_myts::{Client, ServerIdentity};
use voelin_query::{Command as QueryCommand, QueryClient, Row};
fn env(name: &str) -> Result<String> {
std::env::var(format!("VOELIN_MYTS_{name}")).with_context(|| format!("missing {name}"))
}
async fn connected(events: &mut broadcast::Receiver<Event>, session_id: u64) -> Result<u16> {
timeout(Duration::from_secs(35), async {
loop {
match events.recv().await? {
Event::State { session, state }
if session == session_id && state.voice == VoiceState::Connected =>
{
if let Some(id) = state.own_client {
return Ok(id);
}
}
Event::Error { message, .. } => bail!("engine: {message}"),
_ => {}
}
}
})
.await?
}
async fn info(query: &QueryClient, client: u16) -> Result<Row> {
query
.send(&QueryCommand::new("clientinfo").arg("clid", client))
.await?
.into_iter()
.next()
.context("clientinfo missing")
}
async fn wait_id(query: &QueryClient, client: u16, expected: &str) -> Result<()> {
timeout(Duration::from_secs(12), async {
loop {
let row = info(query, client).await?;
if row.get("client_myteamspeak_id") == Some(expected) {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
})
.await
.context("server did not report the expected myTS association")?
}
async fn server(identity: Arc<ServerIdentity>, kind: &str) -> Result<()> {
let address = env(&format!("TEST_{kind}"))?;
let query_address = env(&format!("QUERY_{kind}"))?;
// This test is deliberately limited to caller-owned loopback test servers.
ensure!(address.starts_with("127.0.0.1:"), "voice endpoint must be loopback");
ensure!(query_address.starts_with("127.0.0.1:"), "query endpoint must be loopback");
let (query, _) = QueryClient::connect(&voelin_query::Connect {
transport: if kind == "TS3" {
voelin_query::Transport::Raw
} else {
voelin_query::Transport::Ssh
},
addr: query_address,
user: "serveradmin".into(),
secret: Some(env("QUERY_PASSWORD")?),
server_id: Some(1),
server_port: None,
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
})
.await?;
let engine = Engine::start();
let mut events = engine.subscribe();
let result = async {
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
for session in 1..=2 {
engine.send(Command::ConnectVoice {
session,
options: Box::new(VoiceOptions::new(&address, format!("myts-proof-{session}"))),
});
let client = connected(&mut events, session).await?;
let row = info(&query, client).await?;
let version = voelin_core::versions::native_version()?;
ensure!(row.get("client_platform") == Some(version.get_platform()), "wrong platform");
ensure!(
row.get("client_version") == Some(version.get_version_string()),
"wrong version"
);
let metadata: serde_json::Value =
serde_json::from_str(row.get("client_meta_data").context("missing metadata")?)?;
ensure!(metadata["name"] == "Voelin", "wrong client metadata");
ensure!(metadata["platform"] == std::env::consts::OS, "wrong metadata platform");
eprintln!("{kind}: native platform/Voelin metadata passed");
wait_id(&query, client, &identity.id()).await?;
eprintln!("{kind}: signed clientinit myTS ID passed");
// Two fresh connections prove the signature is bound to each handshake.
engine.send(Command::SetMytsIdentity(None));
wait_id(&query, client, "").await?;
engine.send(Command::SetMytsIdentity(Some(identity.clone())));
wait_id(&query, client, &identity.id()).await?;
eprintln!("{kind}: live clear and reattach passed");
engine.send(Command::CloseSession { session });
}
Ok(())
}
.await;
engine.send(Command::SetMytsIdentity(None));
for session in 1..=2 {
engine.send(Command::CloseSession { session });
}
query.quit().await;
result
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires owner-authorized account and isolated loopback servers"]
async fn authenticated_account_and_server_lifecycle() -> Result<()> {
ensure!(env("LIVE")? == "1", "explicit live opt-in required");
let client = Client::new()?;
let login = client
.login(&env("EMAIL")?, &env("PASSWORD")?, env("OTP").ok().as_deref(), &env("DEVICE_ID")?)
.await?;
// Capture every result before deleting the newly created remote session.
let result = async {
client.validate_session(&login.token).await?;
let identity = Arc::new(login.identity.context("server identity unlock failed")?);
let mut failures = Vec::new();
for kind in ["TS3", "TS6"] {
if let Err(error) = server(identity.clone(), kind).await {
failures.push(format!("{kind}: {error:#}"));
}
}
ensure!(failures.is_empty(), "{}", failures.join("; "));
Ok(())
}
.await;
let logout = client.logout(&login.token).await;
logout.context("remote test session revocation failed")?;
result
}
+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 -3
View File
@@ -1,14 +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
ENV CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0
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
+40 -1
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,
@@ -160,7 +172,7 @@ pub static KEYS: &[KeyDef] = &[
"relay.format",
Kind::Str,
"\"[{nick}] {text}\"",
"How posts appear in TeamSpeak; {nick} and {text} are replaced",
"How posts appear when the relay cannot take the user's nickname; {nick} and {text} are replaced",
),
key(
"relay.idle_teardown_secs",
@@ -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))
}
+161 -69
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;
@@ -19,12 +19,13 @@ use voelin_gateway_proto::{
Action, ActivityEntry, ErrorCode, EventInfo, HistoryEntry, PinInfo, StreamEntry, TopicInfo,
UniqueIds, UserRef, feature, identity_level, verify_auth,
};
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor, relay_text};
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool};
use voelin_query::{Command, Connect, QueryClient};
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as};
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,83 +205,78 @@ 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,
groups: GroupResolver,
pub db: Db,
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),
relay_rebuild: Default::default(),
lookup,
lookup_posting: Default::default(),
perms,
groups: GroupResolver::default(),
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)
}
@@ -303,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.
@@ -347,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.
@@ -374,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);
@@ -708,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(())
}
@@ -751,16 +786,20 @@ impl Hub {
}
None => text.to_string(),
};
let full = relay_text(&rt.relay.format, &user.nickname, &relayed);
// Posts go out under the user's nickname; `relay.format` only when the
// session cannot take it.
match target {
ChatTarget::Server => {
for part in voelin_model::split_message(&full, 1024) {
self.lookup
.send(
&Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
)
.await?;
}
let _posting = self.lookup_posting.lock().await;
post_as(
&self.lookup.client().await,
&lookup_nickname(&rt.relay.nickname),
&user.nickname,
&relayed,
&rt.relay.format,
|part| Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", part),
)
.await?;
}
ChatTarget::Channel(cid) => {
if !self.readers.lock().unwrap().contains_key(cid) {
@@ -768,8 +807,7 @@ impl Hub {
self.add_reader(*cid).await?;
self.remove_reader(*cid);
}
// The pool's format is `{text}`: `full` is already formatted.
self.relays().send(*cid, &user.nickname, &full).await?;
self.relays().post(*cid, &user.nickname, &relayed, &rt.relay.format).await?;
}
ChatTarget::Private(_) => unreachable!("checked by require_post"),
}
@@ -797,15 +835,69 @@ impl Hub {
fn new_relay_pool(connect: &Connect, nickname: &str) -> RelayPool {
let mut config = RelayConfig::new(connect.clone());
config.nickname = nickname.to_string();
// Posts are formatted by the hub, with the current settings.
config.format = "{text}".into();
RelayPool::new(config)
}
async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) {
let _ = lookup
.send(&Command::new("clientupdate").arg("client_nickname", format!("{nickname} Gateway")))
.await;
/// The lookup session's own name, given `relay.nickname`.
fn lookup_nickname(nickname: &str) -> String {
format!("{nickname} Gateway")
}
/// 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 {
+66 -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.
@@ -49,19 +49,29 @@ pub struct State {
pub server_groups: HashMap<u64, Vec<u64>>,
/// (target mode, channel of the posting connection, text)
pub posted: Vec<(u8, u64, String)>,
/// The nickname of the posting connection, for each of `posted`.
pub posters: Vec<String>,
/// Nicknames set with clientupdate.
pub nicknames: Vec<String>,
/// The current nickname of each query connection.
names: HashMap<u16, String>,
/// Connections that registered for server events (the observer).
observers: Vec<mpsc::UnboundedSender<String>>,
/// 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 {
@@ -69,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 {
@@ -116,14 +126,50 @@ 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()
}
/// What was posted as `(nickname of the poster, text)`.
pub fn posted_by(&self) -> Vec<(String, String)> {
let s = self.state.lock().unwrap();
s.posters.iter().cloned().zip(s.posted.iter().map(|p| p.2.clone())).collect()
}
async fn connection(self, stream: tokio::net::TcpStream) {
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;
@@ -138,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;
@@ -148,6 +197,7 @@ impl FakeServer {
return;
}
}
_ = kicked.recv() => return,
}
}
}
@@ -184,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(),
@@ -192,6 +248,12 @@ impl FakeServer {
"whoami" => data(vec![format!("client_id={clid} client_channel_id={channel}")]),
"clientupdate" => {
if let Some(nick) = arg("client_nickname") {
let in_use = s.online.iter().any(|c| c.nickname == nick)
|| s.names.iter().any(|(id, n)| *id != clid && *n == nick);
if in_use {
return "error id=513 msg=nickname\\sis\\salready\\sin\\suse\n\r".into();
}
s.names.insert(clid, nick.clone());
s.nicknames.push(nick);
}
ok
@@ -262,6 +324,8 @@ impl FakeServer {
"sendtextmessage" => {
let mode = num("targetmode") as u8;
s.posted.push((mode, *channel, arg("msg").unwrap_or_default()));
let poster = s.names.get(&clid).cloned().unwrap_or_default();
s.posters.push(poster);
ok
}
_ => ok,
+122 -6
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) {
@@ -173,7 +176,11 @@ async fn chat_pins_reactions_topics() {
unreachable!()
};
assert_eq!((id, message.text.as_str()), (hello.id, "hello"));
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] hello".into())));
// Under Bob's name: "Bob1", as Bob is online with voice as "Bob". The
// relay takes its own name back after the post.
assert!(fx.fake.posted().contains(&(2, 1, "hello".into())));
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "hello".into())));
assert_eq!(fx.fake.state.lock().unwrap().nicknames.last().unwrap(), "Chat Relay 1");
// Pins: moderators only by default; Alice is an admin.
assert_eq!(code(b.pin(hello.id).await), ErrorCode::Forbidden);
@@ -213,7 +220,7 @@ async fn chat_pins_reactions_topics() {
assert_eq!(t.id, topic.id);
let in_topic = b.post(LOBBY, "saturday?".into(), Some(topic.id)).await.unwrap();
assert_eq!(in_topic.topic_id, Some(topic.id));
assert!(fx.fake.posted().contains(&(2, 1, "[Bob] [#Plans] saturday?".into())));
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "[#Plans] saturday?".into())));
expect(
&mut c_rx,
"prefixed chat event",
@@ -456,7 +463,7 @@ async fn admin_settings_apply_live() {
// Feature switches reach connected clients at once.
let first = b.post(LOBBY, "one".into(), None).await.unwrap();
assert!(fx.fake.posted().contains(&(2, 1, "<Bob> one".into())));
assert!(fx.fake.posted_by().contains(&("Bob1".into(), "one".into())));
let entry = a.config_set("features.pins".into(), json!(false)).await.unwrap();
assert_eq!(entry.source, voelin_gateway_proto::ConfigSource::Db);
expect(
@@ -506,10 +513,22 @@ async fn admin_settings_apply_live() {
// 0: no limit.
a.config_set("limits.posts_per_window".into(), json!(0)).await.unwrap();
// Relay settings apply without a restart.
// Relay settings apply without a restart. The format is for posts the
// relay cannot make under Bob's name: every variant of it is taken.
for (clid, nick) in [(21, "Bob1"), (22, "Bob2"), (23, "Bob3")] {
fx.fake.add_online(Online {
clid,
cid: 2,
uid: format!("other-{nick}"),
nickname: nick.into(),
server_groups: Vec::new(),
streaming: false,
});
}
a.config_set("relay.format".into(), json!("{nick}: {text}")).await.unwrap();
b.post(LOBBY, "two".into(), None).await.unwrap();
assert!(fx.fake.posted().contains(&(2, 1, "Bob: two".into())));
assert!(fx.fake.posted_by().contains(&("Chat Relay 1".into(), "Bob: two".into())));
a.config_set("relay.nickname".into(), json!("Bridge")).await.unwrap();
for _ in 0..100 {
if fx.fake.state.lock().unwrap().nicknames.iter().any(|n| n == "Bridge 1") {
@@ -567,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}");
}
+10
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 = []
@@ -42,6 +50,8 @@ token_ttl_hours = 720
[relay]
nickname = "Chat Relay"
# Posts go out under the user's nickname; this form only when the relay
# cannot take it.
format = "[{nick}] {text}"
idle_teardown_secs = 120
# Each relay is one query connection; stay below the server's per-IP limit.
+5 -2
View File
@@ -9,7 +9,8 @@ repository.workspace = true
publish.workspace = true
[features]
default = ["vpx", "openh264", "openh264-download", "ffmpeg", "x11", "pipewire", "wlroots", "segment"]
# Every codec backend: desktop builds have all encoders and decoders.
default = ["vpx", "openh264", "openh264-download", "ffmpeg", "av1", "x11", "pipewire", "wlroots", "segment"]
# VP8 and VP9 through the system libvpx (pkg-config `vpx`).
vpx = ["dep:libvpx-native-sys"]
# H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The
@@ -21,7 +22,9 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"]
# VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox, x264,
# SVT-AV1, ... whatever the installed FFmpeg has (see docs/media.md).
ffmpeg = ["dep:libloading", "dep:rustix"]
# AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3).
# AV1 decoding through libdav1d (pkg-config `dav1d` >= 1.3; on Windows
# vcpkg's or our MinGW build, see .github/actions/system-deps and
# docker/windows.Dockerfile).
av1 = ["dep:dav1d"]
# X11 screen capture (Linux).
x11 = ["dep:x11rb", "dep:memmap2", "dep:rustix"]
+1 -3
View File
@@ -21,9 +21,7 @@ impl Dav1dDecoder {
pub fn new() -> Result<Self> {
let mut settings = Settings::new();
settings.set_max_frame_delay(1);
settings.set_n_threads(
std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32),
);
settings.set_n_threads(crate::codec::dav1d_threads() as u32);
let decoder = dav1d::Decoder::with_settings(&settings).map_err(|e| {
Error::CodecUnavailable { codec: Codec::Av1, reason: format!("dav1d: {e}") }
})?;
+20 -1
View File
@@ -25,6 +25,15 @@ use std::sync::Arc;
use crate::frame::VideoFrame;
use crate::{Error, Result};
/// dav1d's threads with a frame delay of one (ours and FFmpeg's `libdav1d`):
/// a quarter of the cores, 1 to 4. They wait on each other where cores are
/// few (on 4 cores, 1080p: 211 fps on one thread, 155-166 on 3 or 4) and
/// help where there are many (32 cores, 1440p: 412 fps on 8).
#[cfg_attr(not(any(feature = "av1", feature = "ffmpeg")), allow(dead_code))]
pub(crate) fn dav1d_threads() -> usize {
std::thread::available_parallelism().map_or(1, |n| (n.get() / 4).clamp(1, 4))
}
#[cfg(feature = "av1")]
pub mod av1;
#[cfg(feature = "openh264")]
@@ -1051,7 +1060,17 @@ mod tests {
assert!(codecs.new_decoder(Codec::H265).is_err());
#[cfg(feature = "vpx")]
{
assert_eq!(codecs.decoders()[..2], [Codec::Vp9, Codec::Vp8]);
// AV1 (dav1d, feature `av1`) comes first where it is built in.
let vpx: Vec<_> = codecs
.decoders()
.into_iter()
.filter(|c| matches!(c, Codec::Vp8 | Codec::Vp9))
.collect();
assert_eq!(vpx, [Codec::Vp9, Codec::Vp8]);
assert_eq!(
codecs.decoders()[0],
if cfg!(feature = "av1") { Codec::Av1 } else { Codec::Vp9 }
);
assert_eq!(codecs.encoder_codecs()[0], Codec::Vp8);
assert_eq!(codecs.pick_encoder(&[Codec::H264, Codec::Vp9]), Some(Codec::Vp9));
assert_eq!(codecs.pick_encoder(&[Codec::Vp8, Codec::Vp9]), Some(Codec::Vp8));
+5 -1
View File
@@ -302,7 +302,11 @@ impl VpxDecoder {
pub fn new(codec: Codec) -> Result<Self> {
let vp9 = is_vp9(codec)?;
check(codec, false)?;
let threads = std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32);
// libvpx's decoder threads spin waiting for each other: on 4 threads
// with another core busy, our 4- and 8-partition 1440p streams
// decoded at 23 and 11 fps, on 2 at 143 and 129.
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
let threads = (cores / 2).clamp(1, 2) as u32;
let decoder =
raw::Decoder::new(vp9, threads).map_err(|message| Error::Decoder { codec, message })?;
Ok(Self { codec, decoder })
+16 -5
View File
@@ -16,7 +16,8 @@
//! Every decoder is set up for live video: slice threads only (frame
//! threads hold one frame per thread before the first picture comes out),
//! dav1d with a frame delay of one, so each frame's picture comes out of
//! the call that decoded it.
//! the call that decoded it. VP8 decodes on one thread: its slice threads
//! split frames by token partitions and wait on each other ([`decoder_threads`]).
//!
//! [`probe`] runs every decoder once per process (in parallel) on a short
//! clip of its codec: three frames of a test picture encoded by this crate's
@@ -196,9 +197,18 @@ fn hw_device(ffmpeg: &Ffmpeg, kind: &'static str) -> std::result::Result<Ptr, St
}
/// Threads of a software decoder: slice (or dav1d's tile and row) threads,
/// which add no delay.
fn decoder_threads() -> usize {
std::thread::available_parallelism().map_or(1, |n| n.get().min(8))
/// which add no delay. Except for VP8, whose slice threads work on the
/// frame's token partitions and wait on each other: a stream of 4 or 8
/// partitions (ours, from a sender with 6 cores or more) decoded 40-80 %
/// slower on 4 threads than on one, too slow for 1440p at 60 fps. dav1d
/// ([`crate::codec::dav1d_threads`]) gets a quarter of the cores.
fn decoder_threads(codec: Codec, decoder: &str) -> usize {
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
match (codec, decoder) {
(Codec::Vp8, _) => 1,
(_, "libdav1d") => crate::codec::dav1d_threads(),
_ => cores.min(8),
}
}
/// A decoder of one [`DecoderSpec`]; see the [module docs](self).
@@ -258,7 +268,8 @@ impl FfmpegDecoder {
// private options object (NULL if the decoder has none).
let private = unsafe { (api.av_opt_child_next)(this.ctx, std::ptr::null_mut()) };
// A hardware decoder's work is on the GPU.
let threads = if spec.is_hardware() { 1 } else { decoder_threads() };
let threads =
if spec.is_hardware() { 1 } else { decoder_threads(spec.codec, spec.decoder) };
this.set(this.ctx, "threads", &threads.to_string());
this.set(this.ctx, "thread_type", "slice");
if spec.decoder == "libdav1d"
+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));
}
}
+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),
+1 -1
View File
@@ -14,4 +14,4 @@ mod relay;
pub use convert::{channel_from_row, client_from_row, delta_from_notification, is_text_message};
pub use observer::{Observer, ObserverConfig, ObserverEvent};
pub use relay::{RelayConfig, RelayEvent, RelayPool};
pub use relay::{RelayConfig, RelayEvent, RelayPool, post_as};
+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)
);
}
}
+221 -40
View File
@@ -3,10 +3,12 @@
//! TeamSpeak only delivers channel chat to clients in that channel, and a
//! client can only post to its own channel. A relay session is an invisible
//! query client moved into the channel; it forwards what is said there and
//! posts messages on behalf of users as `[Nick] text`.
//! posts messages on behalf of users under their own nickname ([`post_as`]).
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;
@@ -23,13 +25,17 @@ const ERR_ALREADY_MEMBER: u32 = 770;
/// TeamSpeak's limit for one text message.
const MAX_MESSAGE_BYTES: usize = 1024;
/// TeamSpeak's limits for a nickname, in characters.
const MIN_NICKNAME_CHARS: usize = 3;
const MAX_NICKNAME_CHARS: usize = 30;
#[derive(Clone, Debug)]
pub struct RelayConfig {
pub connect: Connect,
/// Base nickname; the channel id is appended because nicknames are unique.
pub nickname: String,
/// How posts appear, with `{nick}` and `{text}` placeholders.
/// How posts appear when the relay cannot take the author's nickname
/// ([`post_as`]), with `{nick}` and `{text}` placeholders.
pub format: String,
}
@@ -49,6 +55,11 @@ 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.
posting: Arc<Mutex<()>>,
task: JoinHandle<()>,
}
@@ -63,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> {
@@ -81,18 +108,43 @@ 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"));
};
let own_id = client.own_client_id().await?;
set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await;
let nickname = set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await;
match client.send(&Command::new("clientmove").arg("clid", own_id).arg("cid", channel)).await
{
// Query clients start in the default channel.
@@ -102,72 +154,160 @@ 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, 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
}
/// Post `text` in `channel` on behalf of `nick`, opening a relay if needed.
/// 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
/// relay if needed.
pub async fn send(
&self,
channel: ChannelId,
nick: &str,
text: &str,
) -> voelin_query::Result<()> {
self.post(channel, nick, text, &self.config.format).await
}
/// [`RelayPool::send`] with another fallback `format` than the pool's.
pub async fn post(
&self,
channel: ChannelId,
nick: &str,
text: &str,
format: &str,
) -> voelin_query::Result<()> {
self.open(channel).await?;
let client = match self.sessions.lock().await.get(&channel) {
Some(s) => s.client.clone(),
let (client, nickname, posting) = match self.sessions.lock().await.get(&channel) {
Some(s) => (s.client.clone(), s.nickname.clone(), s.posting.clone()),
None => return Err(voelin_query::Error::Closed),
};
let full = relay_text(&self.config.format, nick, text);
for part in split_message(&full, MAX_MESSAGE_BYTES) {
client
.send(
&Command::new("sendtextmessage")
.arg("targetmode", 2)
.arg("target", channel)
.arg("msg", part),
)
.await?;
}
Ok(())
let _posting = posting.lock().await;
post_as(&client, &nickname, nick, text, format, |part| {
Command::new("sendtextmessage")
.arg("targetmode", 2)
.arg("target", channel)
.arg("msg", part)
})
.await
}
}
/// Post `text` through the query session `client` as if `nick` wrote it: the
/// session takes the nickname for the post (or `nick1`, `nick2`, … while
/// someone has it, as TeamSpeak names a second client of the same name) and
/// goes back to `own_nickname` afterwards, so it never keeps someone's name.
/// When it cannot take any (too short, refused), the post goes out under the
/// session's own name as `format` (`{nick}`, `{text}`). `command` makes the
/// `sendtextmessage` for one part of the text.
///
/// Callers serialize posts through one session: each borrows a nickname.
pub async fn post_as(
client: &QueryClient,
own_nickname: &str,
nick: &str,
text: &str,
format: &str,
command: impl Fn(String) -> Command,
) -> voelin_query::Result<()> {
let taken = take_nickname(client, nick).await;
let full = if taken { text.to_owned() } else { relay_text(format, nick, text) };
let mut result = Ok(());
for part in split_message(&full, MAX_MESSAGE_BYTES) {
result = client.send(&command(part)).await.map(drop);
if result.is_err() {
break;
}
}
if taken && !own_nickname.is_empty() {
set_nickname(client, own_nickname).await;
}
result
}
/// Name the session `nick` or a numbered variant; whether it did.
async fn take_nickname(client: &QueryClient, nick: &str) -> bool {
for nickname in author_nicknames(nick) {
match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await {
Ok(_) => return true,
Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
Err(e) => {
debug!(%e, "could not take the author's nickname");
return false;
}
}
}
false
}
/// The names a post by `nick` may go out under, in order: the nickname
/// itself, then `nick1` to `nick3`, each within TeamSpeak's length limits.
fn author_nicknames(nick: &str) -> Vec<String> {
let nick = nick.trim();
if nick.chars().count() < MIN_NICKNAME_CHARS {
return Vec::new();
}
let fit = |suffix: &str| {
let head: String = nick.chars().take(MAX_NICKNAME_CHARS - suffix.len()).collect();
format!("{}{suffix}", head.trim_end())
};
std::iter::once(fit("")).chain((1..=3).map(|n| fit(&n.to_string()))).collect()
}
/// Nicknames are unique per server; try a few numbered variants. The name is
/// cosmetic, so failing keeps the server-assigned one.
async fn set_nickname(client: &QueryClient, base: &str) {
/// cosmetic, so failing keeps the server-assigned one. The name it got.
async fn set_nickname(client: &QueryClient, base: &str) -> String {
for attempt in 1..=5 {
let nickname = if attempt == 1 { base.to_string() } else { format!("{base} ({attempt})") };
match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await {
Ok(_) => return,
Ok(_) => return nickname,
Err(voelin_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
Err(e) => {
warn!(%e, %nickname, "could not set relay nickname");
return;
return base.to_owned();
}
}
}
warn!(base, "all relay nicknames in use");
base.to_owned()
}
async fn forward(
@@ -176,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)
@@ -191,5 +332,45 @@ 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() });
}
#[cfg(test)]
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"]);
// Too short for TeamSpeak: the relay's own name and the format.
assert!(author_nicknames("Al").is_empty());
let long = "x".repeat(40);
let names = author_nicknames(&long);
assert_eq!(names[0], "x".repeat(30));
assert_eq!(names[1], format!("{}1", "x".repeat(29)));
assert!(names.iter().all(|n| n.chars().count() <= MAX_NICKNAME_CHARS));
// Characters, not bytes.
assert_eq!(author_nicknames(&"é".repeat(31))[0].chars().count(), 30);
}
}
+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
+5
View File
@@ -7,14 +7,19 @@
//! - [`notify`]: desktop notifications
//! - [`paths`]: data, config, cache and state directories
//! - [`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;
pub mod hotkey;
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};
+159
View File
@@ -0,0 +1,159 @@
//! The app's log file: `<state>/logs/voelin.log` for this run, the previous
//! runs' as `voelin.1.log` (the last one) to `voelin.4.log`. A run that writes
//! more than [`MAX_BYTES`] starts a fresh file (the full one moves to
//! `voelin.1.log`), so the logs never fill the disk.
//!
//! ```no_run
//! let log = voelin_platform::logs::LogFile::open(voelin_platform::logs::default_dir())?;
//! // tracing_subscriber::fmt::layer().with_ansi(false).with_writer(move || log.clone())
//! # Ok::<(), std::io::Error>(())
//! ```
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use crate::paths;
/// The log directory's name under the state directory.
pub const DIR_NAME: &str = "logs";
/// Files kept: this run's and the previous runs'.
pub const KEEP: usize = 5;
/// One file's limit.
pub const MAX_BYTES: u64 = 20 << 20;
const NAME: &str = "voelin";
/// The file this process writes, once [`LogFile::open`] succeeded.
static CURRENT: OnceLock<PathBuf> = OnceLock::new();
/// `<state>/logs`.
pub fn default_dir() -> PathBuf {
paths::state_dir().join(DIR_NAME)
}
/// The log file of this run, if there is one.
pub fn current() -> Option<&'static Path> {
CURRENT.get().map(PathBuf::as_path)
}
/// A log file to write to from any thread; clones write to the same file.
#[derive(Clone)]
pub struct LogFile(Arc<Mutex<Inner>>);
struct Inner {
dir: PathBuf,
file: File,
written: u64,
keep: usize,
max: u64,
}
impl LogFile {
/// Start this run's file in `dir`, moving the previous runs' along.
pub fn open(dir: impl Into<PathBuf>) -> io::Result<Self> {
Self::open_with(dir.into(), KEEP, MAX_BYTES)
}
fn open_with(dir: PathBuf, keep: usize, max: u64) -> io::Result<Self> {
std::fs::create_dir_all(&dir)?;
let file = start(&dir, keep)?;
let _ = CURRENT.set(dir.join(file_name(0)));
Ok(Self(Arc::new(Mutex::new(Inner { dir, file, written: 0, keep, max }))))
}
/// The file being written.
pub fn path(&self) -> PathBuf {
self.lock().dir.join(file_name(0))
}
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Write for LogFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut inner = self.lock();
if inner.written > 0 && inner.written + buf.len() as u64 > inner.max {
inner.file = start(&inner.dir, inner.keep)?;
inner.written = 0;
}
let n = inner.file.write(buf)?;
inner.written += n as u64;
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
self.lock().file.flush()
}
}
/// `voelin.log`, `voelin.1.log`, …
fn file_name(n: usize) -> String {
if n == 0 { format!("{NAME}.log") } else { format!("{NAME}.{n}.log") }
}
/// Move the files one along (the oldest goes) and open a new current one.
fn start(dir: &Path, keep: usize) -> io::Result<File> {
let keep = keep.max(1);
let _ = std::fs::remove_file(dir.join(file_name(keep - 1)));
for n in (0..keep - 1).rev() {
let from = dir.join(file_name(n));
if from.exists() {
let _ = std::fs::rename(&from, dir.join(file_name(n + 1)));
}
}
OpenOptions::new().create(true).write(true).truncate(true).open(dir.join(file_name(0)))
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-logs-{name}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
fn read(dir: &Path, n: usize) -> Option<String> {
std::fs::read_to_string(dir.join(file_name(n))).ok()
}
#[test]
fn each_run_gets_a_file_and_the_oldest_go() {
let dir = temp_dir("runs");
for run in 0..4 {
let mut log = LogFile::open_with(dir.clone(), 3, MAX_BYTES).unwrap();
writeln!(log, "run {run}").unwrap();
}
assert_eq!(read(&dir, 0).as_deref(), Some("run 3\n"));
assert_eq!(read(&dir, 1).as_deref(), Some("run 2\n"));
assert_eq!(read(&dir, 2).as_deref(), Some("run 1\n"));
assert_eq!(read(&dir, 3), None, "only three files are kept");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_full_file_starts_over() {
let dir = temp_dir("full");
let log = LogFile::open_with(dir.clone(), 3, 10).unwrap();
let mut writer = log.clone();
writer.write_all(b"12345678\n").unwrap();
// Clones share the file and its size.
log.clone().write_all(b"abcdef\n").unwrap();
assert_eq!(read(&dir, 0).as_deref(), Some("abcdef\n"));
assert_eq!(read(&dir, 1).as_deref(), Some("12345678\n"));
assert_eq!(log.path(), dir.join("voelin.log"));
// A line longer than the limit still goes out whole.
writer.write_all(b"a line longer than ten bytes\n").unwrap();
assert_eq!(read(&dir, 0).as_deref(), Some("a line longer than ten bytes\n"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+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();
+4 -3
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"
@@ -49,8 +49,9 @@ tsclientlib = { path = "../proto/tsclientlib" }
# Desktop: the keyring for passwords, stream media with libvpx, OpenH264, X11
# 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"] }
+394 -49
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};
@@ -97,9 +98,6 @@ fn default_secrets() -> Box<dyn Secrets> {
#[cfg(not(target_os = "android"))]
impl Secrets for FallbackSecrets {
fn get(&self, key: &str) -> voelin_store::Result<Option<String>> {
if key.starts_with("myts/") {
return self.keyring.get(key);
}
match self.memory.get(key)? {
Some(v) => Ok(Some(v)),
None => Ok(self.keyring.get(key).unwrap_or(None)),
@@ -107,9 +105,6 @@ impl Secrets for FallbackSecrets {
}
fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> {
if key.starts_with("myts/") {
return self.keyring.set(key, value);
}
if let Err(error) = self.keyring.set(key, value) {
warn!(%error, "keyring unavailable, keeping the secret for this session only");
return self.memory.set(key, value);
@@ -118,9 +113,6 @@ impl Secrets for FallbackSecrets {
}
fn delete(&self, key: &str) -> voelin_store::Result<()> {
if key.starts_with("myts/") {
return self.keyring.delete(key);
}
let _ = self.keyring.delete(key);
self.memory.delete(key)
}
@@ -144,7 +136,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 +165,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 +178,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 +192,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 +210,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 +265,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 +280,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 +296,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 +309,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 +325,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 +338,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 +366,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 +377,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 +485,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 +517,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,33 +533,35 @@ 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 {
#[cfg(not(target_os = "android"))]
pub runtime: tokio::runtime::Handle,
#[cfg(not(target_os = "android"))]
pub myts: crate::myts::Account,
pub ui: slint::Weak<MainWindow>,
pub store: Store,
pub secrets: Box<dyn Secrets>,
@@ -430,6 +572,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 +596,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,
@@ -470,6 +625,8 @@ pub(crate) struct App {
pub demo: bool,
/// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs).
pub demo_ui: bool,
/// Servers whose gateway was looked up in this run (`discover_gateway`).
pub gateways_looked_up: HashSet<i64>,
/// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work.
pub autoshare: bool,
/// `VOELIN_OPEN=client`: open the volume dialog of the first other client.
@@ -485,6 +642,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! {
@@ -641,6 +800,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"))]
@@ -659,10 +821,6 @@ pub fn run(options: RunOptions) -> Result<()> {
let mut video = Video::new(&dir, settings.openh264);
video.set_decoder_preference(decoder_preference(&prefs));
let app = App {
#[cfg(not(target_os = "android"))]
runtime: runtime.clone(),
#[cfg(not(target_os = "android"))]
myts: Default::default(),
ui: ui.as_weak(),
store,
// The sample data of VOELIN_DEMO_UI never reaches the system keyring.
@@ -676,6 +834,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,
@@ -688,6 +847,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,
@@ -699,6 +862,7 @@ pub fn run(options: RunOptions) -> Result<()> {
stream_volume: 100.0,
demo: switches.demo_stream,
demo_ui: switches.demo_ui,
gateways_looked_up: HashSet::new(),
autoshare: switches.autoshare,
open_client_pending: switches.open_client,
notices_loaded: false,
@@ -706,23 +870,29 @@ 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();
app.refresh_home();
app.refresh_notices();
app.refresh_pages();
#[cfg(not(target_os = "android"))]
app.start_myts();
if app.demo {
app.start_demo();
}
@@ -761,6 +931,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 {
@@ -780,6 +954,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())
@@ -840,6 +1028,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");
@@ -852,6 +1053,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 {
@@ -884,19 +1087,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) {
@@ -904,6 +1127,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();
@@ -912,6 +1141,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;
@@ -928,9 +1158,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();
@@ -977,6 +1226,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);
}
@@ -998,8 +1250,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();
@@ -1011,7 +1263,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) {
@@ -1022,12 +1274,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 } => {
@@ -1042,6 +1295,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}"));
@@ -1074,3 +1330,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 -10
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>();
@@ -23,18 +23,16 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_disconnect_voice(|| {
with_app(|app| app.command(|session| Command::DisconnectVoice { session }));
});
bridge.on_toggle_observe(|| {
with_app(|app| app.toggle_observe());
});
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));
});
@@ -49,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));
});
@@ -59,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);
});
}
+3 -20
View File
@@ -6,26 +6,6 @@ use crate::app::{Bridge, MainWindow, with_app};
pub(super) fn wire(ui: &MainWindow) {
let bridge = ui.global::<Bridge>();
#[cfg(not(target_os = "android"))]
{
bridge.on_myts_login(|email, password, otp| {
with_app(|app| {
app.myts_login(email.to_string(), password.to_string(), otp.to_string())
});
});
bridge.on_myts_logout(|| {
with_app(|app| app.myts_logout());
});
bridge.on_myts_dismiss(|| {
with_app(|app| app.myts_dismiss());
});
bridge.on_myts_retry(|| {
with_app(|app| app.myts_retry());
});
bridge.on_myts_portal(|action| {
with_app(|app| app.myts_portal(action));
});
}
bridge.on_open_settings(|| {
with_app(|app| app.open_settings());
});
@@ -50,6 +30,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));
});
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff. Show more