M3: tsc-query and tsc-observer (invisible presence, relay chat)

- tsc-query: ServerQuery codec (escaping, rows, errors, notifications,
  command builder/parser), line client for raw TCP and SSH (russh) with
  events, flood-limit token bucket and keepalive, HTTP WebQuery client.
- tsc-model: Presence (snapshot/delta/diff), ChannelInfo, ClientInfo,
  ChatMessage, relay formatting and message splitting.
- tsc-observer: Observer (snapshot, events or polling, resync,
  reconnect) and RelayPool (one query session per channel, reads channel
  chat and posts as [Nick] text, unique nicknames, polite quit).
- tsctl query/observe/relay; smoke test covers presence and relay on
  TS3 (raw) and TS6 (SSH). Dev servers enable all query interfaces with
  a fixed dev password.
- docs: query clients are hidden by clients, not the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 14:15:29 +00:00
1 parent f31d976bfc
commit 6e732d625f
25 files changed
+3555 -52

No files matched your search

Generated
+1059 -47
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -10,6 +10,8 @@ members = [
"crates/proto/tsclientlib",
"crates/tsc-audio",
"crates/tsc-model",
"crates/tsc-observer",
"crates/tsc-query",
"crates/tsc-store",
"tools/tsctl",
]
@@ -22,6 +24,8 @@ default-members = [
"crates/proto/tsclientlib",
"crates/tsc-audio",
"crates/tsc-model",
"crates/tsc-observer",
"crates/tsc-query",
"crates/tsc-store",
"tools/tsctl",
]
+12 -4
View File
@@ -23,7 +23,7 @@ See [docs/architecture.md](docs/architecture.md) for the design and milestones.
## Status
Done so far (milestones M0–M2 of [the plan](docs/architecture.md#milestones)):
Done so far (milestones M0–M3 of [the plan](docs/architecture.md#milestones)):
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
@@ -31,9 +31,13 @@ Done so far (milestones M0–M2 of [the plan](docs/architecture.md#milestones)):
- `crates/tsc-model`: server flavor detection (TS3 / TS6) and capabilities
- `crates/tsc-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
- `crates/tsc-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events
- `crates/tsc-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
- `crates/tsc-observer`: invisible presence (events or polling) and channel-chat relays over ServerQuery
- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events,
`query`, `observe` (invisible presence) and `relay` (channel chat without joining)
- `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh`
checks tree, server chat, channel chat and a voice tone round-trip on both
checks tree, server chat, channel chat, a voice tone round-trip, invisible presence
and relay chat on both
- `fuzz/`: cargo-fuzz targets for packets, commands and the license chain
No GUI and no screen sharing yet.
@@ -50,7 +54,11 @@ cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me repl # interactive chat
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me voice send --tone 440
cargo run -p tsctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav
scripts/it-smoke.sh # tree, chat and voice round-trips on both servers
# ServerQuery (dev password tsc-dev-admin): invisible presence and relay chat
cargo run -p tsctl -- observe ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted
cargo run -p tsctl -- relay ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted --channel 1
scripts/it-smoke.sh # all of the above, on both servers
```
Other commands: `tsctl identity new`, `tsctl versions`, `tsctl connect <addr> listen|chat|raw`.
+81
View File
@@ -0,0 +1,81 @@
//! Chat messages, from any source.
use serde::{Deserialize, Serialize};
use crate::presence::{ChannelId, ClientId};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
pub enum ChatTarget {
/// Everyone on the server.
Server,
Channel(ChannelId),
/// Private chat, by the other side's unique id when known.
Private(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatMessage {
pub target: ChatTarget,
pub author_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author_uid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author_id: Option<ClientId>,
pub text: String,
/// Unix time in milliseconds.
pub ts_ms: i64,
/// Carried by a gateway or query relay rather than our own connection.
#[serde(default)]
pub via_relay: bool,
}
/// 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)
}
/// Split text so each part fits TeamSpeak's message limit (1024 bytes of
/// text), breaking at character boundaries.
pub fn split_message(text: &str, max_bytes: usize) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
for c in text.chars() {
if current.len() + c.len_utf8() > max_bytes {
parts.push(std::mem::take(&mut current));
}
current.push(c);
}
if !current.is_empty() || parts.is_empty() {
parts.push(current);
}
parts
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relay_format() {
assert_eq!(relay_text("[{nick}] {text}", "Alice", "hi"), "[Alice] hi");
}
#[test]
fn splits_on_char_boundaries() {
assert_eq!(split_message("abcdef", 4), vec!["abcd", "ef"]);
assert_eq!(split_message("", 4), vec![""]);
let parts = split_message("ääää", 3);
assert!(parts.iter().all(|p| p.len() <= 3));
assert_eq!(parts.concat(), "ääää");
}
#[test]
fn target_json() {
assert_eq!(
serde_json::to_string(&ChatTarget::Channel(5)).unwrap(),
r#"{"kind":"channel","id":5}"#
);
assert_eq!(serde_json::to_string(&ChatTarget::Server).unwrap(), r#"{"kind":"server"}"#);
}
}
+6
View File
@@ -3,6 +3,12 @@
//! Nothing in here does IO; the types describe what a server offers and what
//! the user sees.
mod chat;
mod presence;
mod server;
pub use chat::{ChatMessage, ChatTarget, relay_text, split_message};
pub use presence::{
ChannelId, ChannelInfo, ClientId, ClientInfo, Presence, PresenceDelta, PresenceSnapshot,
};
pub use server::{Capabilities, ServerFlavor, ServerVersion};
+233
View File
@@ -0,0 +1,233 @@
//! Who is where: channels and the clients in them.
//!
//! The same model is fed from a voice connection, a query session or a
//! gateway. Sources send a [`PresenceSnapshot`] followed by
//! [`PresenceDelta`]s; sources that can only poll use [`Presence::diff`].
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
pub type ChannelId = u64;
pub type ClientId = u16;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelInfo {
pub id: ChannelId,
/// `0` for top-level channels.
pub parent: ChannelId,
/// Id of the sibling directly above, `0` for the first.
pub order: ChannelId,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub topic: Option<String>,
#[serde(default)]
pub has_password: bool,
/// `None` means unlimited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_clients: Option<i32>,
#[serde(default)]
pub needed_subscribe_power: i32,
#[serde(default)]
pub needed_talk_power: i32,
#[serde(default)]
pub is_default: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClientInfo {
pub id: ClientId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uid: Option<String>,
pub nickname: String,
pub channel: ChannelId,
/// ServerQuery clients (bots, our own relays). UIs normally hide them.
#[serde(default)]
pub is_query: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub away: Option<String>,
#[serde(default)]
pub input_muted: bool,
#[serde(default)]
pub output_muted: bool,
/// `None` when the source cannot tell (query sessions see no voice).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub talking: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub streaming: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub server_groups: Vec<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresenceSnapshot {
pub server_name: String,
pub channels: Vec<ChannelInfo>,
pub clients: Vec<ClientInfo>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PresenceDelta {
ChannelAdded(ChannelInfo),
ChannelChanged(ChannelInfo),
ChannelRemoved { id: ChannelId },
ClientJoined(ClientInfo),
ClientChanged(ClientInfo),
ClientMoved { id: ClientId, channel: ChannelId },
ClientLeft { id: ClientId },
ServerRenamed { name: String },
}
/// Current state; apply deltas as they arrive.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Presence {
pub server_name: String,
pub channels: BTreeMap<ChannelId, ChannelInfo>,
pub clients: BTreeMap<ClientId, ClientInfo>,
}
impl Presence {
pub fn from_snapshot(s: PresenceSnapshot) -> Self {
Self {
server_name: s.server_name,
channels: s.channels.into_iter().map(|c| (c.id, c)).collect(),
clients: s.clients.into_iter().map(|c| (c.id, c)).collect(),
}
}
pub fn snapshot(&self) -> PresenceSnapshot {
PresenceSnapshot {
server_name: self.server_name.clone(),
channels: self.channels.values().cloned().collect(),
clients: self.clients.values().cloned().collect(),
}
}
/// Apply a delta. Returns `false` if it referred to something unknown
/// (the caller may want to resynchronise).
pub fn apply(&mut self, delta: &PresenceDelta) -> bool {
match delta {
PresenceDelta::ChannelAdded(c) | PresenceDelta::ChannelChanged(c) => {
self.channels.insert(c.id, c.clone());
true
}
PresenceDelta::ChannelRemoved { id } => self.channels.remove(id).is_some(),
PresenceDelta::ClientJoined(c) | PresenceDelta::ClientChanged(c) => {
self.clients.insert(c.id, c.clone());
true
}
PresenceDelta::ClientMoved { id, channel } => match self.clients.get_mut(id) {
Some(c) => {
c.channel = *channel;
true
}
None => false,
},
PresenceDelta::ClientLeft { id } => self.clients.remove(id).is_some(),
PresenceDelta::ServerRenamed { name } => {
self.server_name = name.clone();
true
}
}
}
/// Deltas that turn `self` into `new`, for sources that poll.
pub fn diff(&self, new: &Presence) -> Vec<PresenceDelta> {
let mut out = Vec::new();
if self.server_name != new.server_name {
out.push(PresenceDelta::ServerRenamed { name: new.server_name.clone() });
}
for (id, c) in &new.channels {
match self.channels.get(id) {
None => out.push(PresenceDelta::ChannelAdded(c.clone())),
Some(old) if old != c => out.push(PresenceDelta::ChannelChanged(c.clone())),
_ => {}
}
}
for (id, c) in &new.clients {
match self.clients.get(id) {
None => out.push(PresenceDelta::ClientJoined(c.clone())),
Some(old) if old == c => {}
Some(old) if ClientInfo { channel: c.channel, ..old.clone() } == *c => {
out.push(PresenceDelta::ClientMoved { id: *id, channel: c.channel });
}
Some(_) => out.push(PresenceDelta::ClientChanged(c.clone())),
}
}
for id in self.clients.keys().filter(|id| !new.clients.contains_key(id)) {
out.push(PresenceDelta::ClientLeft { id: *id });
}
// Channels last, so clients leave a removed channel first.
for id in self.channels.keys().filter(|id| !new.channels.contains_key(id)) {
out.push(PresenceDelta::ChannelRemoved { id: *id });
}
out
}
/// Clients in a channel, excluding query clients.
pub fn members(&self, channel: ChannelId) -> impl Iterator<Item = &ClientInfo> {
self.clients.values().filter(move |c| c.channel == channel && !c.is_query)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ch(id: u64, name: &str) -> ChannelInfo {
ChannelInfo { id, name: name.into(), ..Default::default() }
}
fn cl(id: u16, name: &str, channel: u64) -> ClientInfo {
ClientInfo { id, nickname: name.into(), channel, ..Default::default() }
}
fn presence(channels: Vec<ChannelInfo>, clients: Vec<ClientInfo>) -> Presence {
Presence::from_snapshot(PresenceSnapshot { server_name: "s".into(), channels, clients })
}
#[test]
fn diff_then_apply_reaches_target() {
let old = presence(
vec![ch(1, "Lobby"), ch(2, "Games")],
vec![cl(1, "Alice", 1), cl(2, "Bob", 1), cl(3, "Carol", 2)],
);
let mut muted = cl(2, "Bob", 1);
muted.input_muted = true;
let new = presence(
vec![ch(1, "Lobby"), ch(3, "New")],
vec![cl(1, "Alice", 3), muted, cl(4, "Dave", 1)],
);
let deltas = old.diff(&new);
assert!(deltas.contains(&PresenceDelta::ClientMoved { id: 1, channel: 3 }));
assert!(deltas.contains(&PresenceDelta::ClientLeft { id: 3 }));
assert!(deltas.contains(&PresenceDelta::ChannelRemoved { id: 2 }));
assert!(deltas.iter().any(|d| matches!(d, PresenceDelta::ClientChanged(c) if c.id == 2)));
let mut state = old.clone();
for d in &deltas {
assert!(state.apply(d));
}
assert_eq!(state, new);
assert!(new.diff(&new).is_empty());
}
#[test]
fn members_skip_query_clients() {
let mut bot = cl(9, "bot", 1);
bot.is_query = true;
let p = presence(vec![ch(1, "Lobby")], vec![cl(1, "Alice", 1), bot]);
assert_eq!(p.members(1).count(), 1);
}
#[test]
fn delta_json_is_tagged() {
let json =
serde_json::to_string(&PresenceDelta::ClientMoved { id: 1, channel: 3 }).unwrap();
assert_eq!(json, r#"{"kind":"client_moved","id":1,"channel":3}"#);
let back: PresenceDelta = serde_json::from_str(&json).unwrap();
assert_eq!(back, PresenceDelta::ClientMoved { id: 1, channel: 3 });
}
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "tsc-observer"
version = "0.1.0"
description = "Invisible presence and channel-chat relays over ServerQuery."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt", "sync", "time"] }
tracing = "0.1"
tsc-model = { path = "../tsc-model" }
tsc-query = { path = "../tsc-query" }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util"] }
[lints]
workspace = true
+218
View File
@@ -0,0 +1,218 @@
//! Query rows and events to model types.
use tsc_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, PresenceDelta};
use tsc_query::{Notification, Row};
/// From a `channellist -topic -flags -voice -limits` row, or the fields of
/// `notifychannelcreated`.
pub fn channel_from_row(row: &Row) -> Option<ChannelInfo> {
Some(ChannelInfo {
id: row.parse("cid")?,
parent: row.parse("pid").or_else(|| row.parse("cpid")).unwrap_or(0),
order: row.parse("channel_order").unwrap_or(0),
name: row.get("channel_name").unwrap_or_default().to_string(),
topic: row.get("channel_topic").filter(|t| !t.is_empty()).map(str::to_string),
has_password: row.flag("channel_flag_password").unwrap_or(false),
max_clients: row.parse::<i32>("channel_maxclients").filter(|m| *m >= 0),
needed_subscribe_power: row.parse("channel_needed_subscribe_power").unwrap_or(0),
needed_talk_power: row.parse("channel_needed_talk_power").unwrap_or(0),
is_default: row.flag("channel_flag_default").unwrap_or(false),
})
}
/// Update `channel` with the properties present in `row` (for
/// `notifychanneledited`, which only carries what changed).
pub fn update_channel(channel: &mut ChannelInfo, row: &Row) {
if let Some(name) = row.get("channel_name") {
channel.name = name.to_string();
}
if let Some(topic) = row.get("channel_topic") {
channel.topic = Some(topic.to_string()).filter(|t| !t.is_empty());
}
if let Some(order) = row.parse("channel_order") {
channel.order = order;
}
if let Some(p) = row.flag("channel_flag_password") {
channel.has_password = p;
}
if let Some(m) = row.parse::<i32>("channel_maxclients") {
channel.max_clients = Some(m).filter(|m| *m >= 0);
}
if let Some(p) = row.parse("channel_needed_subscribe_power") {
channel.needed_subscribe_power = p;
}
if let Some(p) = row.parse("channel_needed_talk_power") {
channel.needed_talk_power = p;
}
if let Some(d) = row.flag("channel_flag_default") {
channel.is_default = d;
}
}
/// From a `clientlist -uid -away -voice -groups -country` row or a
/// `notifycliententerview` row (which names the channel `ctid`).
pub fn client_from_row(row: &Row) -> Option<ClientInfo> {
let away = row.flag("client_away").unwrap_or(false);
Some(ClientInfo {
id: row.parse("clid")?,
uid: row.get("client_unique_identifier").map(str::to_string),
nickname: row.get("client_nickname").unwrap_or_default().to_string(),
channel: row.parse("cid").or_else(|| row.parse("ctid"))?,
is_query: row.parse::<u8>("client_type") == Some(1),
away: away.then(|| row.get("client_away_message").unwrap_or_default().to_string()),
input_muted: row.flag("client_input_muted").unwrap_or(false),
output_muted: row.flag("client_output_muted").unwrap_or(false),
talking: row.flag("client_flag_talking"),
streaming: row.flag("client_is_streaming"),
server_groups: row
.get("client_servergroups")
.map(|g| g.split(',').filter_map(|g| g.parse().ok()).collect())
.unwrap_or_default(),
country: row.get("client_country").filter(|c| !c.is_empty()).map(str::to_string),
})
}
/// Presence changes carried by a query event. `notifychanneledited` needs the
/// current channel state and is handled by the observer.
pub fn delta_from_notification(n: &Notification) -> Vec<PresenceDelta> {
let rows = n.rows.iter();
match n.name.as_str() {
"notifycliententerview" => {
rows.filter_map(client_from_row).map(PresenceDelta::ClientJoined).collect()
}
"notifyclientleftview" => rows
.filter_map(|r| r.parse("clid"))
.map(|id| PresenceDelta::ClientLeft { id })
.collect(),
"notifyclientmoved" => {
// Several clients can move at once; ctid is only in the first row.
let ctid = n.rows.first().and_then(|r| r.parse("ctid"));
rows.filter_map(|r| {
Some(PresenceDelta::ClientMoved {
id: r.parse("clid")?,
channel: r.parse("ctid").or(ctid)?,
})
})
.collect()
}
"notifychannelcreated" => {
rows.filter_map(channel_from_row).map(PresenceDelta::ChannelAdded).collect()
}
"notifychanneldeleted" => rows
.filter_map(|r| r.parse("cid"))
.map(|id| PresenceDelta::ChannelRemoved { id })
.collect(),
"notifyserveredited" => rows
.filter_map(|r| r.get("virtualserver_name"))
.map(|name| PresenceDelta::ServerRenamed { name: name.to_string() })
.collect(),
_ => Vec::new(),
}
}
/// A `notifytextmessage` as a chat message.
pub fn is_text_message(n: &Notification, now_ms: i64) -> Option<ChatMessage> {
if n.name != "notifytextmessage" {
return None;
}
let row = n.rows.first()?;
let target = match row.parse::<u8>("targetmode")? {
3 => ChatTarget::Server,
2 => ChatTarget::Channel(0), // filled in by the receiver, who knows its channel
1 => ChatTarget::Private(row.get("invokeruid").unwrap_or_default().to_string()),
_ => return None,
};
Some(ChatMessage {
target,
author_name: row.get("invokername").unwrap_or_default().to_string(),
author_uid: row.get("invokeruid").map(str::to_string),
author_id: row.parse("invokerid"),
text: row.get("msg").unwrap_or_default().to_string(),
ts_ms: now_ms,
via_relay: true,
})
}
#[cfg(test)]
mod tests {
use tsc_query::{Line, parse_line};
use super::*;
fn notify(line: &str) -> Notification {
match parse_line(line) {
Line::Notify(n) => n,
other => panic!("{other:?}"),
}
}
#[test]
fn clientlist_row() {
// Captured from TeamSpeak 6.0.0-beta13.1 (clientlist -uid -away -voice -groups -country).
let row = &tsc_query::parse_rows(
"clid=7 cid=1 client_database_id=4 client_nickname=sample client_type=0 client_away=0 \
client_away_message client_flag_talking=0 client_input_muted=1 client_output_muted=0 \
client_unique_identifier=hSC9DusMo3MJwDuA8MuvZBaHfb\\/h77N9WZtYskAFlG0= \
client_servergroups=8,9 client_country",
)[0];
let c = client_from_row(row).unwrap();
assert_eq!((c.id, c.channel, c.nickname.as_str()), (7, 1, "sample"));
assert!(!c.is_query && c.input_muted && c.away.is_none());
assert_eq!(c.talking, Some(false));
assert_eq!(c.server_groups, vec![8, 9]);
assert_eq!(c.uid.as_deref(), Some("hSC9DusMo3MJwDuA8MuvZBaHfb/h77N9WZtYskAFlG0="));
assert_eq!(c.country, None);
}
#[test]
fn channellist_row() {
let row = &tsc_query::parse_rows(
"cid=1 pid=0 channel_order=0 channel_name=Default\\sChannel channel_topic=t \
channel_flag_default=1 channel_flag_password=0 channel_maxclients=-1 \
channel_needed_subscribe_power=0 channel_needed_talk_power=5",
)[0];
let c = channel_from_row(row).unwrap();
assert_eq!(c.name, "Default Channel");
assert!(c.is_default && !c.has_password);
assert_eq!(c.max_clients, None);
assert_eq!(c.needed_talk_power, 5);
}
#[test]
fn events_to_deltas() {
let n = notify(
"notifycliententerview cfid=0 ctid=1 reasonid=0 clid=6 \
client_unique_identifier=abc client_nickname=evtest client_type=0",
);
match &delta_from_notification(&n)[..] {
[PresenceDelta::ClientJoined(c)] => assert_eq!((c.id, c.channel), (6, 1)),
other => panic!("{other:?}"),
}
let n = notify("notifyclientmoved ctid=5 reasonid=0 clid=6|clid=7");
assert_eq!(
delta_from_notification(&n),
vec![
PresenceDelta::ClientMoved { id: 6, channel: 5 },
PresenceDelta::ClientMoved { id: 7, channel: 5 },
]
);
let n = notify("notifyclientleftview cfid=1 ctid=0 reasonid=8 clid=6");
assert_eq!(delta_from_notification(&n), vec![PresenceDelta::ClientLeft { id: 6 }]);
let n = notify("notifychanneldeleted cid=3 invokerid=0");
assert_eq!(delta_from_notification(&n), vec![PresenceDelta::ChannelRemoved { id: 3 }]);
}
#[test]
fn text_messages() {
let n = notify(
"notifytextmessage targetmode=3 msg=hi\\sall invokerid=5 invokername=Bob invokeruid=u",
);
let m = is_text_message(&n, 42).unwrap();
assert_eq!(m.target, ChatTarget::Server);
assert_eq!(
(m.text.as_str(), m.author_name.as_str(), m.author_id),
("hi all", "Bob", Some(5))
);
assert!(is_text_message(&notify("notifyclientleftview clid=1"), 0).is_none());
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Invisible presence and channel-chat relays over ServerQuery.
//!
//! Query clients do not show up in normal clients' channel trees. The
//! [`Observer`] keeps a live [`Presence`](tsc_model::Presence) of a server
//! from one query session. A [`RelayPool`] puts one query session into each
//! channel whose chat someone wants to read or write without joining it.
//!
//! Used by the gateway (`tsgw`) for all of its users and by the client for
//! users who have their own query credentials.
mod convert;
mod observer;
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};
+234
View File
@@ -0,0 +1,234 @@
//! Keep a server's presence up to date from one query session.
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tokio::sync::{broadcast, watch};
use tokio::time::{Instant, sleep, sleep_until};
use tracing::{debug, info, warn};
use tsc_model::{ChatMessage, Presence, PresenceDelta, PresenceSnapshot};
use tsc_query::{Command, Connect, Notification, QueryClient};
use crate::convert::{
channel_from_row, client_from_row, delta_from_notification, is_text_message, update_channel,
};
#[derive(Clone, Debug)]
pub struct ObserverConfig {
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),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ObserverEvent {
/// Full state; sent after every (re)connect.
Snapshot(PresenceSnapshot),
Delta(PresenceDelta),
Chat(ChatMessage),
/// Lost the query connection; presence may be stale until the next snapshot.
Disconnected(String),
}
/// Handle to a running observer. Dropping it stops the task.
pub struct Observer {
presence: Arc<RwLock<Presence>>,
events: broadcast::Sender<ObserverEvent>,
_stop: watch::Sender<()>,
}
impl Observer {
pub fn spawn(config: ObserverConfig) -> Self {
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 }
}
/// Receive events. Call [`Observer::snapshot`] after subscribing to get
/// the state the events apply to.
pub fn subscribe(&self) -> broadcast::Receiver<ObserverEvent> {
self.events.subscribe()
}
pub fn snapshot(&self) -> PresenceSnapshot {
self.presence.read().unwrap().snapshot()
}
pub fn presence(&self) -> Arc<RwLock<Presence>> {
self.presence.clone()
}
}
async fn run(
config: ObserverConfig,
presence: Arc<RwLock<Presence>>,
events: broadcast::Sender<ObserverEvent>,
mut stopped: watch::Receiver<()>,
) {
loop {
let result = tokio::select! {
r = session(&config, &presence, &events) => 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));
tokio::select! {
_ = sleep(config.reconnect_delay) => {}
_ = stopped.changed() => return,
}
}
}
/// Read the full state.
async fn load(client: &QueryClient) -> tsc_query::Result<Presence> {
let info = client.send(&Command::new("serverinfo")).await?;
let channels = client
.send(&Command::new("channellist").flag("topic").flag("flags").flag("voice").flag("limits"))
.await?;
let clients = client
.send(
&Command::new("clientlist")
.flag("uid")
.flag("away")
.flag("voice")
.flag("groups")
.flag("country"),
)
.await?;
Ok(Presence::from_snapshot(PresenceSnapshot {
server_name: info
.first()
.and_then(|r| r.get("virtualserver_name"))
.unwrap_or_default()
.to_string(),
channels: channels.iter().filter_map(channel_from_row).collect(),
clients: clients.iter().filter_map(client_from_row).collect(),
}))
}
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
async fn session(
config: &ObserverConfig,
presence: &RwLock<Presence>,
events: &broadcast::Sender<ObserverEvent>,
) -> tsc_query::Result<()> {
let (client, mut notifications) = QueryClient::connect(&config.connect).await?;
if notifications.is_some() {
for event in ["server", "channel"] {
let mut cmd = Command::new("servernotifyregister").arg("event", event);
if event == "channel" {
cmd = cmd.arg("id", 0);
}
client.send(&cmd).await?;
}
if config.server_chat {
client.send(&Command::new("servernotifyregister").arg("event", "textserver")).await?;
}
}
let state = load(&client).await?;
info!(
server = %state.server_name,
channels = state.channels.len(),
clients = state.clients.len(),
events = notifications.is_some(),
"observer connected"
);
*presence.write().unwrap() = state.clone();
let _ = events.send(ObserverEvent::Snapshot(state.snapshot()));
let mut next_poll = Instant::now() + config.poll_interval;
loop {
let notification: Option<Notification> = tokio::select! {
n = async {
match &mut notifications {
Some(rx) => rx.recv().await,
None => std::future::pending().await,
}
} => match n {
Some(n) => Some(n),
None => return Ok(()),
},
_ = sleep_until(next_poll) => None,
};
match notification {
Some(n) => handle_notification(&n, presence, events),
None => {
// Resync and publish only what changed.
let fresh = load(&client).await?;
let deltas = presence.read().unwrap().diff(&fresh);
if !deltas.is_empty() {
debug!(changes = deltas.len(), "observer resync");
}
*presence.write().unwrap() = fresh;
for d in deltas {
let _ = events.send(ObserverEvent::Delta(d));
}
next_poll = Instant::now() + config.poll_interval;
}
}
}
}
fn handle_notification(
n: &Notification,
presence: &RwLock<Presence>,
events: &broadcast::Sender<ObserverEvent>,
) {
if let Some(msg) = is_text_message(n, now_ms()) {
let _ = events.send(ObserverEvent::Chat(msg));
return;
}
let deltas = if n.name == "notifychanneledited" || n.name == "notifychannelmoved" {
let state = presence.read().unwrap();
n.rows
.iter()
.filter_map(|row| {
let mut channel = state.channels.get(&row.parse("cid")?)?.clone();
update_channel(&mut channel, row);
if let Some(parent) = row.parse("cpid") {
channel.parent = parent;
}
if let Some(order) = row.parse("order") {
channel.order = order;
}
Some(PresenceDelta::ChannelChanged(channel))
})
.collect()
} else {
delta_from_notification(n)
};
let mut state = presence.write().unwrap();
for d in deltas {
state.apply(&d);
let _ = events.send(ObserverEvent::Delta(d));
}
}
+190
View File
@@ -0,0 +1,190 @@
//! Channel-chat relays: one query session sitting in each relayed channel.
//!
//! 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`.
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{Mutex, broadcast, mpsc};
use tokio::task::JoinHandle;
use tracing::{debug, info, warn};
use tsc_model::{ChannelId, ChatMessage, ChatTarget, relay_text, split_message};
use tsc_query::{Command, Connect, Notification, QueryClient};
use crate::convert::is_text_message;
/// `clientupdate client_nickname=` with a name someone else has.
const ERR_NICKNAME_IN_USE: u32 = 513;
/// `clientmove` into the channel the client is already in.
const ERR_ALREADY_MEMBER: u32 = 770;
/// TeamSpeak's limit for one text message.
const MAX_MESSAGE_BYTES: usize = 1024;
#[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.
pub format: String,
}
impl RelayConfig {
pub fn new(connect: Connect) -> Self {
Self { connect, nickname: "Chat Relay".into(), format: "[{nick}] {text}".into() }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum RelayEvent {
/// Someone wrote in a relayed channel (our own posts are not echoed).
Message(ChatMessage),
/// A relay stopped (connection lost or closed).
Closed { channel: ChannelId, reason: String },
}
struct Session {
client: QueryClient,
task: JoinHandle<()>,
}
impl Drop for Session {
fn drop(&mut self) {
self.task.abort();
}
}
/// Manages relay sessions, at most one per channel.
#[derive(Clone)]
pub struct RelayPool {
config: Arc<RelayConfig>,
sessions: Arc<Mutex<HashMap<ChannelId, Session>>>,
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 }
}
pub fn subscribe(&self) -> broadcast::Receiver<RelayEvent> {
self.events.subscribe()
}
/// Channels with an open relay.
pub async fn channels(&self) -> Vec<ChannelId> {
self.sessions.lock().await.keys().copied().collect()
}
/// Start relaying a channel (no-op if already open).
pub async fn open(&self, channel: ChannelId) -> tsc_query::Result<()> {
let mut 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?;
let Some(notifications) = notifications else {
return Err(tsc_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;
match client.send(&Command::new("clientmove").arg("clid", own_id).arg("cid", channel)).await
{
// Query clients start in the default channel.
Err(tsc_query::Error::Query(e)) if e.id == ERR_ALREADY_MEMBER => {}
other => {
other?;
}
}
client.send(&Command::new("servernotifyregister").arg("event", "textchannel")).await?;
info!(channel, own_id, "relay opened");
let task = tokio::spawn(forward(channel, own_id, notifications, self.events.clone()));
sessions.insert(channel, Session { client, task });
Ok(())
}
/// 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");
}
}
/// 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");
}
}
/// Post `text` in `channel` on behalf of `nick`, opening a relay if needed.
pub async fn send(&self, channel: ChannelId, nick: &str, text: &str) -> tsc_query::Result<()> {
self.open(channel).await?;
let client = match self.sessions.lock().await.get(&channel) {
Some(s) => s.client.clone(),
None => return Err(tsc_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(())
}
}
/// 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) {
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,
Err(tsc_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue,
Err(e) => {
warn!(%e, %nickname, "could not set relay nickname");
return;
}
}
}
warn!(base, "all relay nicknames in use");
}
async fn forward(
channel: ChannelId,
own_id: u16,
mut notifications: mpsc::UnboundedReceiver<Notification>,
events: broadcast::Sender<RelayEvent>,
) {
while let Some(n) = notifications.recv().await {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default();
let Some(mut msg) = is_text_message(&n, now) else { continue };
if msg.author_id == Some(own_id) {
continue;
}
if msg.target == ChatTarget::Channel(0) {
msg.target = ChatTarget::Channel(channel);
}
debug!(channel, author = %msg.author_name, "relayed message");
let _ = events.send(RelayEvent::Message(msg));
}
let _ = events.send(RelayEvent::Closed { channel, reason: "connection closed".into() });
}
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "tsc-query"
version = "0.1.0"
description = "TeamSpeak ServerQuery client: raw TCP, SSH and HTTP WebQuery transports."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
reqwest = { version = "0.13.5", default-features = false, features = ["json", "query", "rustls"] }
russh = "0.63.3"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
thiserror = "2.0.21"
tokio = { version = "1.53.1", features = ["net", "io-util", "sync", "time", "rt", "macros"] }
tracing = "0.1.44"
[lints]
workspace = true
[dev-dependencies]
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "test-util"] }
+149
View File
@@ -0,0 +1,149 @@
//! Transport-independent query client.
use tokio::io::split;
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use crate::codec::{Command, Notification, Row};
use crate::http::HttpClient;
use crate::line::{LineClient, LineOptions};
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Transport {
Raw,
Ssh,
Http,
}
/// Everything needed to open a query connection.
#[derive(Clone, Debug)]
pub struct Connect {
pub transport: Transport,
/// host:port of the query interface.
pub addr: String,
/// Login name (raw/SSH). Ignored for HTTP.
pub user: String,
/// Password (raw/SSH) or API key (HTTP, optional for guest access).
pub secret: Option<String>,
/// Select the virtual server by voice port (`use port=`)...
pub server_port: Option<u16>,
/// ...or by id (defaults to 1).
pub server_id: Option<u32>,
pub line: LineOptions,
}
/// A logged-in query connection with a selected virtual server.
#[derive(Clone)]
pub enum QueryClient {
Line(LineClient),
Http(HttpClient),
}
impl QueryClient {
/// Connect, log in and select the virtual server. The event receiver is
/// `None` for HTTP, which has no events.
pub async fn connect(
cfg: &Connect,
) -> Result<(Self, Option<mpsc::UnboundedReceiver<Notification>>)> {
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());
let client = Self::Line(client);
client.login_and_use(cfg).await?;
Ok((client, Some(events)))
}
Transport::Ssh => {
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 (r, w) = split(shell.stream);
let (client, events) =
LineClient::spawn_with_guard(r, w, cfg.line.clone(), shell.session);
let client = Self::Line(client);
// SSH already authenticated; only select the server.
client.use_server(cfg).await?;
Ok((client, Some(events)))
}
Transport::Http => {
let base = if cfg.addr.contains("://") {
cfg.addr.clone()
} else {
format!("http://{}", cfg.addr)
};
let mut client =
HttpClient::new(&base, cfg.secret.clone(), cfg.server_id.unwrap_or(1))?;
if let Some(port) = cfg.server_port {
// Resolve the port to a server id once.
let servers = client.send(&Command::new("serverlist")).await?;
let sid = servers
.iter()
.find(|r| r.parse::<u16>("virtualserver_port") == Some(port))
.and_then(|r| r.parse("virtualserver_id"))
.ok_or_else(|| {
Error::Protocol(format!("no virtual server on port {port}"))
})?;
client.set_sid(sid);
}
Ok((Self::Http(client), None))
}
}
}
async fn login_and_use(&self, cfg: &Connect) -> Result<()> {
if let Some(password) = &cfg.secret {
self.send(
&Command::new("login")
.arg("client_login_name", &cfg.user)
.arg("client_login_password", password),
)
.await?;
}
self.use_server(cfg).await
}
async fn use_server(&self, cfg: &Connect) -> Result<()> {
let cmd = match (cfg.server_port, cfg.server_id) {
(Some(port), _) => Command::new("use").arg("port", port),
(None, sid) => Command::new("use").arg("sid", sid.unwrap_or(1)),
};
self.send(&cmd).await.map(|_| ())
}
pub async fn send(&self, cmd: &Command) -> Result<Vec<Row>> {
match self {
QueryClient::Line(c) => c.send(cmd).await,
QueryClient::Http(c) => c.send(cmd).await,
}
}
/// End the session politely (servers otherwise keep SSH query clients
/// around until they time out). HTTP has no session to end.
pub async fn quit(&self) {
if let QueryClient::Line(c) = self {
// The server closes the connection instead of answering.
let _ = tokio::time::timeout(
std::time::Duration::from_secs(2),
c.send(&Command::new("quit")),
)
.await;
}
}
/// Whether the transport delivers `notify*` events.
pub fn has_events(&self) -> bool {
matches!(self, QueryClient::Line(_))
}
/// Our own client id (`whoami`).
pub async fn own_client_id(&self) -> Result<u16> {
let rows = self.send(&Command::new("whoami")).await?;
rows.first()
.and_then(|r| r.parse("client_id"))
.ok_or_else(|| Error::Protocol("whoami without client_id".into()))
}
}
+352
View File
@@ -0,0 +1,352 @@
//! ServerQuery text format: escaping, commands, responses and events.
//!
//! A response is zero or more data lines followed by `error id=0 msg=ok`.
//! Data is a list of rows separated by `|`, each row a space-separated list of
//! `key=value` pairs. Events are lines starting with `notify`.
use std::fmt;
/// Escape a value for the query protocol.
pub fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'/' => out.push_str("\\/"),
' ' => out.push_str("\\s"),
'|' => out.push_str("\\p"),
'\x07' => out.push_str("\\a"),
'\x08' => out.push_str("\\b"),
'\x0c' => out.push_str("\\f"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\x0b' => out.push_str("\\v"),
c => out.push(c),
}
}
out
}
/// Reverse [`escape`]. Unknown escapes are kept as they are.
pub fn unescape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next() {
Some('\\') => out.push('\\'),
Some('/') => out.push('/'),
Some('s') => out.push(' '),
Some('p') => out.push('|'),
Some('a') => out.push('\x07'),
Some('b') => out.push('\x08'),
Some('f') => out.push('\x0c'),
Some('n') => out.push('\n'),
Some('r') => out.push('\r'),
Some('t') => out.push('\t'),
Some('v') => out.push('\x0b'),
Some(other) => {
out.push('\\');
out.push(other);
}
None => out.push('\\'),
}
}
out
}
/// One `key=value ...` group of a response or event. Keys keep their order;
/// a key without `=` has an empty value.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Row(pub Vec<(String, String)>);
impl Row {
pub fn get(&self, key: &str) -> Option<&str> {
self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
}
pub fn parse<T: std::str::FromStr>(&self, key: &str) -> Option<T> {
self.get(key)?.parse().ok()
}
/// `1` / `0` flags.
pub fn flag(&self, key: &str) -> Option<bool> {
self.get(key).map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
}
pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
let key = key.into();
let value = value.into();
match self.0.iter_mut().find(|(k, _)| *k == key) {
Some(entry) => entry.1 = value,
None => self.0.push((key, value)),
}
}
}
/// Parse `a=1 b=2|a=3` into rows. Keys shared by the first row are not
/// repeated by the server in later rows for some commands; callers that need
/// that should use [`Row::get`] on the first row as a fallback.
pub fn parse_rows(line: &str) -> Vec<Row> {
line.split('|')
.map(|part| {
Row(part
.split(' ')
.filter(|kv| !kv.is_empty())
.map(|kv| match kv.split_once('=') {
Some((k, v)) => (k.to_string(), unescape(v)),
None => (kv.to_string(), String::new()),
})
.collect())
})
.filter(|row| !row.0.is_empty())
.collect()
}
/// The `error` line that ends every response.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub struct QueryError {
pub id: u32,
pub msg: String,
pub extra_msg: Option<String>,
pub failed_permid: Option<u32>,
}
impl fmt::Display for QueryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({})", self.id, self.msg)?;
if let Some(extra) = &self.extra_msg {
write!(f, ": {extra}")?;
}
if let Some(perm) = self.failed_permid {
write!(f, " [failed permission {perm}]")?;
}
Ok(())
}
}
impl QueryError {
pub fn is_ok(&self) -> bool {
self.id == 0
}
/// The server has no data for a list command (`database empty result set`).
pub fn is_empty_result(&self) -> bool {
self.id == 1281
}
pub(crate) fn from_row(row: &Row) -> Self {
QueryError {
id: row.parse("id").unwrap_or(u32::MAX),
msg: row.get("msg").unwrap_or_default().to_string(),
extra_msg: row.get("extra_msg").map(str::to_string),
failed_permid: row.parse("failed_permid"),
}
}
}
/// An event, e.g. `notifycliententerview`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Notification {
/// Name including the `notify` prefix.
pub name: String,
pub rows: Vec<Row>,
}
/// A classified line from a line-based transport.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Line {
Error(QueryError),
Notify(Notification),
Data(Vec<Row>),
Empty,
}
pub fn parse_line(line: &str) -> Line {
let line = line.trim_matches(|c| c == '\r' || c == '\n');
if line.is_empty() {
return Line::Empty;
}
if let Some(rest) = line.strip_prefix("error ") {
let row = parse_rows(rest).into_iter().next().unwrap_or_default();
return Line::Error(QueryError::from_row(&row));
}
if line.starts_with("notify") {
let (name, rest) = line.split_once(' ').unwrap_or((line, ""));
return Line::Notify(Notification { name: name.to_string(), rows: parse_rows(rest) });
}
Line::Data(parse_rows(line))
}
/// A command to send, built with escaping applied.
///
/// ```
/// use tsc_query::Command;
/// let cmd = Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", "hi there");
/// assert_eq!(cmd.to_line(), "sendtextmessage targetmode=3 msg=hi\\sthere");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Command {
pub name: String,
/// Rows; the first row also carries the command-wide arguments.
pub rows: Vec<Vec<(String, String)>>,
pub flags: Vec<String>,
}
impl Command {
pub fn new(name: impl Into<String>) -> Self {
Self { name: name.into(), rows: vec![Vec::new()], flags: Vec::new() }
}
/// Add an argument to the current row.
pub fn arg(mut self, key: impl Into<String>, value: impl fmt::Display) -> Self {
self.rows.last_mut().unwrap().push((key.into(), value.to_string()));
self
}
/// Start a new `|`-separated row.
pub fn row(mut self) -> Self {
self.rows.push(Vec::new());
self
}
/// Add an option like `-uid`.
pub fn flag(mut self, flag: impl Into<String>) -> Self {
let flag = flag.into();
self.flags.push(if flag.starts_with('-') { flag } else { format!("-{flag}") });
self
}
/// Parse an escaped command line such as `clientlist -uid` or
/// `clientmove clid=5 cid=2|clid=6`.
pub fn parse(line: &str) -> Option<Self> {
let line = line.trim();
let (name, rest) = line.split_once(' ').unwrap_or((line, ""));
if name.is_empty() {
return None;
}
let mut cmd = Command::new(name);
for (i, part) in rest.split('|').enumerate() {
if i > 0 {
cmd = cmd.row();
}
for token in part.split(' ').filter(|t| !t.is_empty()) {
if token.starts_with('-') && !token.contains('=') {
cmd.flags.push(token.to_string());
} else {
let (k, v) = token.split_once('=').unwrap_or((token, ""));
cmd = cmd.arg(k, unescape(v));
}
}
}
Some(cmd)
}
/// Render for line-based transports (no trailing newline).
pub fn to_line(&self) -> String {
let mut out = self.name.clone();
for (i, row) in self.rows.iter().enumerate() {
if i > 0 {
out.push('|');
} else if !row.is_empty() {
out.push(' ');
}
let parts: Vec<String> =
row.iter().map(|(k, v)| format!("{k}={}", escape(v))).collect();
out.push_str(&parts.join(" "));
}
for flag in &self.flags {
out.push(' ');
out.push_str(flag);
}
out
}
}
impl fmt::Display for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_line())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escape_roundtrip() {
let s = "a b|c\\d/e\nf\tg";
assert_eq!(escape(s), "a\\sb\\pc\\\\d\\/e\\nf\\tg");
assert_eq!(unescape(&escape(s)), s);
assert_eq!(unescape("trailing\\"), "trailing\\");
assert_eq!(unescape("\\x"), "\\x");
}
#[test]
fn parses_lines() {
assert_eq!(parse_line("\n\r"), Line::Empty);
match parse_line("error id=1281 msg=database\\sempty\\sresult\\sset\n\r") {
Line::Error(e) => {
assert!(e.is_empty_result());
assert_eq!(e.msg, "database empty result set");
}
other => panic!("{other:?}"),
}
match parse_line("notifytextmessage targetmode=3 msg=hi\\sall invokerid=5 invokername=Bob")
{
Line::Notify(n) => {
assert_eq!(n.name, "notifytextmessage");
assert_eq!(n.rows[0].get("msg"), Some("hi all"));
assert_eq!(n.rows[0].parse::<u16>("invokerid"), Some(5));
}
other => panic!("{other:?}"),
}
match parse_line("clid=1 cid=1 client_nickname=A|clid=2 cid=3 client_nickname=B\\sC") {
Line::Data(rows) => {
assert_eq!(rows.len(), 2);
assert_eq!(rows[1].get("client_nickname"), Some("B C"));
}
other => panic!("{other:?}"),
}
}
#[test]
fn builds_commands() {
let cmd = Command::new("clientlist").flag("uid").flag("-away");
assert_eq!(cmd.to_line(), "clientlist -uid -away");
let cmd = Command::new("clientkick").arg("clid", 1).row().arg("clid", 2).arg("reasonid", 5);
assert_eq!(cmd.to_line(), "clientkick clid=1|clid=2 reasonid=5");
let cmd = Command::new("login")
.arg("client_login_name", "a b")
.arg("client_login_password", "p|w");
assert_eq!(cmd.to_line(), "login client_login_name=a\\sb client_login_password=p\\pw");
}
#[test]
fn parses_command_lines() {
let line = r"clientmove clid=5 cid=2 cpw=a\sb|clid=6 -continueonerror";
let cmd = Command::parse(line).unwrap();
assert_eq!(cmd.name, "clientmove");
assert_eq!(cmd.rows.len(), 2);
assert_eq!(cmd.rows[0][2], ("cpw".to_string(), "a b".to_string()));
assert_eq!(cmd.flags, vec!["-continueonerror"]);
assert_eq!(cmd.to_line(), line);
assert!(Command::parse(" ").is_none());
}
#[test]
fn row_helpers() {
let mut row = parse_rows("a=1 b=0 c").remove(0);
assert_eq!(row.flag("a"), Some(true));
assert_eq!(row.flag("b"), Some(false));
assert_eq!(row.get("c"), Some(""));
row.insert("b", "7");
row.insert("d", "x");
assert_eq!(row.parse::<i32>("b"), Some(7));
assert_eq!(row.get("d"), Some("x"));
}
}
+93
View File
@@ -0,0 +1,93 @@
//! HTTP WebQuery: `GET /<sid>/<command>?key=value` with an `x-api-key` header,
//! answered with JSON `{"body": [...], "status": {"code": 0, "message": "ok"}}`.
use serde::Deserialize;
use crate::codec::{Command, QueryError, Row};
use crate::{Error, Result};
#[derive(Clone)]
pub struct HttpClient {
http: reqwest::Client,
base: String,
api_key: Option<String>,
sid: u32,
}
#[derive(Deserialize)]
struct Status {
code: u32,
message: String,
#[serde(default)]
extra_message: Option<String>,
#[serde(default)]
failed_permission: Option<serde_json::Value>,
}
#[derive(Deserialize)]
struct Reply {
#[serde(default)]
body: Vec<serde_json::Map<String, serde_json::Value>>,
status: Status,
}
impl HttpClient {
/// `base` is e.g. `http://host:10080`. Without an API key requests run
/// with the server's guest query permissions.
pub fn new(base: &str, api_key: Option<String>, sid: u32) -> Result<Self> {
let http = reqwest::Client::builder().build()?;
Ok(Self { http, base: base.trim_end_matches('/').to_string(), api_key, sid })
}
pub fn set_sid(&mut self, sid: u32) {
self.sid = sid;
}
pub async fn send(&self, cmd: &Command) -> Result<Vec<Row>> {
// Multi-row commands are not expressible as query parameters.
if cmd.rows.len() > 1 {
return Err(Error::Unsupported("multi-row commands over HTTP"));
}
// Instance-level commands have no server id in the path.
let url = if matches!(cmd.name.as_str(), "serverlist" | "version" | "hostinfo") {
format!("{}/{}", self.base, cmd.name)
} else {
format!("{}/{}/{}", self.base, self.sid, cmd.name)
};
let mut params: Vec<(String, String)> = cmd.rows[0].clone();
params.extend(cmd.flags.iter().map(|f| (f.clone(), String::new())));
let mut req = self.http.get(url).query(&params);
if let Some(key) = &self.api_key {
req = req.header("x-api-key", key);
}
let reply: Reply = req.send().await?.json().await?;
if reply.status.code != 0 && reply.status.code != 1281 {
return Err(QueryError {
id: reply.status.code,
msg: reply.status.message,
extra_msg: reply.status.extra_message.or_else(|| {
reply.status.failed_permission.map(|p| format!("missing permission {p}"))
}),
failed_permid: None,
}
.into());
}
Ok(reply
.body
.into_iter()
.map(|obj| {
Row(obj
.into_iter()
.map(|(k, v)| {
let v = match v {
serde_json::Value::String(s) => s,
serde_json::Value::Null => String::new(),
other => other.to_string(),
};
(k, v)
})
.collect())
})
.collect())
}
}
+50
View File
@@ -0,0 +1,50 @@
//! TeamSpeak ServerQuery client.
//!
//! ServerQuery is the admin/bot interface of TeamSpeak servers. Query clients
//! are invisible to normal users, which is what makes invisible presence and
//! channel-chat relays possible.
//!
//! Transports:
//! - raw TCP (TeamSpeak 3, port 10011) and SSH (both, port 10022): line based,
//! with asynchronous `notify*` events ([`LineClient`])
//! - HTTP WebQuery (TeamSpeak 6 and 3.12+, port 10080): request/response only,
//! authenticated with an API key ([`HttpClient`])
//!
//! [`QueryClient`] hides the difference for code that only sends commands.
mod client;
mod codec;
mod http;
mod line;
mod ssh;
pub use client::{Connect, QueryClient, Transport};
pub use codec::{
Command, Line, Notification, QueryError, Row, escape, parse_line, parse_rows, unescape,
};
pub use http::HttpClient;
pub use line::{LineClient, LineOptions};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("ssh: {0}")]
Ssh(#[from] russh::Error),
#[error("ssh authentication failed")]
SshAuth,
#[error("http: {0}")]
Http(#[from] reqwest::Error),
#[error("server error {0}")]
Query(#[from] QueryError),
#[error("protocol: {0}")]
Protocol(String),
#[error("connection closed")]
Closed,
#[error("timed out")]
Timeout,
#[error("not supported by this transport: {0}")]
Unsupported(&'static str),
}
pub type Result<T> = std::result::Result<T, Error>;
+314
View File
@@ -0,0 +1,314 @@
//! Client for the line-based transports (raw TCP and SSH).
//!
//! A background task owns the connection. Commands are sent one at a time
//! (the protocol has no request ids); `notify*` lines are forwarded to an
//! event channel whenever they arrive.
use std::collections::VecDeque;
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 crate::codec::{Command, Line, Notification, Row, parse_line};
use crate::{Error, Result};
#[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.
pub rate_limit: Option<(u32, Duration)>,
/// Give up on a command after this long.
pub timeout: Duration,
}
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))),
timeout: Duration::from_secs(15),
}
}
}
type Reply = oneshot::Sender<Result<Vec<Row>>>;
struct Request {
line: String,
reply: Reply,
}
/// Handle to a line-based query connection. Cheap to clone.
#[derive(Clone)]
pub struct LineClient {
requests: mpsc::Sender<Request>,
timeout: Duration,
}
impl LineClient {
/// Start the connection task. Returns the client and the event stream.
pub fn spawn<R, W>(
reader: R,
writer: W,
options: LineOptions,
) -> (Self, mpsc::UnboundedReceiver<Notification>)
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
Self::spawn_with_guard(reader, writer, options, ())
}
/// Like [`LineClient::spawn`], keeping `guard` alive as long as the
/// connection task runs (e.g. an SSH session handle).
pub fn spawn_with_guard<R, W, G>(
reader: R,
writer: W,
options: LineOptions,
guard: G,
) -> (Self, mpsc::UnboundedReceiver<Notification>)
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
G: Send + 'static,
{
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)
}
/// Send a command and collect its data rows.
pub async fn send(&self, cmd: &Command) -> Result<Vec<Row>> {
self.send_line(cmd.to_line()).await
}
/// Send an already formatted command line.
pub async fn send_line(&self, line: String) -> Result<Vec<Row>> {
let (reply, rx) = oneshot::channel();
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),
}
}
pub fn is_closed(&self) -> bool {
self.requests.is_closed()
}
}
/// Token bucket for the query flood protection.
struct RateLimiter {
limit: Option<(u32, Duration)>,
sent: VecDeque<Instant>,
}
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)
}
}
fn record(&mut self, t: Instant) {
if self.limit.is_some() {
self.sent.push_back(t);
}
}
}
async fn run<R, W>(
mut reader: BufReader<R>,
mut writer: W,
mut requests: mpsc::Receiver<Request>,
events: mpsc::UnboundedSender<Notification>,
options: LineOptions,
) where
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 mut last_activity = Instant::now();
let mut buf = Vec::new();
loop {
let can_send = pending.is_none() && !keepalive_pending;
let keepalive_at = last_activity + options.keepalive;
tokio::select! {
read = reader.read_until(b'\n', &mut buf) => {
match read {
Ok(0) | Err(_) => {
debug!("query connection closed");
break;
}
Ok(_) => {}
}
let text = String::from_utf8_lossy(&buf).into_owned();
buf.clear();
trace!(line = %text.trim(), "query <");
match parse_line(&text) {
Line::Empty => {}
Line::Notify(n) => {
let _ = events.send(n);
}
// Response data always has key=value pairs; lines without
// 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);
}
}
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);
}
}
}
}
req = requests.recv(), if can_send => {
let Some(req) = req else { break };
let slot = limiter.next_slot(Instant::now());
if slot > Instant::now() {
sleep_until(slot).await;
}
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() {
break;
}
last_activity = Instant::now();
keepalive_pending = true;
}
}
}
if let Some((reply, _)) = pending {
let _ = reply.send(Err(Error::Closed));
}
debug!("query connection task ended");
}
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?;
writer.flush().await
}
#[cfg(test)]
mod tests {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, duplex};
use super::*;
/// A scripted fake server: answers each command from `script` in order.
async fn fake_server(
stream: tokio::io::DuplexStream,
script: Vec<(&'static str, &'static str)>,
) {
let (r, mut w) = tokio::io::split(stream);
let mut r = BufReader::new(r);
w.write_all(b"TS3\n\rWelcome to the TeamSpeak 3 ServerQuery interface.\n\r").await.unwrap();
for (expect, answer) in script {
let mut line = String::new();
r.read_line(&mut line).await.unwrap();
assert_eq!(line.trim_end(), expect);
w.write_all(answer.as_bytes()).await.unwrap();
}
}
#[tokio::test]
async fn request_response_and_events() {
let (client_io, server_io) = duplex(4096);
let server = tokio::spawn(fake_server(
server_io,
vec![
(
"login client_login_name=serveradmin client_login_password=pw",
"error id=0 msg=ok\n\r",
),
(
"clientlist -uid",
"clid=1 client_nickname=A|clid=2 client_nickname=B\\sC\n\r\
notifycliententerview clid=3 client_nickname=D\n\r\
error id=0 msg=ok\n\r",
),
("use sid=9", "error id=1024 msg=invalid\\sserverID\n\r"),
("channellist", "error id=1281 msg=database\\sempty\\sresult\\sset\n\r"),
],
));
let (r, w) = tokio::io::split(client_io);
let (client, mut events) =
LineClient::spawn(r, w, LineOptions { rate_limit: None, ..Default::default() });
let login = Command::new("login")
.arg("client_login_name", "serveradmin")
.arg("client_login_password", "pw");
assert!(client.send(&login).await.unwrap().is_empty());
let rows = client.send(&Command::new("clientlist").flag("uid")).await.unwrap();
assert_eq!(rows.len(), 2);
assert_eq!(rows[1].get("client_nickname"), Some("B C"));
let event = events.recv().await.unwrap();
assert_eq!(event.name, "notifycliententerview");
match client.send(&Command::new("use").arg("sid", 9)).await {
Err(Error::Query(e)) => assert_eq!(e.id, 1024),
other => panic!("{other:?}"),
}
// "empty result set" is an empty list, not an error.
assert!(client.send(&Command::new("channellist")).await.unwrap().is_empty());
server.await.unwrap();
}
#[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() };
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));
let later = t0 + Duration::from_secs(4);
assert_eq!(limiter.next_slot(later), later);
}
}
+59
View File
@@ -0,0 +1,59 @@
//! SSH transport: password login, then the query runs in the shell channel.
use std::sync::Arc;
use std::time::Duration;
use russh::client;
use russh::keys::PublicKeyOrCertificate;
use crate::{Error, Result};
/// Accepts any host key. ServerQuery hosts generate their key on first start
/// and there is no out-of-band way to learn it; callers that care can pin the
/// fingerprint returned by [`connect`].
pub(crate) struct AcceptAny {
fingerprint: Arc<std::sync::Mutex<Option<String>>>,
}
impl client::Handler for AcceptAny {
type Error = russh::Error;
async fn check_server_key(
&mut self,
key: &PublicKeyOrCertificate,
) -> std::result::Result<bool, Self::Error> {
if let PublicKeyOrCertificate::PublicKey { key, .. } = key {
*self.fingerprint.lock().unwrap() =
Some(key.fingerprint(russh::keys::HashAlg::Sha256).to_string());
}
Ok(true)
}
}
/// An open SSH shell channel. The session handle is kept with it because the
/// connection closes when the handle is dropped.
pub(crate) struct Shell {
pub stream: russh::ChannelStream<client::Msg>,
pub session: client::Handle<AcceptAny>,
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> {
let config = Arc::new(client::Config {
inactivity_timeout: None,
keepalive_interval: Some(Duration::from_secs(60)),
..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 auth = session.authenticate_password(user, password).await?;
if !auth.success() {
return Err(Error::SshAuth);
}
let channel = session.channel_open_session().await?;
channel.request_shell(true).await?;
let fingerprint = fingerprint.lock().unwrap().clone();
Ok(Shell { stream: channel.into_stream(), session, fingerprint })
}
+13 -1
View File
@@ -6,6 +6,10 @@
# Each server prints a one-time ServerAdmin privilege key to its log on first
# start; the smoke test reads it from there. `down -v` resets the servers.
#
# ServerQuery: every interface is enabled with the fixed development password
# `tsc-dev-admin` for the `serveradmin` login (TS3: raw 10011, SSH 10023,
# HTTP 10081; TS6: SSH 10022, HTTP 10080). Never use these settings in production.
#
# query_ip_allowlist.txt allowlists private ranges: clients reach the servers
# through the Docker bridge, and allowlisted IPs skip the anti-flood bans that
# rapid test connections would otherwise trigger. Development use only.
@@ -21,9 +25,13 @@ services:
environment:
TS3SERVER_LICENSE: accept
TS3SERVER_IP_ALLOWLIST: /etc/ts3server/query_ip_allowlist.txt
TS3SERVER_SERVERADMIN_PASSWORD: tsc-dev-admin
TS3SERVER_QUERY_PROTOCOLS: raw,ssh,http
ports:
- "9987:9987/udp" # voice
- "10011:10011" # raw ServerQuery
- "10023:10022" # SSH ServerQuery
- "10081:10080" # HTTP WebQuery
- "30033:30033" # file transfer
volumes:
- ts3-data:/var/ts3server
@@ -34,6 +42,10 @@ services:
image: ${REGISTRY:-docker.io}/teamspeaksystems/teamspeak6-server@sha256:d845f803aecf842c2df034c959c23ff2462357bacafb3807500885c5ec170fa1
environment:
TSSERVER_LICENSE_ACCEPTED: accept
TSSERVER_QUERY_ADMIN_PASSWORD: tsc-dev-admin
TSSERVER_QUERY_SSH_ENABLED: 1
TSSERVER_QUERY_HTTP_ENABLED: 1
TSSERVER_QUERY_ALLOW_LIST: /etc/tsserver/query_ip_allowlist.txt
ports:
- "9988:9987/udp" # voice (mapped to 9988 so both servers can run)
- "10022:10022" # SSH ServerQuery
@@ -41,7 +53,7 @@ services:
- "30034:30033" # file transfer
volumes:
- ts6-data:/var/tsserver
- ./query_ip_allowlist.txt:/var/tsserver/query_ip_allowlist.txt:ro
- ./query_ip_allowlist.txt:/etc/tsserver/query_ip_allowlist.txt:ro
volumes:
ts3-data:
+16
View File
@@ -20,6 +20,22 @@ facts constrain it, how the code is organised, and the milestone order.
- TeamSpeak 6 servers still accept the TeamSpeak 3 client protocol; verified with
`tsctl` against 6.0.0-beta13.1.
### What "invisible" means for query clients (verified on 3.13.8 and 6.0.0-beta13.1)
The server does not hide ServerQuery clients: every client subscribed to a
channel receives `notifycliententerview` for query clients in it too
(`client_type=1`). Official clients hide a query client when its
`client_needed_serverquery_view_power` (100 for `serveradmin` by default) is
higher than the viewer's `i_client_serverquery_view_power` (only Server Admins
have it by default). So observers and relays are invisible to normal users of
official clients, visible to admins, and visible to third-party clients that
ignore the rule. This client applies the same rule.
TeamSpeak 6 ships with SSH and HTTP query disabled
(`TSSERVER_QUERY_SSH_ENABLED`, `TSSERVER_QUERY_HTTP_ENABLED`). HTTP guest
access (`query-http-allow-guest`, on by default) lacks list permissions unless
the admin grants them to the guest query group.
## How each feature is delivered
| Feature | Mechanism |
+51
View File
@@ -7,6 +7,8 @@
# 2. server chat between two clients
# 3. channel chat between two clients
# 4. voice: a 1 kHz tone sent by one client is recorded by another
# 5. invisible presence: a ServerQuery observer sees a voice client join
# 6. relay chat: a query relay reads channel chat and posts into the channel
#
# Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both)
# Env: TSCTL=path/to/tsctl (default: builds target/debug/tsctl)
@@ -28,6 +30,9 @@ if [[ -z "${TSCTL:-}" ]]; then
fi
declare -A PORTS=([ts3]=9987 [ts6]=9988)
# ServerQuery transport and address per server (dev/docker-compose.yml).
declare -A QUERY=([ts3]="raw 127.0.0.1:10011" [ts6]="ssh 127.0.0.1:10022")
QUERY_SECRET=tsc-dev-admin
SERVERS=("$@")
[[ ${#SERVERS[@]} -eq 0 ]] && SERVERS=(ts3 ts6)
@@ -99,6 +104,50 @@ voice_roundtrip() {
grep "tone ratio" "$out"
}
# An observer over ServerQuery must see a voice client join.
presence_check() {
local addr=$1 query=$2 out="$STATE_DIR/observe.log"
# shellcheck disable=SC2086
"$TSCTL" observe $query --secret "$QUERY_SECRET" --allowlisted --poll 2 \
--seconds 20 --expect-client presence-probe >"$out" 2>&1 &
local observer=$!
sleep 2
"$TSCTL" connect "$addr" --nick presence-probe listen --timeout 4 >/dev/null 2>&1 || true
if ! wait "$observer"; then
cat "$out"
fail "observer did not see the voice client"
fi
grep "presence-probe" "$out"
}
# A relay reads a voice client's channel message and posts one back.
relay_check() {
local addr=$1 query=$2 out="$STATE_DIR/relay.log" heard="$STATE_DIR/relay-heard.log"
local token="relay-$RANDOM$RANDOM"
# shellcheck disable=SC2086
"$TSCTL" relay $query --secret "$QUERY_SECRET" --allowlisted --channel 1 \
--expect "to-relay-$token" --seconds 20 >"$out" 2>&1 &
local relay=$!
"$TSCTL" connect "$addr" --nick relay-listener listen --expect "from-relay-$token" \
--timeout 20 >"$heard" 2>&1 &
local listener=$!
sleep 4
"$TSCTL" connect "$addr" --nick relay-talker chat channel "to-relay-$token"
# shellcheck disable=SC2086
"$TSCTL" relay $query --secret "$QUERY_SECRET" --allowlisted --channel 1 --nick Alice \
--send "from-relay-$token" --seconds 1 >/dev/null
if ! wait "$relay"; then
cat "$out"
fail "relay did not receive the channel message"
fi
if ! wait "$listener"; then
cat "$heard"
fail "voice client did not receive the relayed post"
fi
grep "to-relay-$token" "$out"
grep "from-relay-$token" "$heard"
}
for svc in "${SERVERS[@]}"; do
port=${PORTS[$svc]:?unknown server $svc}
addr="127.0.0.1:$port"
@@ -114,6 +163,8 @@ for svc in "${SERVERS[@]}"; do
chat_roundtrip "$addr" server "$admin"
chat_roundtrip "$addr" channel ""
voice_roundtrip "$addr"
presence_check "$addr" "${QUERY[$svc]}"
relay_check "$addr" "${QUERY[$svc]}"
done
log "all smoke tests passed"
+2
View File
@@ -21,6 +21,8 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tsclientlib = { path = "../../crates/proto/tsclientlib" }
tsproto-packets = { path = "../../crates/proto/tsproto-packets" }
tsc-model = { path = "../../crates/tsc-model" }
tsc-query = { path = "../../crates/tsc-query" }
tsc-observer = { path = "../../crates/tsc-observer" }
tsc-audio = { path = "../../crates/tsc-audio", default-features = false }
[lints]
+11
View File
@@ -1,6 +1,8 @@
//! `tsctl`: headless TeamSpeak 3/6 client for development and integration tests.
mod identity;
mod observe;
mod query;
mod session;
mod tree;
mod versions;
@@ -34,6 +36,12 @@ enum Command {
},
/// Connect to a server and run an action.
Connect(ConnectArgs),
/// Run ServerQuery commands (raw TCP, SSH or HTTP WebQuery).
Query(query::QueryArgs),
/// Watch who is in which channel through ServerQuery, without appearing on the server.
Observe(observe::ObserveArgs),
/// Read and write a channel's chat through an invisible query relay.
Relay(observe::RelayArgs),
}
#[derive(Subcommand, Debug)]
@@ -190,6 +198,9 @@ fn main() -> Result<()> {
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(session::run(args))
}
Command::Query(args) => tokio::runtime::Runtime::new()?.block_on(query::run(args)),
Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)),
Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)),
}
}
+227
View File
@@ -0,0 +1,227 @@
//! `tsctl observe` and `tsctl relay`: invisible presence and channel chat.
use std::time::Duration;
use anyhow::{Result, bail};
use clap::Args;
use tokio::sync::broadcast::error::RecvError;
use tokio::time::{Instant, timeout_at};
use tsc_model::{ChatMessage, ChatTarget, Presence, PresenceDelta};
use tsc_observer::{Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool};
use crate::query::QueryConnArgs;
#[derive(Args, Debug, Clone)]
pub struct ObserveArgs {
#[command(flatten)]
pub conn: QueryConnArgs,
/// Stop after this many seconds (default: until Ctrl-C).
#[arg(long)]
pub seconds: Option<u64>,
/// Print events as JSON lines.
#[arg(long)]
pub json: bool,
/// Resync interval in seconds.
#[arg(long, default_value_t = 10)]
pub poll: u64,
/// Exit successfully once a client with this nickname is seen (for tests).
#[arg(long)]
pub expect_client: Option<String>,
}
#[derive(Args, Debug, Clone)]
pub struct RelayArgs {
#[command(flatten)]
pub conn: QueryConnArgs,
/// Channel id to relay.
#[arg(long)]
pub channel: u64,
/// Post this message after opening the relay.
#[arg(long)]
pub send: Option<String>,
/// Name shown in relayed posts.
#[arg(long, default_value = "tsctl")]
pub nick: String,
/// Stop after this many seconds (default: until Ctrl-C).
#[arg(long)]
pub seconds: Option<u64>,
/// Exit successfully once a message containing this text arrives.
#[arg(long)]
pub expect: Option<String>,
}
fn print_chat(msg: &ChatMessage) {
let target = match &msg.target {
ChatTarget::Server => "server".to_string(),
ChatTarget::Channel(cid) => format!("channel {cid}"),
ChatTarget::Private(_) => "private".to_string(),
};
println!("[{target}] {}: {}", msg.author_name, msg.text);
}
fn print_tree(p: &Presence) {
let channels: Vec<_> = p
.channels
.values()
.map(|c| crate::tree::ChannelNode {
id: tsclientlib::ChannelId(c.id),
parent: tsclientlib::ChannelId(c.parent),
order: tsclientlib::ChannelId(c.order),
name: c.name.clone(),
})
.collect();
let clients: Vec<_> = p
.clients
.values()
.map(|c| crate::tree::ClientNode {
channel: tsclientlib::ChannelId(c.channel),
name: c.nickname.clone(),
talk_power: 0,
is_query: c.is_query,
input_muted: c.input_muted,
output_muted: c.output_muted,
away: c.away.is_some(),
streaming: c.streaming == Some(true),
})
.collect();
print!(
"{}",
crate::tree::render(
&format!("{} (via query, invisible)", p.server_name),
&channels,
&clients
)
);
}
fn describe(p: &Presence, d: &PresenceDelta) -> String {
let name = |id: &u16| {
p.clients.get(id).map(|c| c.nickname.clone()).unwrap_or_else(|| format!("clid {id}"))
};
let channel = |id: &u64| {
p.channels.get(id).map(|c| c.name.clone()).unwrap_or_else(|| format!("cid {id}"))
};
match d {
PresenceDelta::ClientJoined(c) => format!("+ {} in #{}", c.nickname, channel(&c.channel)),
PresenceDelta::ClientLeft { id } => format!("- {} left", name(id)),
PresenceDelta::ClientMoved { id, channel: to } => {
format!("> {} moved to #{}", name(id), channel(to))
}
PresenceDelta::ClientChanged(c) => format!(
"~ {} changed (muted: {}, away: {})",
c.nickname,
c.input_muted,
c.away.is_some()
),
PresenceDelta::ChannelAdded(c) => format!("+ channel #{}", c.name),
PresenceDelta::ChannelChanged(c) => format!("~ channel #{}", c.name),
PresenceDelta::ChannelRemoved { id } => format!("- channel {}", channel(id)),
PresenceDelta::ServerRenamed { name } => format!("~ server renamed to {name}"),
}
}
pub async fn observe(args: ObserveArgs) -> Result<()> {
let mut config = ObserverConfig::new(args.conn.connect_config());
config.poll_interval = Duration::from_secs(args.poll);
let observer = Observer::spawn(config);
let mut events = observer.subscribe();
let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s));
loop {
let next = async {
match deadline {
Some(d) => timeout_at(d, events.recv()).await.ok(),
None => Some(events.recv().await),
}
};
let event = tokio::select! {
e = next => e,
_ = tokio::signal::ctrl_c() => return Ok(()),
};
let event = match event {
None => break,
Some(Ok(e)) => e,
Some(Err(RecvError::Lagged(n))) => {
eprintln!("(missed {n} events)");
continue;
}
Some(Err(RecvError::Closed)) => bail!("observer stopped"),
};
let presence = observer.presence();
let presence = presence.read().unwrap().clone();
if args.json {
match &event {
ObserverEvent::Snapshot(s) => println!("{}", serde_json::to_string(s)?),
ObserverEvent::Delta(d) => println!("{}", serde_json::to_string(d)?),
ObserverEvent::Chat(m) => println!("{}", serde_json::to_string(m)?),
ObserverEvent::Disconnected(r) => {
println!("{}", serde_json::json!({"disconnected": r}))
}
}
} else {
match &event {
ObserverEvent::Snapshot(_) => print_tree(&presence),
ObserverEvent::Delta(d) => println!("{}", describe(&presence, d)),
ObserverEvent::Chat(m) => print_chat(m),
ObserverEvent::Disconnected(r) => println!("! disconnected: {r}"),
}
}
if let Some(nick) = &args.expect_client
&& presence.clients.values().any(|c| &c.nickname == nick)
{
return Ok(());
}
}
if let Some(nick) = &args.expect_client {
bail!("client {nick:?} not seen");
}
Ok(())
}
pub async fn relay(args: RelayArgs) -> Result<()> {
let pool = RelayPool::new(RelayConfig::new(args.conn.connect_config()));
let mut events = pool.subscribe();
pool.open(args.channel).await?;
println!("relaying channel {}", args.channel);
if let Some(text) = &args.send {
pool.send(args.channel, &args.nick, text).await?;
println!("sent");
}
let result = relay_loop(&args, &mut events).await;
pool.close_all().await;
result
}
async fn relay_loop(
args: &RelayArgs,
events: &mut tokio::sync::broadcast::Receiver<RelayEvent>,
) -> Result<()> {
let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s));
loop {
let next = async {
match deadline {
Some(d) => timeout_at(d, events.recv()).await.ok(),
None => Some(events.recv().await),
}
};
let event = tokio::select! {
e = next => e,
_ = tokio::signal::ctrl_c() => return Ok(()),
};
match event {
None => break,
Some(Ok(RelayEvent::Message(m))) => {
print_chat(&m);
if args.expect.as_ref().is_some_and(|e| m.text.contains(e.as_str())) {
return Ok(());
}
}
Some(Ok(RelayEvent::Closed { reason, .. })) => bail!("relay closed: {reason}"),
Some(Err(RecvError::Lagged(_))) => {}
Some(Err(RecvError::Closed)) => break,
}
}
if let Some(expect) = &args.expect {
bail!("no message containing {expect:?}");
}
Ok(())
}
+118
View File
@@ -0,0 +1,118 @@
//! `tsctl query`: ServerQuery commands and events.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use clap::Args;
use tokio::io::{AsyncBufReadExt, BufReader};
use tsc_query::{Command, Connect, LineOptions, QueryClient, Row, Transport};
/// How to reach and log into a ServerQuery interface.
#[derive(Args, Debug, Clone)]
pub struct QueryConnArgs {
/// Transport: raw (TS3 only), ssh or http.
#[arg(value_enum)]
pub transport: TransportArg,
/// host:port of the query interface (e.g. 127.0.0.1:10022).
pub addr: String,
/// Login name (raw/SSH).
#[arg(long, default_value = "serveradmin")]
pub user: String,
/// Password (raw/SSH) or API key (HTTP). Without it, HTTP runs as guest.
#[arg(long, env = "TSCTL_QUERY_SECRET", hide_env_values = true)]
pub secret: Option<String>,
/// Select the virtual server by its voice port instead of id 1.
#[arg(long)]
pub server_port: Option<u16>,
/// Our IP is on the server's query allowlist: skip client-side rate limiting.
#[arg(long)]
pub allowlisted: bool,
}
#[derive(Args, Debug, Clone)]
pub struct QueryArgs {
#[command(flatten)]
pub conn: QueryConnArgs,
/// After the commands, print events for this many seconds.
#[arg(long)]
pub events: Option<u64>,
/// Command line to run, e.g. `clientlist -uid`. Without one, commands are read from stdin.
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
pub command: Vec<String>,
}
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub enum TransportArg {
Raw,
Ssh,
Http,
}
impl QueryConnArgs {
pub fn connect_config(&self) -> Connect {
Connect {
transport: match self.transport {
TransportArg::Raw => Transport::Raw,
TransportArg::Ssh => Transport::Ssh,
TransportArg::Http => Transport::Http,
},
addr: self.addr.clone(),
user: self.user.clone(),
secret: self.secret.clone(),
server_port: self.server_port,
server_id: None,
line: LineOptions {
rate_limit: if self.allowlisted { None } else { LineOptions::default().rate_limit },
..Default::default()
},
}
}
}
pub fn print_rows(rows: &[Row]) {
for row in rows {
let fields: Vec<String> = row.0.iter().map(|(k, v)| format!("{k}={v}")).collect();
println!("{}", fields.join(" "));
}
}
pub async fn run(args: QueryArgs) -> Result<()> {
let (client, events) = QueryClient::connect(&args.conn.connect_config())
.await
.context("query connection failed")?;
if args.command.is_empty() {
let mut lines = BufReader::new(tokio::io::stdin()).lines();
while let Some(line) = lines.next_line().await? {
if line.trim().is_empty() {
continue;
}
run_line(&client, &line).await;
}
} else {
let line = args.command.join(" ");
let Some(cmd) = Command::parse(&line) else { bail!("empty command") };
print_rows(&client.send(&cmd).await?);
}
if let Some(secs) = args.events {
let Some(mut events) = events else { bail!("this transport has no events") };
let deadline = tokio::time::Instant::now() + Duration::from_secs(secs);
while let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.recv()).await {
print!("{}: ", event.name);
print_rows(&event.rows);
}
}
Ok(())
}
async fn run_line(client: &QueryClient, line: &str) {
let Some(cmd) = Command::parse(line) else { return };
match client.send(&cmd).await {
Ok(rows) => {
print_rows(&rows);
println!("ok");
}
Err(error) => println!("error: {error}"),
}
}