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

+39
View File
@@ -130,6 +130,18 @@ pub static KEYS: &[KeyDef] = &[
"null",
"URL clients use, e.g. wss://gw.example.org/v1",
),
boot(
"log.level",
Kind::OptStr,
"null",
"What to log, e.g. \"debug\" or \"info,voelin_query=trace\"; default: RUST_LOG, else \"info\"",
),
boot(
"log.file",
Kind::OptStr,
"null",
"Also write the log to this file (appended; at 20 MB it moves to <name>.1.log, 5 files kept)",
),
boot(
"history.path",
Kind::Str,
@@ -493,6 +505,10 @@ impl Layers {
bind: self.get::<String>("listen.bind")?.parse().context("listen.bind")?,
public_url: self.get("listen.public_url")?,
db_path: self.get("history.path")?,
log_level: self.get::<Option<String>>("log.level")?.filter(|l| !l.trim().is_empty()),
log_file: self
.get::<Option<PathBuf>>("log.file")?
.filter(|p| !p.as_os_str().is_empty()),
})
}
}
@@ -514,6 +530,10 @@ pub struct Bootstrap {
pub bind: SocketAddr,
pub public_url: Option<String>,
pub db_path: PathBuf,
/// Log filter (`log.level`); `None`: `RUST_LOG`, else the default.
pub log_level: Option<String>,
/// Log file (`log.file`), on top of standard output.
pub log_file: Option<PathBuf>,
}
impl Bootstrap {
@@ -524,6 +544,8 @@ impl Bootstrap {
.unwrap_or_else(|| format!("tsgw@{}", self.addr))
}
/// How to open query connections. Connections opened with clones of
/// the result share one flood count, as the server counts them.
pub fn query_connect(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: self.transport,
@@ -751,4 +773,21 @@ mod tests {
assert!(cli_values(&["nope=1".into()]).is_err());
assert!(cli_values(&["history.retention_days=-1".into()]).is_err());
}
#[test]
fn log_settings_are_bootstrap_keys() {
let file = file_values(
"[query]\ntransport = \"ssh\"\naddr = \"127.0.0.1:10022\"\n\
[log]\nfile = \"logs/tsgw.log\"\n",
)
.unwrap();
let env = env_values(|name| (name == "TSGW_LOG_LEVEL").then(|| "debug".into())).unwrap();
let boot = Layers { file, env, ..Default::default() }.bootstrap().unwrap();
assert_eq!(boot.log_level.as_deref(), Some("debug"));
assert_eq!(boot.log_file, Some(PathBuf::from("logs/tsgw.log")));
assert!(key_def("log.level").unwrap().bootstrap);
let none = file_values("[query]\ntransport = \"raw\"\naddr = \"h:1\"\n").unwrap();
let boot = Layers { file: none, ..Default::default() }.bootstrap().unwrap();
assert_eq!((boot.log_level, boot.log_file), (None, None));
}
}
+1
View File
@@ -367,6 +367,7 @@ impl Db {
}
/// Whether `uid` reacted with `emoji`.
#[cfg(test)]
pub fn has_reaction(&self, message_id: i64, emoji: &str, uid: &str) -> rusqlite::Result<bool> {
self.lock()
.conn
+1
View File
@@ -253,6 +253,7 @@ impl Db {
self.0.lock().unwrap_or_else(|e| e.into_inner())
}
#[cfg(test)]
pub fn schema_version(&self) -> rusqlite::Result<i64> {
self.lock().conn.pragma_query_value(None, "user_version", |r| r.get(0))
}
+139 -56
View File
@@ -5,7 +5,7 @@
//! feed are in `features.rs`, the stream directory in `streams.rs`, the
//! background tasks in `tasks.rs`.
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
@@ -21,10 +21,11 @@ use voelin_gateway_proto::{
};
use voelin_model::{ChannelId, ChatMessage, ChatTarget, Presence, ServerFlavor};
use voelin_observer::{Observer, ObserverConfig, RelayConfig, RelayPool, post_as};
use voelin_query::{Command, Connect, QueryClient};
use voelin_query::{Command, Connect};
use crate::config::{Bootstrap, Layers, Runtime};
use crate::config::{Layers, Runtime};
use crate::db::{Db, TokenInfo};
use crate::lookup::Lookup;
use crate::perms::{
ChannelAccess, GroupResolver, PermIds, PermResolver, UserGroups, channel_access, effective,
granted, rule_allows,
@@ -192,7 +193,6 @@ impl Feature {
}
pub struct Hub {
pub boot: Bootstrap,
pub settings: Settings,
pub gateway_id: String,
pub server_uid: String,
@@ -205,7 +205,7 @@ pub struct Hub {
relays: RwLock<RelayPool>,
/// Serializes rebuilding the relay pool.
relay_rebuild: tokio::sync::Mutex<()>,
lookup: QueryClient,
pub(crate) lookup: Arc<Lookup>,
/// One server-chat post at a time: each borrows the poster's nickname.
lookup_posting: tokio::sync::Mutex<()>,
perms: PermResolver,
@@ -214,57 +214,51 @@ pub struct Hub {
events: broadcast::Sender<Arc<HubEvent>>,
/// Readers per relayed channel, and when the last one left.
readers: Mutex<HashMap<ChannelId, (usize, Instant)>>,
/// Our own query clients, whose messages are echoes.
own_clients: Mutex<HashSet<u16>>,
/// Message ids while history is off.
next_message_id: Mutex<i64>,
pub(crate) directory: Mutex<Directory>,
}
impl Hub {
/// Connect to the server, open the database and start the background tasks.
/// Connect to the server, open the database and start the background
/// tasks. Waits for the TeamSpeak server as long as it takes.
pub async fn start(layers: Layers) -> Result<Arc<Self>> {
let started = Instant::now();
let boot = layers.bootstrap()?;
let db = Db::open(&boot.db_path)
.with_context(|| format!("failed to open {}", boot.db_path.display()))?;
let settings = Settings::new(layers, &db)?;
let rt = settings.current();
// Clones share the count of commands for the flood protection.
let connect = boot.query_connect();
let (lookup, _) =
QueryClient::connect(&connect).await.context("query login for lookups failed")?;
let info = lookup.send(&Command::new("serverinfo")).await?;
let info = info.first().context("empty serverinfo")?;
let version = info.get("virtualserver_version").unwrap_or_default();
let is_ts6 = matches!(ServerFlavor::from_version_string(version), ServerFlavor::Ts6(_));
let server_uid =
info.get("virtualserver_unique_identifier").unwrap_or_default().to_string();
let server_name = info.get("virtualserver_name").unwrap_or_default().to_string();
let needed_level = info.parse("virtualserver_needed_identity_security_level").unwrap_or(8);
let channels = lookup.send(&Command::new("channellist").flag("flags")).await?;
let default_channel = channels
.iter()
.find(|r| r.flag("channel_flag_default") == Some(true))
.and_then(|r| r.parse("cid"))
.unwrap_or(1);
let perms = PermResolver::new(PermIds::load(&lookup).await?);
let own_id = lookup.own_client_id().await?;
set_lookup_nickname(&lookup, &rt.relay.nickname).await;
let lookup = Lookup::open(connect.clone(), lookup_nickname(&rt.relay.nickname)).await;
lookup.log_address(boot.allowlisted).await;
let server = ServerFacts::load_until_it_works(&lookup, &connect).await;
let perms = PermResolver::new(server.perm_ids);
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
let relays = new_relay_pool(&connect, &rt.relay.nickname);
let directory = Directory::load(&db);
info!(%server_name, %server_uid, version, is_ts6, "gateway connected to server");
info!(
server_name = %server.name,
server_uid = %server.uid,
version = %server.version,
is_ts6 = server.is_ts6,
default_channel = server.default_channel,
needed_level = server.needed_level,
elapsed_ms = started.elapsed().as_millis() as u64,
"gateway connected to server"
);
let hub = Arc::new(Self {
gateway_id: boot.gateway_id(),
boot,
settings,
server_uid,
server_name,
is_ts6,
needed_level,
default_channel,
server_uid: server.uid,
server_name: server.name,
is_ts6: server.is_ts6,
needed_level: server.needed_level,
default_channel: server.default_channel,
observer,
connect,
relays: RwLock::new(relays),
@@ -276,15 +270,13 @@ impl Hub {
db,
events: broadcast::channel(4096).0,
readers: Default::default(),
own_clients: Mutex::new([own_id].into()),
next_message_id: Mutex::new(0),
directory: Mutex::new(directory),
});
crate::tasks::spawn_all(&hub);
// Apps may log in meanwhile.
for &cid in &rt.relay.pinned_channels {
if let Err(error) = hub.relays().open(cid).await {
warn!(cid, %error, "could not open pinned relay");
}
hub.open_relay_soon(cid);
}
Ok(hub)
}
@@ -306,7 +298,7 @@ impl Hub {
}
pub(crate) fn is_own_client(&self, id: u16) -> bool {
self.own_clients.lock().unwrap().contains(&id)
self.lookup.is_own(id)
}
/// Features for the `hello` message.
@@ -350,26 +342,37 @@ impl Hub {
let pool = new_relay_pool(&self.connect, nickname);
tokio::spawn(crate::tasks::pump_relays(self.clone(), pool.subscribe()));
let old = std::mem::replace(&mut *self.relays.write().unwrap(), pool);
let channels = old.channels().await;
old.close_all().await;
// Also the relays being opened now, which open no more in the old pool.
let channels = old.close_all().await;
drop(old);
set_lookup_nickname(&self.lookup, nickname).await;
self.lookup.set_nickname(&lookup_nickname(nickname)).await;
let pool = self.relays();
for cid in channels {
if let Err(error) = pool.open(cid).await {
warn!(cid, %error, "could not reopen relay");
// A failure is logged by the pool.
if pool.open(cid).await.is_err() && self.relay_wanted(cid) {
let hub = self.clone();
tokio::spawn(async move { hub.reopen_relay(cid).await });
}
}
info!(nickname, "relays renamed");
}
/// Pinned channels changed: open new ones, let removed ones idle out.
pub(crate) async fn apply_pinned_channels(&self, old: &[u64], new: &[u64]) {
let pool = self.relays();
for cid in new.iter().filter(|c| !old.contains(c)) {
if let Err(error) = pool.open(*cid).await {
warn!(cid, %error, "could not open pinned relay");
/// Open a channel's relay in the background, and while that fails, again
/// for as long as it is wanted ([`Hub::reopen_relay`]).
fn open_relay_soon(self: &Arc<Self>, cid: ChannelId) {
let hub = self.clone();
tokio::spawn(async move {
// A failure is logged by the pool.
if hub.relays().open(cid).await.is_err() {
hub.reopen_relay(cid).await;
}
});
}
/// Pinned channels changed: open new ones, let removed ones idle out.
pub(crate) fn apply_pinned_channels(self: &Arc<Self>, old: &[u64], new: &[u64]) {
for cid in new.iter().filter(|c| !old.contains(c)) {
self.open_relay_soon(*cid);
}
for cid in old.iter().filter(|c| !new.contains(c)) {
// The idle teardown closes it once nobody reads it.
@@ -377,6 +380,27 @@ impl Hub {
}
}
/// Someone reads the channel, or it is pinned.
pub(crate) fn relay_wanted(&self, cid: ChannelId) -> bool {
self.runtime().relay.pinned_channels.contains(&cid)
|| self.readers.lock().unwrap().get(&cid).is_some_and(|(n, _)| *n > 0)
}
/// Open a relay the server dropped again, waiting longer after each
/// failure, for as long as it is wanted.
pub(crate) async fn reopen_relay(&self, cid: ChannelId) {
let mut attempt = 0;
while self.relay_wanted(cid) {
attempt += 1;
tokio::time::sleep(self.connect.retry_delay(attempt)).await;
// A failure is logged by the pool.
if self.relays().open(cid).await.is_ok() {
info!(channel = cid, attempt, "relay reopened");
return;
}
}
}
/// Channels whose relay nobody needs any more.
pub(crate) fn idle_relays(&self, rt: &Runtime) -> Vec<ChannelId> {
let idle = std::time::Duration::from_secs(rt.relay.idle_teardown_secs);
@@ -711,7 +735,15 @@ impl Hub {
));
}
}
self.relays().open(cid).await?;
loop {
let pool = self.relays();
match pool.open(cid).await {
// Replaced on the way (a new nickname): open in the new pool.
Err(_) if pool.is_closed() => continue,
result => result?,
}
break;
}
self.readers.lock().unwrap().entry(cid).or_insert((0, Instant::now())).0 += 1;
Ok(())
}
@@ -760,7 +792,7 @@ impl Hub {
ChatTarget::Server => {
let _posting = self.lookup_posting.lock().await;
post_as(
&self.lookup,
&self.lookup.client().await,
&lookup_nickname(&rt.relay.nickname),
&user.nickname,
&relayed,
@@ -811,10 +843,61 @@ fn lookup_nickname(nickname: &str) -> String {
format!("{nickname} Gateway")
}
async fn set_lookup_nickname(lookup: &QueryClient, nickname: &str) {
let _ = lookup
.send(&Command::new("clientupdate").arg("client_nickname", lookup_nickname(nickname)))
.await;
/// What the gateway reads from the server once, at start.
struct ServerFacts {
version: String,
is_ts6: bool,
uid: String,
name: String,
needed_level: u8,
default_channel: ChannelId,
perm_ids: PermIds,
}
impl ServerFacts {
async fn load_until_it_works(lookup: &Lookup, connect: &Connect) -> Self {
let mut attempt = 0;
loop {
attempt += 1;
match Self::load(lookup).await {
Ok(facts) => return facts,
Err(error) => {
let retry_in = connect.retry_delay(attempt);
warn!(
error = format!("{error:#}"),
attempt,
retry_in_s = retry_in.as_secs_f32(),
"could not read the server's settings; trying again"
);
tokio::time::sleep(retry_in).await;
}
}
}
}
async fn load(lookup: &Lookup) -> Result<Self> {
// Failures are logged by the caller.
let info = lookup.send_quiet(&Command::new("serverinfo")).await.context("serverinfo")?;
let info = info.first().context("empty serverinfo")?;
let version = info.get("virtualserver_version").unwrap_or_default().to_string();
let channels = lookup
.send_quiet(&Command::new("channellist").flag("flags"))
.await
.context("channellist")?;
Ok(Self {
is_ts6: matches!(ServerFlavor::from_version_string(&version), ServerFlavor::Ts6(_)),
version,
uid: info.get("virtualserver_unique_identifier").unwrap_or_default().to_string(),
name: info.get("virtualserver_name").unwrap_or_default().to_string(),
needed_level: info.parse("virtualserver_needed_identity_security_level").unwrap_or(8),
default_channel: channels
.iter()
.find(|r| r.flag("channel_flag_default") == Some(true))
.and_then(|r| r.parse("cid"))
.unwrap_or(1),
perm_ids: PermIds::load(lookup).await.context("looking up permission ids")?,
})
}
}
/// Split `text` by a topic format like `[#{topic}] {text}` into title and
+202
View File
@@ -0,0 +1,202 @@
//! Where the log goes: standard output (journald, `docker logs`) and, with
//! `log.file`, a file as well.
//!
//! What is logged comes from `log.level` (`TSGW_LOG_LEVEL`), else
//! `RUST_LOG`, else [`DEFAULT_FILTER`]. The libraries that log every packet
//! stay at warnings unless the filter names them, so `debug` stays readable.
use std::fs::{File, OpenOptions};
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use tracing::warn;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{EnvFilter, fmt};
use crate::config::Bootstrap;
/// What is logged when nothing says otherwise.
pub const DEFAULT_FILTER: &str = "info,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn";
/// Libraries kept at warnings unless a filter names them.
const NOISY: &[&str] = &["russh", "hyper", "h2", "tower", "tungstenite", "tokio_tungstenite"];
/// One log file's limit before it moves aside.
const MAX_BYTES: u64 = 20 << 20;
/// Files kept: the one written and the ones moved aside.
const KEEP: usize = 5;
/// Start logging. Problems with the filter or the file are logged, not
/// fatal. Returns the log file in use.
pub fn init(boot: &Bootstrap) -> Option<PathBuf> {
let rust_log = std::env::var("RUST_LOG").ok();
let (directives, from) = match (&boot.log_level, &rust_log) {
(Some(level), _) => (level.as_str(), "log.level"),
(None, Some(rust_log)) if !rust_log.trim().is_empty() => (rust_log.as_str(), "RUST_LOG"),
_ => (DEFAULT_FILTER, "default"),
};
let (filter, bad_filter) = match EnvFilter::try_new(quiet_noisy(directives)) {
Ok(filter) => (filter, None),
Err(error) => (EnvFilter::new(DEFAULT_FILTER), Some(error)),
};
let ansi = io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none();
let console = fmt::layer().with_ansi(ansi);
let file = boot.log_file.as_deref().map(|path| (path, LogFile::open(path, KEEP, MAX_BYTES)));
let to_file = match &file {
Some((_, Ok(log))) => {
let log = log.clone();
Some(fmt::layer().with_ansi(false).with_writer(move || log.clone()))
}
_ => None,
};
tracing_subscriber::registry().with(filter).with(console).with(to_file).init();
if let Some(error) = bad_filter {
warn!(filter = directives, from, %error, "not a log filter; using the default");
}
match file {
Some((path, Ok(_))) => Some(path.to_path_buf()),
Some((path, Err(error))) => {
warn!(
file = %path.display(),
%error,
"cannot write the log file; logging to standard output only"
);
None
}
None => None,
}
}
/// `directives` with the libraries in [`NOISY`] it does not name at
/// warnings.
fn quiet_noisy(directives: &str) -> String {
let named = |lib: &str| {
directives.split(',').any(|d| {
let target = d.trim().split(['=', '[']).next().unwrap_or_default();
target == lib || target.starts_with(&format!("{lib}::"))
})
};
let mut filter = directives.trim().trim_end_matches(',').to_string();
for lib in NOISY.iter().filter(|lib| !named(lib)) {
filter.push_str(&format!(",{lib}=warn"));
}
filter
}
/// A log file written by appending, also across restarts. When it would
/// grow past its limit it moves to `<name>.1.<ext>` (the older ones one
/// further along, the oldest dropped) and a new one starts. Clones write to
/// the same file.
#[derive(Clone)]
pub struct LogFile(Arc<Mutex<Inner>>);
struct Inner {
path: PathBuf,
file: File,
written: u64,
keep: usize,
max: u64,
}
impl LogFile {
pub fn open(path: &Path, keep: usize, max: u64) -> io::Result<Self> {
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir)?;
}
let file = append(path)?;
let written = file.metadata()?.len();
let inner = Inner { path: path.to_path_buf(), file, written, keep: keep.max(1), max };
Ok(Self(Arc::new(Mutex::new(inner))))
}
}
impl Write for LogFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut inner = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if inner.written > 0 && inner.written + buf.len() as u64 > inner.max {
rotate(&inner.path, inner.keep);
// If no new file can be made, the moved one goes on: moving the
// files along on every line would soon drop them all.
if let Ok(file) = append(&inner.path) {
inner.file = file;
}
inner.written = 0;
}
let n = inner.file.write(buf)?;
inner.written += n as u64;
Ok(n)
}
fn flush(&mut self) -> io::Result<()> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).file.flush()
}
}
fn append(path: &Path) -> io::Result<File> {
OpenOptions::new().create(true).append(true).open(path)
}
/// `tsgw.log` as the `n`th one moved aside: `tsgw.1.log`.
fn moved_aside(path: &Path, n: usize) -> PathBuf {
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
let name = match path.extension() {
Some(ext) => format!("{stem}.{n}.{}", ext.to_string_lossy()),
None => format!("{stem}.{n}"),
};
path.with_file_name(name)
}
/// Move the files one along; the oldest goes.
fn rotate(path: &Path, keep: usize) {
if keep <= 1 {
let _ = std::fs::remove_file(path);
return;
}
let _ = std::fs::remove_file(moved_aside(path, keep - 1));
for n in (1..keep - 1).rev() {
let _ = std::fs::rename(moved_aside(path, n), moved_aside(path, n + 1));
}
let _ = std::fs::rename(path, moved_aside(path, 1));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn noisy_libraries_stay_quiet_unless_named() {
assert_eq!(
quiet_noisy("debug"),
"debug,russh=warn,hyper=warn,h2=warn,tower=warn,tungstenite=warn,tokio_tungstenite=warn"
);
let named = quiet_noisy("info,voelin_query=trace,russh=debug,hyper::proto=info,");
assert!(named.starts_with("info,voelin_query=trace,russh=debug,hyper::proto=info,h2=warn"));
assert!(!named.contains("russh=warn") && !named.contains("hyper=warn"));
assert!(EnvFilter::try_new(quiet_noisy(DEFAULT_FILTER)).is_ok());
assert_eq!(quiet_noisy(DEFAULT_FILTER).matches("russh").count(), 1);
}
#[test]
fn the_file_is_appended_to_and_moved_aside_when_full() {
let dir = std::env::temp_dir().join(format!("tsgw-log-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("logs").join("tsgw.log");
let read = |p: PathBuf| std::fs::read_to_string(p).ok();
LogFile::open(&path, 3, 12).unwrap().write_all(b"start 1\n").unwrap();
// A restart goes on in the same file.
let log = LogFile::open(&path, 3, 12).unwrap();
log.clone().write_all(b"two\n").unwrap();
assert_eq!(read(path.clone()).as_deref(), Some("start 1\ntwo\n"));
// Full: moved aside, and the oldest goes.
log.clone().write_all(b"three\n").unwrap();
log.clone().write_all(b"four 4\n").unwrap();
log.clone().write_all(b"five 5\n").unwrap();
assert_eq!(read(path.clone()).as_deref(), Some("five 5\n"));
assert_eq!(read(dir.join("logs/tsgw.1.log")).as_deref(), Some("four 4\n"));
assert_eq!(read(dir.join("logs/tsgw.2.log")).as_deref(), Some("three\n"));
assert_eq!(read(dir.join("logs/tsgw.3.log")), None, "three files in all");
assert_eq!(moved_aside(Path::new("/var/log/tsgw"), 2), Path::new("/var/log/tsgw.2"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+231
View File
@@ -0,0 +1,231 @@
//! The lookup query connection: logins, permission checks and server chat
//! posts go through it. When the TeamSpeak server drops it (a restart, a
//! network problem) it is opened again, and commands sent meanwhile wait
//! for it a little.
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use tracing::{debug, error, info, warn};
use voelin_query::{Command, Connect, QueryClient, Row, Transport, attempt_worth_a_warning};
/// How long a command waits for a lost connection to come back.
const RECONNECT_WAIT: Duration = Duration::from_secs(5);
pub struct Lookup {
connect: Connect,
client: watch::Sender<QueryClient>,
/// The session's nickname, set again on every new connection.
nickname: Mutex<String>,
/// The connection's client id while it is up: server chat from it is the
/// gateway's own. Not kept across reconnects: after a server restart the
/// old id may be a user's.
own_id: Mutex<Option<u16>>,
}
impl Lookup {
/// Log in, trying until it works, and keep the connection open from
/// then on.
pub async fn open(mut connect: Connect, nickname: String) -> Arc<Self> {
connect.line.label = "lookup".into();
let (client, own_id) = open_until_it_works(&connect, &nickname).await;
let lookup = Arc::new(Self {
connect,
client: watch::channel(client).0,
nickname: Mutex::new(nickname),
own_id: Mutex::new(Some(own_id)),
});
tokio::spawn(keep_open(Arc::downgrade(&lookup)));
lookup
}
/// The connection is up.
pub fn is_up(&self) -> bool {
!self.client.borrow().is_closed()
}
/// The connection's client id, while it is up.
pub fn own_id(&self) -> Option<u16> {
*self.own_id.lock().unwrap()
}
/// The id is the connection's own.
pub fn is_own(&self, id: u16) -> bool {
self.own_id() == Some(id)
}
/// Send a command; when the connection is lost on the way, once more
/// on the new one. A failure is logged with the command's name.
pub async fn send(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
let result = self.send_quiet(cmd).await;
if let Err(error) = &result {
warn!(command = %cmd.name, %error, "ServerQuery command failed");
}
result
}
/// [`Lookup::send`] for callers that log a failure themselves.
pub async fn send_quiet(&self, cmd: &Command) -> voelin_query::Result<Vec<Row>> {
let mut current = self.client.subscribe();
let client = current.borrow_and_update().clone();
match client.send(cmd).await {
Err(error) if lost(&error, &client) => {
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
Ok(Ok(())) => {
let client = current.borrow_and_update().clone();
client.send(cmd).await
}
_ => Err(error),
}
}
result => result,
}
}
/// The connection, after waiting a little for it if it is lost.
pub async fn client(&self) -> QueryClient {
let mut current = self.client.subscribe();
let client = current.borrow_and_update().clone();
if !client.is_closed() {
return client;
}
match tokio::time::timeout(RECONNECT_WAIT, current.changed()).await {
Ok(Ok(())) => current.borrow_and_update().clone(),
_ => client,
}
}
/// Rename the session, now and after reconnects.
pub async fn set_nickname(&self, nickname: &str) {
*self.nickname.lock().unwrap() = nickname.to_string();
set_nickname(&self.client().await, nickname).await;
}
/// Log the address the server sees the gateway's queries come from: it
/// counts the commands of each address for its flood protection, unless
/// the address is in its `query_ip_allowlist.txt`.
pub async fn log_address(&self, allowlisted: bool) {
let Some(own) = self.own_id() else { return };
let Ok(rows) = self.send(&Command::new("clientlist").flag("ip")).await else { return };
let address = rows
.iter()
.find(|r| r.parse::<u16>("clid") == Some(own))
.and_then(|r| r.get("connection_client_ip"));
let Some(address) = address.filter(|a| !a.is_empty()) else {
debug!("the server did not say where the gateway's queries come from");
return;
};
let loopback = address.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
match (allowlisted, loopback) {
(true, _) => info!(
address,
"the TeamSpeak server sees the gateway's queries coming from this address"
),
(false, true) => info!(
address,
hint = "the server's query_ip_allowlist.txt has this address by default; if it still \
does, set query.allowlisted = true so the gateway stops slowing itself down",
"the TeamSpeak server sees the gateway's queries coming from this address"
),
(false, false) => info!(
address,
hint = "add this address to the server's query_ip_allowlist.txt (read again within \
seconds) and set query.allowlisted = true; until then the server's flood \
protection limits the gateway",
"the TeamSpeak server sees the gateway's queries coming from this address"
),
}
}
}
/// The error means the connection is gone, not that the command failed.
fn lost(error: &voelin_query::Error, client: &QueryClient) -> bool {
use voelin_query::Error;
matches!(error, Error::Closed | Error::Io(_) | Error::Ssh(_)) || client.is_closed()
}
/// Wait for the connection to close, open it again, repeat.
async fn keep_open(lookup: Weak<Lookup>) {
loop {
let Some(client) = lookup.upgrade().map(|l| l.client.borrow().clone()) else { return };
client.closed().await;
let Some(lookup) = lookup.upgrade() else { return };
let lost_at = Instant::now();
*lookup.own_id.lock().unwrap() = None;
warn!(addr = %lookup.connect.addr, "lookup query connection lost; reconnecting");
let nickname = lookup.nickname.lock().unwrap().clone();
let (client, own_id) = open_until_it_works(&lookup.connect, &nickname).await;
*lookup.own_id.lock().unwrap() = Some(own_id);
lookup.client.send_replace(client);
info!(down_ms = lost_at.elapsed().as_millis() as u64, "lookup query connection restored");
}
}
/// Open a connection, waiting longer after each failure.
async fn open_until_it_works(connect: &Connect, nickname: &str) -> (QueryClient, u16) {
let started = Instant::now();
let transport = match connect.transport {
Transport::Ssh => "ssh",
Transport::Raw => "raw",
Transport::Http => "http",
};
let mut attempt = 0;
loop {
attempt += 1;
match open_once(connect, nickname).await {
Ok(opened) => {
let elapsed_ms = started.elapsed().as_millis() as u64;
info!(addr = %connect.addr, transport, attempt, elapsed_ms, "query login ok");
return opened;
}
Err(e) => {
let retry_in = connect.retry_delay(attempt);
let retry_in_s = retry_in.as_secs_f32();
let refused = matches!(&e, voelin_query::Error::SshAuth)
|| matches!(&e, voelin_query::Error::Query(q) if q.id == ERR_INVALID_LOGIN);
if refused {
error!(
addr = %connect.addr,
user = %connect.user,
attempt,
retry_in_s,
"the TeamSpeak server refused the query login; check query.user and the password"
);
} else if attempt_worth_a_warning(attempt) {
warn!(
addr = %connect.addr,
error = %e,
attempt,
retry_in_s,
"query login failed; trying again"
);
} else {
debug!(
addr = %connect.addr,
error = %e,
attempt,
retry_in_s,
"query login failed; trying again"
);
}
tokio::time::sleep(retry_in).await;
}
}
}
}
/// `login` with a wrong name or password.
const ERR_INVALID_LOGIN: u32 = 520;
async fn open_once(connect: &Connect, nickname: &str) -> voelin_query::Result<(QueryClient, u16)> {
let (client, _) = QueryClient::connect(connect).await?;
let own_id = client.own_client_id().await?;
set_nickname(&client, nickname).await;
Ok((client, own_id))
}
/// The name is cosmetic: failing keeps the server-assigned one.
async fn set_nickname(client: &QueryClient, nickname: &str) {
let _ = client.send(&Command::new("clientupdate").arg("client_nickname", nickname)).await;
}
+217 -31
View File
@@ -9,6 +9,8 @@ mod config;
mod db;
mod features;
mod hub;
mod logging;
mod lookup;
mod perms;
mod session;
mod settings;
@@ -17,20 +19,27 @@ mod tasks;
#[cfg(test)]
mod tests;
use std::future::IntoFuture;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use anyhow::Result;
use axum::extract::{State, WebSocketUpgrade};
use axum::http::{HeaderMap, header};
use axum::response::IntoResponse;
use anyhow::{Context, Result};
use axum::extract::{ConnectInfo, State, WebSocketUpgrade};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use axum::{Extension, Json, Router};
use clap::Parser;
use tracing::info;
use tracing_subscriber::EnvFilter;
use tokio::sync::watch;
use tracing::{debug, info, warn};
use voelin_query::Transport;
use crate::config::Bootstrap;
use crate::hub::Hub;
use crate::session::Peer;
#[derive(Parser, Debug)]
#[command(version, about)]
@@ -44,54 +53,207 @@ struct Args {
set: Vec<String>,
}
/// How long a WebSocket connection made while the gateway starts waits for
/// the TeamSpeak server before it is refused.
const START_WAIT: Duration = Duration::from_secs(10);
/// How long open connections get to close at shutdown.
const CLOSE_WAIT: Duration = Duration::from_secs(2);
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
)
.init();
let args = Args::parse();
let layers = config::Layers::load(&args.config, &args.set)?;
let bind = layers.bootstrap()?.bind;
let hub = Hub::start(layers).await?;
tokio::spawn(reload_on_hangup(hub.clone()));
let listener = tokio::net::TcpListener::bind(bind).await?;
info!(%bind, "listening");
axum::serve(listener, router(hub)).with_graceful_shutdown(shutdown()).await?;
let boot = layers.bootstrap()?;
let log_file = logging::init(&boot);
info!(
version = env!("CARGO_PKG_VERSION"),
config = %args.config.display(),
bind = %boot.bind,
public_url = boot.public_url.as_deref(),
gateway_id = %boot.gateway_id(),
voice_port = boot.voice_port,
query_transport = transport_name(boot.transport),
query_addr = %boot.addr,
query_user = %boot.user,
query_password = if boot.password.is_some() { "set" } else { "none" },
allowlisted = boot.allowlisted,
db = %boot.db_path.display(),
log_file = log_file.as_ref().map(|p| p.display().to_string()),
"tsgw starting"
);
// Listen at once: apps that come while the TeamSpeak server is not
// reachable yet wait for it a little instead of being turned away.
let listener = tokio::net::TcpListener::bind(boot.bind)
.await
.with_context(|| format!("cannot listen on {}", boot.bind))?;
info!(
bind = %boot.bind,
public_url = boot.public_url.as_deref(),
well_known = boot.public_url.as_deref().unwrap_or("ws://<host the app asked for>/v1"),
"listening"
);
let app = App::new(boot);
let service = router(app.clone()).into_make_service_with_connect_info::<SocketAddr>();
let server = axum::serve(listener, service).with_graceful_shutdown(shutdown(app.clone()));
let mut server = std::pin::pin!(server.into_future());
tokio::select! {
// Stopped before the TeamSpeak server answered.
served = &mut server => return served.context("serving failed"),
hub = Hub::start(layers) => {
let hub = hub?;
app.hub.send_replace(Some(hub.clone()));
tokio::spawn(reload_on_hangup(hub));
}
}
server.await.context("serving failed")?;
app.closed_within(CLOSE_WAIT).await;
Ok(())
}
pub fn router(hub: Arc<Hub>) -> Router {
fn transport_name(transport: Transport) -> &'static str {
match transport {
Transport::Ssh => "ssh",
Transport::Raw => "raw",
Transport::Http => "http",
}
}
/// What the HTTP handlers share.
pub struct App {
boot: Bootstrap,
/// The hub, once the gateway is logged in to the TeamSpeak server.
hub: watch::Sender<Option<Arc<Hub>>>,
/// Turns true at shutdown, which closes the WebSocket connections.
stop: watch::Sender<bool>,
/// WebSocket connections open now, and since the start.
open: AtomicUsize,
connections: AtomicU64,
}
impl App {
fn new(boot: Bootstrap) -> Arc<Self> {
Arc::new(Self {
boot,
hub: watch::channel(None).0,
stop: watch::channel(false).0,
open: AtomicUsize::new(0),
connections: AtomicU64::new(0),
})
}
/// An app for a hub that has started.
#[cfg(test)]
fn started(boot: Bootstrap, hub: Arc<Hub>) -> Arc<Self> {
let app = Self::new(boot);
app.hub.send_replace(Some(hub));
app
}
fn hub(&self) -> Option<Arc<Hub>> {
self.hub.borrow().clone()
}
/// The hub, waiting up to `wait` for it to start.
async fn hub_within(&self, wait: Duration) -> Option<Arc<Hub>> {
let mut hub = self.hub.subscribe();
let started = tokio::time::timeout(wait, hub.wait_for(Option::is_some)).await;
started.ok()?.ok()?.clone()
}
/// Wait for the WebSocket connections to close, at most `wait`.
async fn closed_within(&self, wait: Duration) {
let deadline = Instant::now() + wait;
while self.open.load(Ordering::Relaxed) > 0 && Instant::now() < deadline {
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
}
pub fn router(app: Arc<App>) -> Router {
Router::new()
.route("/v1", get(ws))
.route("/health", get(|| async { "ok" }))
.route("/health", get(health))
.route("/.well-known/tsgw", get(well_known))
.with_state(hub)
.with_state(app)
}
/// `ok` while the gateway is logged in to the TeamSpeak server and watching
/// it; otherwise 503 and what is missing.
async fn health(State(app): State<Arc<App>>) -> (StatusCode, String) {
let Some(hub) = app.hub() else {
let starting = "starting: not logged in to the TeamSpeak server yet";
return (StatusCode::SERVICE_UNAVAILABLE, starting.into());
};
let (query, observer) = (hub.lookup.is_up(), hub.observer.is_connected());
if query && observer {
return (StatusCode::OK, "ok".into());
}
let state = |up| if up { "up" } else { "down" };
let text = format!("query: {}, observer: {}", state(query), state(observer));
(StatusCode::SERVICE_UNAVAILABLE, text)
}
/// Where apps reach this gateway, for those that find it by asking the
/// server's host on the default port (docs/gateway-admin.md): the
/// configured public URL, else this listener as the request reached it.
async fn well_known(State(hub): State<Arc<Hub>>, headers: HeaderMap) -> Json<serde_json::Value> {
let url = hub.boot.public_url.clone().unwrap_or_else(|| {
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("localhost");
format!("ws://{host}/v1")
});
async fn well_known(State(app): State<Arc<App>>, headers: HeaderMap) -> Json<serde_json::Value> {
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok());
let url = app
.boot
.public_url
.clone()
.unwrap_or_else(|| format!("ws://{}/v1", host.unwrap_or("localhost")));
debug!(host, answer = %url, "asked where the gateway is");
Json(serde_json::json!({ "url": url }))
}
async fn ws(State(hub): State<Arc<Hub>>, upgrade: WebSocketUpgrade) -> impl IntoResponse {
async fn ws(
State(app): State<Arc<App>>,
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
headers: HeaderMap,
upgrade: WebSocketUpgrade,
) -> Response {
let text = |name: header::HeaderName| {
headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned)
};
let peer = Peer {
id: app.connections.fetch_add(1, Ordering::Relaxed) + 1,
addr: connect_info.map(|Extension(ConnectInfo(addr))| addr),
forwarded_for: text(header::HeaderName::from_static("x-forwarded-for")),
user_agent: text(header::USER_AGENT),
};
let mut stop = app.stop.subscribe();
// Not held up by the wait at shutdown, which waits for open requests.
let hub = tokio::select! {
hub = app.hub_within(START_WAIT) => hub,
_ = stop.wait_for(|stopping| *stopping) => None,
};
if *stop.borrow_and_update() {
debug!(id = peer.id, peer = %peer.address(), "websocket refused: shutting down");
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is stopping").into_response();
}
let Some(hub) = hub else {
warn!(
id = peer.id,
peer = %peer.address(),
"websocket refused: not logged in to the TeamSpeak server yet"
);
return (StatusCode::SERVICE_UNAVAILABLE, "the gateway is starting").into_response();
};
upgrade
.protocols([voelin_gateway_proto::SUBPROTOCOL])
.on_upgrade(move |socket| session::run(hub, socket))
.on_upgrade(move |socket| async move {
app.open.fetch_add(1, Ordering::Relaxed);
session::run(hub, socket, peer, stop).await;
app.open.fetch_sub(1, Ordering::Relaxed);
})
.into_response()
}
/// `SIGHUP` reads the configuration file again.
#[cfg(unix)]
async fn reload_on_hangup(hub: Arc<Hub>) {
use tokio::signal::unix::{SignalKind, signal};
use tracing::warn;
let Ok(mut hangup) = signal(SignalKind::hangup()) else { return };
while hangup.recv().await.is_some() {
if let Err(error) = hub.settings.reload() {
@@ -103,7 +265,31 @@ async fn reload_on_hangup(hub: Arc<Hub>) {
#[cfg(not(unix))]
async fn reload_on_hangup(_hub: Arc<Hub>) {}
async fn shutdown() {
async fn shutdown(app: Arc<App>) {
terminated().await;
info!(connections = app.open.load(Ordering::Relaxed), "shutting down");
app.stop.send_replace(true);
}
/// Ctrl-C, or `SIGTERM` (`systemctl stop`, `docker stop`: as the
/// container's first process tsgw gets no default handling of it).
#[cfg(unix)]
async fn terminated() {
use tokio::signal::unix::{SignalKind, signal};
match signal(SignalKind::terminate()) {
Ok(mut term) => {
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
Err(_) => {
let _ = tokio::signal::ctrl_c().await;
}
}
}
#[cfg(not(unix))]
async fn terminated() {
let _ = tokio::signal::ctrl_c().await;
info!("shutting down");
}
+19 -7
View File
@@ -10,7 +10,9 @@ use std::sync::Mutex;
use std::time::{Duration, Instant};
use voelin_gateway_proto::PermRule;
use voelin_query::{Command, QueryClient, Row};
use voelin_query::{Command, Row};
use crate::lookup::Lookup;
const CACHE_TTL: Duration = Duration::from_secs(60);
@@ -87,7 +89,8 @@ pub struct PermIds {
}
impl PermIds {
pub async fn load(client: &QueryClient) -> voelin_query::Result<Self> {
/// Look the ids up. Failures are logged here or by the caller.
pub async fn load(client: &Lookup) -> voelin_query::Result<Self> {
let names = [
"i_channel_join_power",
"i_channel_needed_join_power",
@@ -98,7 +101,8 @@ impl PermIds {
];
let mut ids = [0u32; 6];
for (i, name) in names.iter().enumerate() {
let rows = client.send(&Command::new("permidgetbyname").arg("permsid", name)).await?;
let rows =
client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await?;
ids[i] = rows.first().and_then(|r| r.parse("permid")).ok_or_else(|| {
voelin_query::Error::Protocol(format!("unknown permission {name}"))
})?;
@@ -108,8 +112,16 @@ impl PermIds {
let mut optional = [0u32; 2];
for (i, name) in ["b_channel_modify_name", "b_virtualserver_modify_name"].iter().enumerate()
{
match client.send(&Command::new("permidgetbyname").arg("permsid", name)).await {
match client.send_quiet(&Command::new("permidgetbyname").arg("permsid", name)).await {
Ok(rows) => optional[i] = rows.first().and_then(|r| r.parse("permid")).unwrap_or(0),
// More commands now would get the gateway banned.
Err(voelin_query::Error::Query(e)) if e.is_flood() => {
tracing::warn!(
name,
"the server's flood protection refused looking up a permission; its default grants nobody"
);
break;
}
Err(error) => tracing::warn!(%error, name, "unknown permission"),
}
}
@@ -160,7 +172,7 @@ pub struct GroupResolver {
impl GroupResolver {
pub async fn server_groups(
&self,
client: &QueryClient,
client: &Lookup,
cldbid: u64,
) -> voelin_query::Result<Vec<u64>> {
if let Some((at, groups)) = self.server.lock().unwrap().get(&cldbid)
@@ -177,7 +189,7 @@ impl GroupResolver {
pub async fn channel_groups(
&self,
client: &QueryClient,
client: &Lookup,
cldbid: u64,
cid: u64,
) -> voelin_query::Result<Vec<u64>> {
@@ -231,7 +243,7 @@ impl PermResolver {
pub async fn entries(
&self,
client: &QueryClient,
client: &Lookup,
cldbid: u64,
cid: u64,
) -> voelin_query::Result<Vec<Entry>> {
+136 -20
View File
@@ -1,15 +1,17 @@
//! One WebSocket client.
use std::collections::HashSet;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::extract::ws::{Message, WebSocket};
use axum::extract::ws::{CloseFrame, Message, WebSocket, close_code};
use base64::prelude::*;
use rand::RngExt;
use serde::Deserialize;
use tokio::sync::broadcast::error::RecvError;
use tracing::{debug, info};
use tokio::sync::watch;
use tracing::{Instrument, Level, debug, info, info_span, warn};
use voelin_gateway_proto::{ClientMsg, Envelope, ErrorCode, EventInfo, ServerMsg, feature};
use voelin_model::{ChatTarget, Presence};
use voelin_observer::ObserverEvent;
@@ -53,13 +55,50 @@ struct Session {
actions: RateLimit,
}
/// Enough of an envelope to answer one that did not parse.
/// Enough of an envelope to answer one that did not parse, and to name it
/// in the log.
#[derive(Deserialize)]
struct RawEnvelope {
id: Option<u64>,
/// Any JSON value: a `type` that is no string must not cost the `id`.
#[serde(rename = "type")]
kind: Option<serde_json::Value>,
}
pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
/// Requests that take longer are logged.
const SLOW: Duration = Duration::from_secs(1);
/// Where a connection comes from, for the log.
#[derive(Debug)]
pub struct Peer {
/// Counts connections since the start.
pub id: u64,
/// The address the connection came from (a proxy's, behind one).
pub addr: Option<SocketAddr>,
pub forwarded_for: Option<String>,
pub user_agent: Option<String>,
}
impl Peer {
/// [`Peer::addr`] for the log.
pub fn address(&self) -> String {
self.addr.map_or_else(|| "unknown".to_string(), |a| a.to_string())
}
}
/// Serve one connection until it closes or `stop` turns true.
pub async fn run(hub: Arc<Hub>, socket: WebSocket, peer: Peer, stop: watch::Receiver<bool>) {
let span = info_span!("ws", id = peer.id, peer = %peer.address());
serve(hub, socket, peer, stop).instrument(span).await;
}
async fn serve(hub: Arc<Hub>, mut socket: WebSocket, peer: Peer, mut stop: watch::Receiver<bool>) {
let connected = Instant::now();
info!(
forwarded_for = peer.forwarded_for.as_deref(),
user_agent = peer.user_agent.as_deref(),
"websocket connected"
);
let nonce_bytes: [u8; 24] = rand::rng().random();
let mut session = Session {
nonce: BASE64_URL_SAFE_NO_PAD.encode(nonce_bytes),
@@ -83,22 +122,29 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
capabilities: hub.capabilities(),
};
if send(&mut socket, None, hello).await.is_err() {
info!(reason = "could not send", "websocket closed");
return;
}
let mut observer = hub.observer.subscribe();
let mut events = hub.subscribe();
'outer: loop {
let reason = 'outer: loop {
tokio::select! {
msg = socket.recv() => {
let Some(Ok(msg)) = msg else { break };
let text = match msg {
Message::Text(t) => t,
Message::Close(_) => break,
_ => continue,
Some(Ok(Message::Text(t))) => t,
Some(Ok(Message::Close(_))) => break "closed by the app".to_string(),
Some(Ok(_)) => continue,
Some(Err(e)) => break format!("connection failed: {e}"),
None => break "connection ended".to_string(),
};
let replies = match serde_json::from_str::<Envelope<ClientMsg>>(text.as_str()) {
Ok(env) => session.handle(env.msg).await.into_iter().map(|m| (env.id, m)).collect(),
Ok(env) => {
let started = Instant::now();
let replies = session.handle(env.msg).await;
log_request(text.as_str(), started.elapsed(), &replies);
replies.into_iter().map(|m| (env.id, m)).collect()
}
Err(e) => {
let id = serde_json::from_str::<RawEnvelope>(text.as_str()).ok().and_then(|r| r.id);
let code = if e.to_string().starts_with("unknown variant") {
@@ -111,18 +157,18 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
};
for (id, reply) in replies {
if send(&mut socket, id, reply).await.is_err() {
break 'outer;
break 'outer "could not send".to_string();
}
}
}
event = observer.recv(), if session.presence.is_some() => {
let resync = matches!(event, Err(RecvError::Lagged(_)) | Ok(ObserverEvent::Snapshot(_)));
if let Err(RecvError::Closed) = event {
break;
break "the gateway stopped".to_string();
}
for msg in session.presence_update(resync) {
if send(&mut socket, None, msg).await.is_err() {
break 'outer;
break 'outer "could not send".to_string();
}
}
}
@@ -130,19 +176,59 @@ pub async fn run(hub: Arc<Hub>, mut socket: WebSocket) {
let event = match event {
Ok(event) => event,
Err(RecvError::Lagged(_)) => continue,
Err(RecvError::Closed) => break,
Err(RecvError::Closed) => break "the gateway stopped".to_string(),
};
for msg in session.push(&event).await {
if send(&mut socket, None, msg).await.is_err() {
break 'outer;
break 'outer "could not send".to_string();
}
}
}
// Turns true once, at shutdown.
_ = stop.changed() => {
// Apps connect again at once instead of finding out later.
let frame = CloseFrame { code: close_code::AWAY, reason: "the gateway is restarting".into() };
let _ = socket.send(Message::Close(Some(frame))).await;
break "the gateway is shutting down".to_string();
}
}
}
};
info!(
uid = session.user.as_ref().map(|u| u.uid.as_str()),
connected_s = connected.elapsed().as_secs(),
%reason,
open_chats = session.open_chats.len(),
"websocket closed"
);
session.close();
}
/// Log a request that failed on the gateway's side or took long, and every
/// request at debug level.
fn log_request(text: &str, elapsed: Duration, replies: &[ServerMsg]) {
let failure = replies.iter().find_map(|m| match m {
ServerMsg::Error {
code: code @ (ErrorCode::Unavailable | ErrorCode::Internal),
message,
} => Some((code, message.as_str())),
_ => None,
});
let slow = elapsed >= SLOW;
if !slow && failure.is_none() && !tracing::enabled!(Level::DEBUG) {
return;
}
let kind = serde_json::from_str::<RawEnvelope>(text).ok().and_then(|r| r.kind);
let request = kind.as_ref().and_then(serde_json::Value::as_str).unwrap_or("unknown");
let elapsed_ms = elapsed.as_millis() as u64;
match failure {
// Logged as a refused login.
Some(_) if matches!(request, "auth" | "resume") => {}
Some((code, error)) => warn!(request, ?code, error, elapsed_ms, "request failed"),
None if slow => warn!(request, elapsed_ms, "slow request"),
None => debug!(request, elapsed_ms, "request"),
}
}
async fn send(socket: &mut WebSocket, id: Option<u64>, msg: ServerMsg) -> Result<(), axum::Error> {
let env = Envelope { v: voelin_gateway_proto::VERSION, id, msg };
let text = serde_json::to_string(&env).expect("messages serialize");
@@ -175,9 +261,21 @@ fn is_action(msg: &ClientMsg) -> bool {
impl Session {
async fn handle(&mut self, msg: ClientMsg) -> Vec<ServerMsg> {
let login = match &msg {
ClientMsg::Auth { .. } => Some("signature"),
ClientMsg::Resume { .. } => Some("token"),
_ => None,
};
let started = Instant::now();
match self.handle_inner(msg).await {
Ok(msgs) => msgs,
Err(Denied(code, message)) => vec![error(code, &message)],
Err(Denied(code, message)) => {
if let Some(via) = login {
let elapsed_ms = started.elapsed().as_millis() as u64;
warn!(?code, %message, via, elapsed_ms, "login refused");
}
vec![error(code, &message)]
}
}
}
@@ -203,14 +301,15 @@ impl Session {
match msg {
ClientMsg::Ping => Ok(vec![ServerMsg::Pong]),
ClientMsg::Auth { omega, key_offset, ts, signature, .. } => {
let started = Instant::now();
let (user, token, token_expires) =
hub.authenticate(&omega, key_offset, ts, &signature, &self.nonce).await?;
info!(uid = %user.uid, nickname = %user.nickname, "user logged in");
self.logged_in(user, token, token_expires).await
self.logged_in(user, token, token_expires, "signature", started).await
}
ClientMsg::Resume { token, .. } => {
let started = Instant::now();
let (user, token, token_expires) = hub.resume(&token).await?;
self.logged_in(user, token, token_expires).await
self.logged_in(user, token, token_expires, "token", started).await
}
ClientMsg::SubscribePresence => {
self.user()?;
@@ -437,9 +536,13 @@ impl Session {
user: User,
token: String,
token_expires: i64,
via: &str,
started: Instant,
) -> Result<Vec<ServerMsg>, Denied> {
let capabilities = self.hub.user_capabilities(&user).await;
let uid = user.uid.clone();
let elapsed_ms = started.elapsed().as_millis() as u64;
info!(uid = %user.uid, nickname = %user.nickname, via, elapsed_ms, "user logged in");
self.user = Some(user);
Ok(vec![ServerMsg::AuthOk { uid, token, token_expires, capabilities }])
}
@@ -571,3 +674,16 @@ impl Session {
self.hub.session_streams_closed(&self.own_streams);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bad_request_keeps_its_id() {
let raw = |text: &str| serde_json::from_str::<RawEnvelope>(text).unwrap();
assert_eq!(raw(r#"{"id":7,"type":5}"#).id, Some(7));
assert_eq!(raw(r#"{"id":8,"type":"ping","extra":[]}"#).id, Some(8));
assert_eq!(raw(r#"{"type":"ping"}"#).id, None);
}
}
+7 -3
View File
@@ -81,8 +81,12 @@ pub async fn pump_relays(hub: Arc<Hub>, mut events: broadcast::Receiver<RelayEve
hub.publish_incoming(msg);
}
}
Ok(RelayEvent::Closed { channel, reason }) => {
warn!(channel, %reason, "relay closed");
// Logged by the pool.
Ok(RelayEvent::Closed { channel, .. }) => {
if hub.relay_wanted(channel) {
let hub = hub.clone();
tokio::spawn(async move { hub.reopen_relay(channel).await });
}
}
Err(RecvError::Lagged(_)) => {}
Err(RecvError::Closed) => return,
@@ -196,7 +200,7 @@ async fn apply_settings(hub: Arc<Hub>) {
hub.rebuild_relays(&new.relay.nickname).await;
}
if new.relay.pinned_channels != old.relay.pinned_channels {
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels).await;
hub.apply_pinned_channels(&old.relay.pinned_channels, &new.relay.pinned_channels);
}
let features_changed = Feature::ALL.iter().any(|f| f.enabled(&old) != f.enabled(&new));
if features_changed || new.perm.admin != old.perm.admin {
+48 -2
View File
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::sync::{broadcast, mpsc};
use voelin_query::{Command, escape};
/// Permission ids the fake server uses.
@@ -60,12 +60,18 @@ pub struct State {
/// Relay connections by channel.
relays: Vec<(u64, mpsc::UnboundedSender<String>)>,
next_clid: u16,
/// Permission lookups (`permsid`) to refuse for flooding, and how often.
refusals: HashMap<String, usize>,
/// The commands received, in order (`login` left out).
commands: Vec<String>,
}
#[derive(Clone)]
pub struct FakeServer {
pub addr: SocketAddr,
pub state: Arc<Mutex<State>>,
/// Ends every open connection, like a server restart.
kick: broadcast::Sender<()>,
}
impl FakeServer {
@@ -73,7 +79,7 @@ impl FakeServer {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let state = Arc::new(Mutex::new(State { next_clid: 100, ..Default::default() }));
let server = Self { addr, state };
let server = Self { addr, state, kick: broadcast::channel(1).0 };
let s = server.clone();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
@@ -120,6 +126,35 @@ impl FakeServer {
}
}
/// Answer looking up permission `permsid` with the flood protection's
/// refusal, the next `times` times.
pub fn refuse(&self, permsid: &str, times: usize) {
self.state.lock().unwrap().refusals.insert(permsid.to_string(), times);
}
/// The commands received so far, in order (`login` left out).
pub fn commands(&self) -> Vec<String> {
self.state.lock().unwrap().commands.clone()
}
/// An observer connection is registered for server events.
pub fn observed(&self) -> bool {
!self.state.lock().unwrap().observers.is_empty()
}
/// Channels with a relay listening.
pub fn relayed_channels(&self) -> Vec<u64> {
self.state.lock().unwrap().relays.iter().map(|(c, _)| *c).collect()
}
/// Drop every query connection, as a restarting server does.
pub fn drop_connections(&self) {
let mut s = self.state.lock().unwrap();
s.observers.clear();
s.relays.clear();
let _ = self.kick.send(());
}
pub fn posted(&self) -> Vec<(u8, u64, String)> {
self.state.lock().unwrap().posted.clone()
}
@@ -134,6 +169,7 @@ impl FakeServer {
let (r, mut w) = stream.into_split();
let mut lines = BufReader::new(r).lines();
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
let mut kicked = self.kick.subscribe();
let clid = {
let mut s = self.state.lock().unwrap();
s.next_clid += 1;
@@ -148,6 +184,9 @@ impl FakeServer {
line = lines.next_line() => {
let Ok(Some(line)) = line else { return };
let Some(cmd) = Command::parse(&line) else { continue };
if cmd.name != "login" {
self.state.lock().unwrap().commands.push(line.clone());
}
let reply = self.answer(&cmd, clid, &mut channel, &tx);
if w.write_all(reply.as_bytes()).await.is_err() {
return;
@@ -158,6 +197,7 @@ impl FakeServer {
return;
}
}
_ = kicked.recv() => return,
}
}
}
@@ -194,6 +234,12 @@ impl FakeServer {
]),
"permidgetbyname" => {
let name = arg("permsid").unwrap_or_default();
if let Some(left @ 1..) = s.refusals.get_mut(&name) {
*left -= 1;
return "error id=524 msg=client\\sis\\sflooding \
extra_msg=please\\swait\\s1\\sseconds\n\r"
.into();
}
match PERMS.iter().find(|(n, _)| *n == name) {
Some((_, id)) => data(vec![format!("permsid={name} permid={id}")]),
None => "error id=2 msg=invalid\\spermission\n\r".into(),
+102 -2
View File
@@ -26,6 +26,7 @@ const LOBBY: ChatTarget = ChatTarget::Channel(1);
struct Fixture {
fake: FakeServer,
boot: crate::config::Bootstrap,
hub: Arc<Hub>,
url: String,
dir: std::path::PathBuf,
@@ -80,6 +81,7 @@ impl Fixture {
});
}
let layers = Layers { file: file_values(&toml).unwrap(), ..Default::default() };
let boot = layers.bootstrap().unwrap();
let hub = Hub::start(layers).await.unwrap();
// Wait for the observer's first snapshot.
for _ in 0..100 {
@@ -90,9 +92,10 @@ impl Fixture {
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://{}/v1", listener.local_addr().unwrap());
let app = crate::router(hub.clone());
let app = crate::router(crate::App::started(boot.clone(), hub.clone()))
.into_make_service_with_connect_info::<std::net::SocketAddr>();
tokio::spawn(async move { axum::serve(listener, app).await });
Self { fake, hub, url, dir, people }
Self { fake, boot, hub, url, dir, people }
}
fn people(&self) -> (&Person, &Person, &Person) {
@@ -583,3 +586,100 @@ async fn tells_apps_where_it_is() {
let fx = Fixture::start("well-known-public", public).await;
assert_eq!(well_known(&fx).await, "wss://gw.example.test/v1");
}
/// The TeamSpeak server drops the gateway's query connections (a restart):
/// logins go on working, through a new lookup connection.
#[tokio::test(flavor = "multi_thread")]
async fn logins_work_after_the_server_dropped_the_gateway() {
let fx = Fixture::start("reconnect", "").await;
let (alice, bob, _) = fx.people();
let (b, mut b_rx) = bob.connect(&fx).await;
b.open_chat(LOBBY).await.unwrap();
b.open_chat(ChatTarget::Server).await.unwrap();
assert!(fx.hub.lookup.is_up());
let old_id = fx.hub.lookup.own_id().unwrap();
fx.fake.drop_connections();
// At once: the login waits for the new connection.
let (a, _a_rx) = alice.connect(&fx).await;
assert!(a.has(feature::ADMIN));
assert!(fx.hub.lookup.is_up());
a.post(ChatTarget::Server, "back again".into(), None).await.unwrap();
assert!(fx.fake.posted().contains(&(3, 1, "back again".into())));
// Bob still reads the lobby: its relay comes back.
for _ in 0..100 {
if fx.fake.relayed_channels().contains(&1) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
fx.fake.say_in_channel(1, "Dave", "dave", "after the restart");
expect(
&mut b_rx,
"relayed after the restart",
|p| matches!(p, Push::Chat { message, .. } if message.text == "after the restart"),
)
.await;
// A restarted server hands out client ids from 1 again: a user may get
// the one the gateway had. Their server chat is not the gateway's own.
assert_ne!(fx.hub.lookup.own_id(), Some(old_id));
for _ in 0..100 {
if fx.fake.observed() {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
fx.fake.notify_observers(&format!(
"notifytextmessage targetmode=3 msg=hi\\sall invokerid={old_id} invokername=Erin \
invokeruid=erin"
));
expect(
&mut b_rx,
"server chat from the gateway's old id",
|p| matches!(p, Push::Chat { message, .. } if message.text == "hi all"),
)
.await;
}
/// The server's flood protection refuses looking up an optional permission,
/// also when asked again after the wait: the gateway asks for no more, which
/// would get it banned for 10 minutes.
#[tokio::test(flavor = "multi_thread")]
async fn optional_permissions_stop_at_the_flood_protection() {
let fake = FakeServer::start().await;
fake.refuse("b_channel_modify_name", 2);
let connect = voelin_query::Connect {
transport: voelin_query::Transport::Raw,
addr: fake.addr.to_string(),
user: "serveradmin".into(),
secret: None,
server_port: None,
server_id: None,
// Taken to be on the allowlist.
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
};
let lookup = crate::lookup::Lookup::open(connect, "Gateway".into()).await;
let ids = crate::perms::PermIds::load(&lookup).await.unwrap();
assert_eq!(ids.subscribe_power, fake::SUBSCRIBE_POWER);
assert_eq!((ids.channel_modify_name, ids.server_modify_name), (0, 0));
let asked = fake.commands();
let count =
|name: &str| asked.iter().filter(|c| c.ends_with(&format!("permsid={name}"))).count();
assert_eq!(count("b_channel_modify_name"), 2, "{asked:?}");
assert_eq!(count("b_virtualserver_modify_name"), 0, "{asked:?}");
}
/// `/health` says what is missing until the gateway is logged in.
#[tokio::test(flavor = "multi_thread")]
async fn health_tells_whether_the_gateway_is_up() {
use axum::extract::State;
use axum::http::StatusCode;
let fx = Fixture::start("health", "").await;
let app = crate::App::started(fx.boot.clone(), fx.hub.clone());
assert_eq!(crate::health(State(app)).await, (StatusCode::OK, "ok".to_string()));
let starting = crate::App::new(fx.boot.clone());
let (status, text) = crate::health(State(starting)).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert!(text.starts_with("starting"), "{text}");
}