The one public field of QueryLogin without a doc comment. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
231 lines
7.4 KiB
Rust
231 lines
7.4 KiB
Rust
//! The query source: own ServerQuery credentials, in-process observer and relays.
|
|
|
|
use std::fmt;
|
|
|
|
use tokio::sync::{broadcast, mpsc};
|
|
use voelin_model::{ChatMessage, ChatTarget, Presence};
|
|
use voelin_observer::{
|
|
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
|
|
};
|
|
|
|
/// How a ServerQuery connection talks to the server.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum QueryTransport {
|
|
/// The raw text protocol (TeamSpeak 3; port 10011).
|
|
Raw,
|
|
/// SSH.
|
|
Ssh,
|
|
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
|
|
Http,
|
|
}
|
|
|
|
/// The user's own ServerQuery credentials for a server
|
|
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
|
|
/// engine logs in with to observe a server invisibly and to relay its
|
|
/// channels' chat. The connection's own tuning (flood protection, timeouts)
|
|
/// is the engine's.
|
|
#[derive(Clone, PartialEq, Eq)]
|
|
pub struct QueryLogin {
|
|
/// The protocol of the query interface at `address`.
|
|
pub transport: QueryTransport,
|
|
/// `host:port` of the query interface.
|
|
pub address: String,
|
|
/// The login name (raw and SSH; ignored for HTTP).
|
|
pub user: String,
|
|
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
|
|
pub secret: Option<String>,
|
|
/// Select the virtual server by its voice port...
|
|
pub server_port: Option<u16>,
|
|
/// ...or by id (the first server when neither is given).
|
|
pub server_id: Option<u32>,
|
|
/// This machine's address is on the server's query allowlist, which the
|
|
/// server's flood protection skips: the engine then sends its commands
|
|
/// without the limit it keeps for a server that has not said so (a command
|
|
/// the server refuses as a flood slows the connection down all the same).
|
|
/// The application usually cannot know, and says `false`; the development
|
|
/// servers of the tests allowlist their clients.
|
|
pub allowlisted: bool,
|
|
}
|
|
|
|
impl fmt::Debug for QueryLogin {
|
|
// The secret is kept out of logs.
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("QueryLogin")
|
|
.field("transport", &self.transport)
|
|
.field("address", &self.address)
|
|
.field("user", &self.user)
|
|
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
|
|
.field("server_port", &self.server_port)
|
|
.field("server_id", &self.server_id)
|
|
.field("allowlisted", &self.allowlisted)
|
|
.finish()
|
|
}
|
|
}
|
|
|
|
impl QueryLogin {
|
|
/// The connection the observer and the relays open.
|
|
fn connect(&self) -> voelin_query::Connect {
|
|
voelin_query::Connect {
|
|
transport: match self.transport {
|
|
QueryTransport::Raw => voelin_query::Transport::Raw,
|
|
QueryTransport::Ssh => voelin_query::Transport::Ssh,
|
|
QueryTransport::Http => voelin_query::Transport::Http,
|
|
},
|
|
addr: self.address.clone(),
|
|
user: self.user.clone(),
|
|
secret: self.secret.clone(),
|
|
server_port: self.server_port,
|
|
server_id: self.server_id,
|
|
line: voelin_query::LineOptions {
|
|
// Off the client-side limit only where the server skips it.
|
|
rate_limit: if self.allowlisted {
|
|
None
|
|
} else {
|
|
voelin_query::LineOptions::default().rate_limit
|
|
},
|
|
..Default::default()
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) enum QueryCmd {
|
|
OpenChat(ChatTarget),
|
|
CloseChat(ChatTarget),
|
|
SendChat { target: ChatTarget, nick: String, text: String },
|
|
Stop,
|
|
}
|
|
|
|
pub(crate) enum QueryEvent {
|
|
Presence(Box<Presence>),
|
|
Chat(ChatMessage),
|
|
Error(String),
|
|
Disconnected,
|
|
}
|
|
|
|
pub(crate) async fn run(
|
|
login: QueryLogin,
|
|
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
|
|
events: mpsc::UnboundedSender<QueryEvent>,
|
|
) {
|
|
let connect = login.connect();
|
|
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
|
|
let relays = RelayPool::new(RelayConfig::new(connect));
|
|
let mut observed = observer.subscribe();
|
|
let mut relayed = relays.subscribe();
|
|
let mut open = std::collections::HashSet::new();
|
|
loop {
|
|
tokio::select! {
|
|
e = observed.recv() => match e {
|
|
Ok(ObserverEvent::Snapshot(_)) | Ok(ObserverEvent::Delta(_)) | Err(broadcast::error::RecvError::Lagged(_)) => {
|
|
let presence = observer.presence().read().unwrap().clone();
|
|
let _ = events.send(QueryEvent::Presence(Box::new(presence)));
|
|
}
|
|
Ok(ObserverEvent::Chat(msg)) => {
|
|
if open.contains(&msg.target) {
|
|
let _ = events.send(QueryEvent::Chat(msg));
|
|
}
|
|
}
|
|
Ok(ObserverEvent::Disconnected(reason)) => {
|
|
let _ = events.send(QueryEvent::Error(format!("query connection lost: {reason}")));
|
|
}
|
|
Err(broadcast::error::RecvError::Closed) => break,
|
|
},
|
|
e = relayed.recv() => match e {
|
|
Ok(RelayEvent::Message(msg)) => {
|
|
let _ = events.send(QueryEvent::Chat(msg));
|
|
}
|
|
Ok(RelayEvent::Closed { channel, reason }) => {
|
|
let _ = events.send(QueryEvent::Error(format!("relay for channel {channel} closed: {reason}")));
|
|
}
|
|
Err(_) => {}
|
|
},
|
|
cmd = commands.recv() => match cmd {
|
|
None | Some(QueryCmd::Stop) => break,
|
|
Some(QueryCmd::OpenChat(target)) => {
|
|
if let ChatTarget::Channel(cid) = target
|
|
&& let Err(e) = relays.open(cid).await
|
|
{
|
|
let _ = events.send(QueryEvent::Error(e.to_string()));
|
|
continue;
|
|
}
|
|
open.insert(target);
|
|
}
|
|
Some(QueryCmd::CloseChat(target)) => {
|
|
if let ChatTarget::Channel(cid) = target {
|
|
relays.close(cid).await;
|
|
}
|
|
open.remove(&target);
|
|
}
|
|
Some(QueryCmd::SendChat { target, nick, text }) => {
|
|
let result = match &target {
|
|
ChatTarget::Channel(cid) => relays.send(*cid, &nick, &text).await,
|
|
_ => Err(voelin_query::Error::Unsupported("only channel chat is relayed with own credentials")),
|
|
};
|
|
if let Err(e) = result {
|
|
let _ = events.send(QueryEvent::Error(e.to_string()));
|
|
}
|
|
}
|
|
},
|
|
}
|
|
}
|
|
relays.close_all().await;
|
|
let _ = events.send(QueryEvent::Disconnected);
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn a_login_is_the_connection_the_query_crate_opens() {
|
|
let login = QueryLogin {
|
|
transport: QueryTransport::Ssh,
|
|
address: "ts.example.com:10022".into(),
|
|
user: "serveradmin".into(),
|
|
secret: Some("hunter2".into()),
|
|
server_port: Some(9987),
|
|
server_id: Some(3),
|
|
allowlisted: false,
|
|
};
|
|
let connect = login.connect();
|
|
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
|
|
assert_eq!(
|
|
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
|
|
("ts.example.com:10022", "serveradmin", Some("hunter2"))
|
|
);
|
|
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
|
|
for (ours, theirs) in [
|
|
(QueryTransport::Raw, voelin_query::Transport::Raw),
|
|
(QueryTransport::Http, voelin_query::Transport::Http),
|
|
] {
|
|
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
|
|
assert_eq!(connect.transport, theirs);
|
|
}
|
|
// The line options are the query crate's defaults, as the UI always
|
|
// gave them, unless the server allowlists the client.
|
|
let line = voelin_query::LineOptions::default();
|
|
assert!(line.rate_limit.is_some());
|
|
assert_eq!(connect.line.rate_limit, line.rate_limit);
|
|
assert_eq!(connect.line.timeout, line.timeout);
|
|
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
|
|
assert_eq!(allowlisted.line.rate_limit, None);
|
|
assert_eq!(allowlisted.line.timeout, line.timeout);
|
|
}
|
|
|
|
#[test]
|
|
fn the_secret_stays_out_of_the_debug_text() {
|
|
let login = QueryLogin {
|
|
transport: QueryTransport::Raw,
|
|
address: "h:1".into(),
|
|
user: "u".into(),
|
|
secret: Some("hunter2".into()),
|
|
server_port: None,
|
|
server_id: None,
|
|
allowlisted: false,
|
|
};
|
|
let text = format!("{login:?}");
|
|
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
|
|
}
|
|
}
|