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

+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 })
}