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
This commit is contained in:
Claude committed 2026-10-06 18:28:09 +00:00
1 parent 1c2d5efd3a
commit 79a12654c8
56 files changed
+7405 -672

No files matched your search

+48 -2
View File
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::sync::{broadcast, mpsc};
use voelin_query::{Command, escape};
/// Permission ids the fake server uses.
@@ -60,12 +60,18 @@ pub struct State {
/// Relay connections by channel.
relays: Vec<(u64, mpsc::UnboundedSender<String>)>,
next_clid: u16,
/// Permission lookups (`permsid`) to refuse for flooding, and how often.
refusals: HashMap<String, usize>,
/// The commands received, in order (`login` left out).
commands: Vec<String>,
}
#[derive(Clone)]
pub struct FakeServer {
pub addr: SocketAddr,
pub state: Arc<Mutex<State>>,
/// Ends every open connection, like a server restart.
kick: broadcast::Sender<()>,
}
impl FakeServer {
@@ -73,7 +79,7 @@ impl FakeServer {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let state = Arc::new(Mutex::new(State { next_clid: 100, ..Default::default() }));
let server = Self { addr, state };
let server = Self { addr, state, kick: broadcast::channel(1).0 };
let s = server.clone();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
@@ -120,6 +126,35 @@ impl FakeServer {
}
}
/// Answer looking up permission `permsid` with the flood protection's
/// refusal, the next `times` times.
pub fn refuse(&self, permsid: &str, times: usize) {
self.state.lock().unwrap().refusals.insert(permsid.to_string(), times);
}
/// The commands received so far, in order (`login` left out).
pub fn commands(&self) -> Vec<String> {
self.state.lock().unwrap().commands.clone()
}
/// An observer connection is registered for server events.
pub fn observed(&self) -> bool {
!self.state.lock().unwrap().observers.is_empty()
}
/// Channels with a relay listening.
pub fn relayed_channels(&self) -> Vec<u64> {
self.state.lock().unwrap().relays.iter().map(|(c, _)| *c).collect()
}
/// Drop every query connection, as a restarting server does.
pub fn drop_connections(&self) {
let mut s = self.state.lock().unwrap();
s.observers.clear();
s.relays.clear();
let _ = self.kick.send(());
}
pub fn posted(&self) -> Vec<(u8, u64, String)> {
self.state.lock().unwrap().posted.clone()
}
@@ -134,6 +169,7 @@ impl FakeServer {
let (r, mut w) = stream.into_split();
let mut lines = BufReader::new(r).lines();
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
let mut kicked = self.kick.subscribe();
let clid = {
let mut s = self.state.lock().unwrap();
s.next_clid += 1;
@@ -148,6 +184,9 @@ impl FakeServer {
line = lines.next_line() => {
let Ok(Some(line)) = line else { return };
let Some(cmd) = Command::parse(&line) else { continue };
if cmd.name != "login" {
self.state.lock().unwrap().commands.push(line.clone());
}
let reply = self.answer(&cmd, clid, &mut channel, &tx);
if w.write_all(reply.as_bytes()).await.is_err() {
return;
@@ -158,6 +197,7 @@ impl FakeServer {
return;
}
}
_ = kicked.recv() => return,
}
}
}
@@ -194,6 +234,12 @@ impl FakeServer {
]),
"permidgetbyname" => {
let name = arg("permsid").unwrap_or_default();
if let Some(left @ 1..) = s.refusals.get_mut(&name) {
*left -= 1;
return "error id=524 msg=client\\sis\\sflooding \
extra_msg=please\\swait\\s1\\sseconds\n\r"
.into();
}
match PERMS.iter().find(|(n, _)| *n == name) {
Some((_, id)) => data(vec![format!("permsid={name} permid={id}")]),
None => "error id=2 msg=invalid\\spermission\n\r".into(),
+102 -2
View File
@@ -26,6 +26,7 @@ const LOBBY: ChatTarget = ChatTarget::Channel(1);
struct Fixture {
fake: FakeServer,
boot: crate::config::Bootstrap,
hub: Arc<Hub>,
url: String,
dir: std::path::PathBuf,
@@ -80,6 +81,7 @@ impl Fixture {
});
}
let layers = Layers { file: file_values(&toml).unwrap(), ..Default::default() };
let boot = layers.bootstrap().unwrap();
let hub = Hub::start(layers).await.unwrap();
// Wait for the observer's first snapshot.
for _ in 0..100 {
@@ -90,9 +92,10 @@ impl Fixture {
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
let app = crate::router(hub.clone());
let app = crate::router(crate::App::started(boot.clone(), hub.clone()))
.into_make_service_with_connect_info::<std::net::SocketAddr>();
tokio::spawn(async move { axum::serve(listener, app).await });
Self { fake, hub, url, dir, people }
Self { fake, boot, hub, url, dir, people }
}
fn people(&self) -> (&Person, &Person, &Person) {
@@ -583,3 +586,100 @@ async fn tells_apps_where_it_is() {
let fx = Fixture::start("well-known-public", public).await;
assert_eq!(well_known(&fx).await, "wss://gw.example.test/v1");
}
/// The TeamSpeak server drops the gateway's query connections (a restart):
/// logins go on working, through a new lookup connection.
#[tokio::test(flavor = "multi_thread")]
async fn logins_work_after_the_server_dropped_the_gateway() {
let fx = Fixture::start("reconnect", "").await;
let (alice, bob, _) = fx.people();
let (b, mut b_rx) = bob.connect(&fx).await;
b.open_chat(LOBBY).await.unwrap();
b.open_chat(ChatTarget::Server).await.unwrap();
assert!(fx.hub.lookup.is_up());
let old_id = fx.hub.lookup.own_id().unwrap();
fx.fake.drop_connections();
// At once: the login waits for the new connection.
let (a, _a_rx) = alice.connect(&fx).await;
assert!(a.has(feature::ADMIN));
assert!(fx.hub.lookup.is_up());
a.post(ChatTarget::Server, "back again".into(), None).await.unwrap();
assert!(fx.fake.posted().contains(&(3, 1, "back again".into())));
// Bob still reads the lobby: its relay comes back.
for _ in 0..100 {
if fx.fake.relayed_channels().contains(&1) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
fx.fake.say_in_channel(1, "Dave", "dave", "after the restart");
expect(
&mut b_rx,
"relayed after the restart",
|p| matches!(p, Push::Chat { message, .. } if message.text == "after the restart"),
)
.await;
// A restarted server hands out client ids from 1 again: a user may get
// the one the gateway had. Their server chat is not the gateway's own.
assert_ne!(fx.hub.lookup.own_id(), Some(old_id));
for _ in 0..100 {
if fx.fake.observed() {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
fx.fake.notify_observers(&format!(
"notifytextmessage targetmode=3 msg=hi\\sall invokerid={old_id} invokername=Erin \
invokeruid=erin"
));
expect(
&mut b_rx,
"server chat from the gateway's old id",
|p| matches!(p, Push::Chat { message, .. } if message.text == "hi all"),
)
.await;
}
/// The server's flood protection refuses looking up an optional permission,
/// also when asked again after the wait: the gateway asks for no more, which
/// would get it banned for 10 minutes.
#[tokio::test(flavor = "multi_thread")]
async fn optional_permissions_stop_at_the_flood_protection() {
let fake = FakeServer::start().await;
fake.refuse("b_channel_modify_name", 2);
let connect = voelin_query::Connect {
transport: voelin_query::Transport::Raw,
addr: fake.addr.to_string(),
user: "serveradmin".into(),
secret: None,
server_port: None,
server_id: None,
// Taken to be on the allowlist.
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
};
let lookup = crate::lookup::Lookup::open(connect, "Gateway".into()).await;
let ids = crate::perms::PermIds::load(&lookup).await.unwrap();
assert_eq!(ids.subscribe_power, fake::SUBSCRIBE_POWER);
assert_eq!((ids.channel_modify_name, ids.server_modify_name), (0, 0));
let asked = fake.commands();
let count =
|name: &str| asked.iter().filter(|c| c.ends_with(&format!("permsid={name}"))).count();
assert_eq!(count("b_channel_modify_name"), 2, "{asked:?}");
assert_eq!(count("b_virtualserver_modify_name"), 0, "{asked:?}");
}
/// `/health` says what is missing until the gateway is logged in.
#[tokio::test(flavor = "multi_thread")]
async fn health_tells_whether_the_gateway_is_up() {
use axum::extract::State;
use axum::http::StatusCode;
let fx = Fixture::start("health", "").await;
let app = crate::App::started(fx.boot.clone(), fx.hub.clone());
assert_eq!(crate::health(State(app)).await, (StatusCode::OK, "ok".to_string()));
let starting = crate::App::new(fx.boot.clone());
let (status, text) = crate::health(State(starting)).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert!(text.starts_with("starting"), "{text}");
}