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:
1 parent
6ab7b292b0
commit
a8a03661b9
25 files changed
+3555
-52
No files matched your search
@@ -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"}"#);
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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(¬ify("notifyclientleftview clid=1"), 0).is_none());
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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() });
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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()))
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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(¶ms);
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
Reference in new issue
Block a user