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:
25 files changed
+3555
-52
No files matched your search
@@ -21,6 +21,8 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tsclientlib = { path = "../../crates/proto/tsclientlib" }
|
||||
tsproto-packets = { path = "../../crates/proto/tsproto-packets" }
|
||||
tsc-model = { path = "../../crates/tsc-model" }
|
||||
tsc-query = { path = "../../crates/tsc-query" }
|
||||
tsc-observer = { path = "../../crates/tsc-observer" }
|
||||
tsc-audio = { path = "../../crates/tsc-audio", default-features = false }
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! `tsctl`: headless TeamSpeak 3/6 client for development and integration tests.
|
||||
|
||||
mod identity;
|
||||
mod observe;
|
||||
mod query;
|
||||
mod session;
|
||||
mod tree;
|
||||
mod versions;
|
||||
@@ -34,6 +36,12 @@ enum Command {
|
||||
},
|
||||
/// Connect to a server and run an action.
|
||||
Connect(ConnectArgs),
|
||||
/// Run ServerQuery commands (raw TCP, SSH or HTTP WebQuery).
|
||||
Query(query::QueryArgs),
|
||||
/// Watch who is in which channel through ServerQuery, without appearing on the server.
|
||||
Observe(observe::ObserveArgs),
|
||||
/// Read and write a channel's chat through an invisible query relay.
|
||||
Relay(observe::RelayArgs),
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
@@ -190,6 +198,9 @@ fn main() -> Result<()> {
|
||||
let rt = tokio::runtime::Runtime::new()?;
|
||||
rt.block_on(session::run(args))
|
||||
}
|
||||
Command::Query(args) => tokio::runtime::Runtime::new()?.block_on(query::run(args)),
|
||||
Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)),
|
||||
Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
//! `tsctl observe` and `tsctl relay`: invisible presence and channel chat.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use clap::Args;
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use tsc_model::{ChatMessage, ChatTarget, Presence, PresenceDelta};
|
||||
use tsc_observer::{Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool};
|
||||
|
||||
use crate::query::QueryConnArgs;
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct ObserveArgs {
|
||||
#[command(flatten)]
|
||||
pub conn: QueryConnArgs,
|
||||
/// Stop after this many seconds (default: until Ctrl-C).
|
||||
#[arg(long)]
|
||||
pub seconds: Option<u64>,
|
||||
/// Print events as JSON lines.
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
/// Resync interval in seconds.
|
||||
#[arg(long, default_value_t = 10)]
|
||||
pub poll: u64,
|
||||
/// Exit successfully once a client with this nickname is seen (for tests).
|
||||
#[arg(long)]
|
||||
pub expect_client: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct RelayArgs {
|
||||
#[command(flatten)]
|
||||
pub conn: QueryConnArgs,
|
||||
/// Channel id to relay.
|
||||
#[arg(long)]
|
||||
pub channel: u64,
|
||||
/// Post this message after opening the relay.
|
||||
#[arg(long)]
|
||||
pub send: Option<String>,
|
||||
/// Name shown in relayed posts.
|
||||
#[arg(long, default_value = "tsctl")]
|
||||
pub nick: String,
|
||||
/// Stop after this many seconds (default: until Ctrl-C).
|
||||
#[arg(long)]
|
||||
pub seconds: Option<u64>,
|
||||
/// Exit successfully once a message containing this text arrives.
|
||||
#[arg(long)]
|
||||
pub expect: Option<String>,
|
||||
}
|
||||
|
||||
fn print_chat(msg: &ChatMessage) {
|
||||
let target = match &msg.target {
|
||||
ChatTarget::Server => "server".to_string(),
|
||||
ChatTarget::Channel(cid) => format!("channel {cid}"),
|
||||
ChatTarget::Private(_) => "private".to_string(),
|
||||
};
|
||||
println!("[{target}] {}: {}", msg.author_name, msg.text);
|
||||
}
|
||||
|
||||
fn print_tree(p: &Presence) {
|
||||
let channels: Vec<_> = p
|
||||
.channels
|
||||
.values()
|
||||
.map(|c| crate::tree::ChannelNode {
|
||||
id: tsclientlib::ChannelId(c.id),
|
||||
parent: tsclientlib::ChannelId(c.parent),
|
||||
order: tsclientlib::ChannelId(c.order),
|
||||
name: c.name.clone(),
|
||||
})
|
||||
.collect();
|
||||
let clients: Vec<_> = p
|
||||
.clients
|
||||
.values()
|
||||
.map(|c| crate::tree::ClientNode {
|
||||
channel: tsclientlib::ChannelId(c.channel),
|
||||
name: c.nickname.clone(),
|
||||
talk_power: 0,
|
||||
is_query: c.is_query,
|
||||
input_muted: c.input_muted,
|
||||
output_muted: c.output_muted,
|
||||
away: c.away.is_some(),
|
||||
streaming: c.streaming == Some(true),
|
||||
})
|
||||
.collect();
|
||||
print!(
|
||||
"{}",
|
||||
crate::tree::render(
|
||||
&format!("{} (via query, invisible)", p.server_name),
|
||||
&channels,
|
||||
&clients
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
fn describe(p: &Presence, d: &PresenceDelta) -> String {
|
||||
let name = |id: &u16| {
|
||||
p.clients.get(id).map(|c| c.nickname.clone()).unwrap_or_else(|| format!("clid {id}"))
|
||||
};
|
||||
let channel = |id: &u64| {
|
||||
p.channels.get(id).map(|c| c.name.clone()).unwrap_or_else(|| format!("cid {id}"))
|
||||
};
|
||||
match d {
|
||||
PresenceDelta::ClientJoined(c) => format!("+ {} in #{}", c.nickname, channel(&c.channel)),
|
||||
PresenceDelta::ClientLeft { id } => format!("- {} left", name(id)),
|
||||
PresenceDelta::ClientMoved { id, channel: to } => {
|
||||
format!("> {} moved to #{}", name(id), channel(to))
|
||||
}
|
||||
PresenceDelta::ClientChanged(c) => format!(
|
||||
"~ {} changed (muted: {}, away: {})",
|
||||
c.nickname,
|
||||
c.input_muted,
|
||||
c.away.is_some()
|
||||
),
|
||||
PresenceDelta::ChannelAdded(c) => format!("+ channel #{}", c.name),
|
||||
PresenceDelta::ChannelChanged(c) => format!("~ channel #{}", c.name),
|
||||
PresenceDelta::ChannelRemoved { id } => format!("- channel {}", channel(id)),
|
||||
PresenceDelta::ServerRenamed { name } => format!("~ server renamed to {name}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn observe(args: ObserveArgs) -> Result<()> {
|
||||
let mut config = ObserverConfig::new(args.conn.connect_config());
|
||||
config.poll_interval = Duration::from_secs(args.poll);
|
||||
let observer = Observer::spawn(config);
|
||||
let mut events = observer.subscribe();
|
||||
let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s));
|
||||
loop {
|
||||
let next = async {
|
||||
match deadline {
|
||||
Some(d) => timeout_at(d, events.recv()).await.ok(),
|
||||
None => Some(events.recv().await),
|
||||
}
|
||||
};
|
||||
let event = tokio::select! {
|
||||
e = next => e,
|
||||
_ = tokio::signal::ctrl_c() => return Ok(()),
|
||||
};
|
||||
let event = match event {
|
||||
None => break,
|
||||
Some(Ok(e)) => e,
|
||||
Some(Err(RecvError::Lagged(n))) => {
|
||||
eprintln!("(missed {n} events)");
|
||||
continue;
|
||||
}
|
||||
Some(Err(RecvError::Closed)) => bail!("observer stopped"),
|
||||
};
|
||||
let presence = observer.presence();
|
||||
let presence = presence.read().unwrap().clone();
|
||||
if args.json {
|
||||
match &event {
|
||||
ObserverEvent::Snapshot(s) => println!("{}", serde_json::to_string(s)?),
|
||||
ObserverEvent::Delta(d) => println!("{}", serde_json::to_string(d)?),
|
||||
ObserverEvent::Chat(m) => println!("{}", serde_json::to_string(m)?),
|
||||
ObserverEvent::Disconnected(r) => {
|
||||
println!("{}", serde_json::json!({"disconnected": r}))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match &event {
|
||||
ObserverEvent::Snapshot(_) => print_tree(&presence),
|
||||
ObserverEvent::Delta(d) => println!("{}", describe(&presence, d)),
|
||||
ObserverEvent::Chat(m) => print_chat(m),
|
||||
ObserverEvent::Disconnected(r) => println!("! disconnected: {r}"),
|
||||
}
|
||||
}
|
||||
if let Some(nick) = &args.expect_client
|
||||
&& presence.clients.values().any(|c| &c.nickname == nick)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Some(nick) = &args.expect_client {
|
||||
bail!("client {nick:?} not seen");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn relay(args: RelayArgs) -> Result<()> {
|
||||
let pool = RelayPool::new(RelayConfig::new(args.conn.connect_config()));
|
||||
let mut events = pool.subscribe();
|
||||
pool.open(args.channel).await?;
|
||||
println!("relaying channel {}", args.channel);
|
||||
if let Some(text) = &args.send {
|
||||
pool.send(args.channel, &args.nick, text).await?;
|
||||
println!("sent");
|
||||
}
|
||||
let result = relay_loop(&args, &mut events).await;
|
||||
pool.close_all().await;
|
||||
result
|
||||
}
|
||||
|
||||
async fn relay_loop(
|
||||
args: &RelayArgs,
|
||||
events: &mut tokio::sync::broadcast::Receiver<RelayEvent>,
|
||||
) -> Result<()> {
|
||||
let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s));
|
||||
loop {
|
||||
let next = async {
|
||||
match deadline {
|
||||
Some(d) => timeout_at(d, events.recv()).await.ok(),
|
||||
None => Some(events.recv().await),
|
||||
}
|
||||
};
|
||||
let event = tokio::select! {
|
||||
e = next => e,
|
||||
_ = tokio::signal::ctrl_c() => return Ok(()),
|
||||
};
|
||||
match event {
|
||||
None => break,
|
||||
Some(Ok(RelayEvent::Message(m))) => {
|
||||
print_chat(&m);
|
||||
if args.expect.as_ref().is_some_and(|e| m.text.contains(e.as_str())) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Some(Ok(RelayEvent::Closed { reason, .. })) => bail!("relay closed: {reason}"),
|
||||
Some(Err(RecvError::Lagged(_))) => {}
|
||||
Some(Err(RecvError::Closed)) => break,
|
||||
}
|
||||
}
|
||||
if let Some(expect) = &args.expect {
|
||||
bail!("no message containing {expect:?}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! `tsctl query`: ServerQuery commands and events.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::Args;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tsc_query::{Command, Connect, LineOptions, QueryClient, Row, Transport};
|
||||
|
||||
/// How to reach and log into a ServerQuery interface.
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct QueryConnArgs {
|
||||
/// Transport: raw (TS3 only), ssh or http.
|
||||
#[arg(value_enum)]
|
||||
pub transport: TransportArg,
|
||||
/// host:port of the query interface (e.g. 127.0.0.1:10022).
|
||||
pub addr: String,
|
||||
/// Login name (raw/SSH).
|
||||
#[arg(long, default_value = "serveradmin")]
|
||||
pub user: String,
|
||||
/// Password (raw/SSH) or API key (HTTP). Without it, HTTP runs as guest.
|
||||
#[arg(long, env = "TSCTL_QUERY_SECRET", hide_env_values = true)]
|
||||
pub secret: Option<String>,
|
||||
/// Select the virtual server by its voice port instead of id 1.
|
||||
#[arg(long)]
|
||||
pub server_port: Option<u16>,
|
||||
/// Our IP is on the server's query allowlist: skip client-side rate limiting.
|
||||
#[arg(long)]
|
||||
pub allowlisted: bool,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
pub struct QueryArgs {
|
||||
#[command(flatten)]
|
||||
pub conn: QueryConnArgs,
|
||||
/// After the commands, print events for this many seconds.
|
||||
#[arg(long)]
|
||||
pub events: Option<u64>,
|
||||
/// Command line to run, e.g. `clientlist -uid`. Without one, commands are read from stdin.
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
pub command: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
|
||||
pub enum TransportArg {
|
||||
Raw,
|
||||
Ssh,
|
||||
Http,
|
||||
}
|
||||
|
||||
impl QueryConnArgs {
|
||||
pub fn connect_config(&self) -> Connect {
|
||||
Connect {
|
||||
transport: match self.transport {
|
||||
TransportArg::Raw => Transport::Raw,
|
||||
TransportArg::Ssh => Transport::Ssh,
|
||||
TransportArg::Http => Transport::Http,
|
||||
},
|
||||
addr: self.addr.clone(),
|
||||
user: self.user.clone(),
|
||||
secret: self.secret.clone(),
|
||||
server_port: self.server_port,
|
||||
server_id: None,
|
||||
line: LineOptions {
|
||||
rate_limit: if self.allowlisted { None } else { LineOptions::default().rate_limit },
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn print_rows(rows: &[Row]) {
|
||||
for row in rows {
|
||||
let fields: Vec<String> = row.0.iter().map(|(k, v)| format!("{k}={v}")).collect();
|
||||
println!("{}", fields.join(" "));
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(args: QueryArgs) -> Result<()> {
|
||||
let (client, events) = QueryClient::connect(&args.conn.connect_config())
|
||||
.await
|
||||
.context("query connection failed")?;
|
||||
|
||||
if args.command.is_empty() {
|
||||
let mut lines = BufReader::new(tokio::io::stdin()).lines();
|
||||
while let Some(line) = lines.next_line().await? {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
run_line(&client, &line).await;
|
||||
}
|
||||
} else {
|
||||
let line = args.command.join(" ");
|
||||
let Some(cmd) = Command::parse(&line) else { bail!("empty command") };
|
||||
print_rows(&client.send(&cmd).await?);
|
||||
}
|
||||
|
||||
if let Some(secs) = args.events {
|
||||
let Some(mut events) = events else { bail!("this transport has no events") };
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(secs);
|
||||
while let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.recv()).await {
|
||||
print!("{}: ", event.name);
|
||||
print_rows(&event.rows);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_line(client: &QueryClient, line: &str) {
|
||||
let Some(cmd) = Command::parse(line) else { return };
|
||||
match client.send(&cmd).await {
|
||||
Ok(rows) => {
|
||||
print_rows(&rows);
|
||||
println!("ok");
|
||||
}
|
||||
Err(error) => println!("error: {error}"),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user