myTS avatar, badges and User Tag from a saved session; banners; gateway logs and speed
Own account on TeamSpeak 6 servers:
- With only a saved session, the account's avatar and its certificate come
from myTeamSpeak's avatar service (requestContactsAvatar for the own myTS
ID), the signed badges from getSignedBadges and the User Tag's token from
/tschat requestSignedAllowedIdentifierList; no password sign-in needed.
- tsproto::myts::Certificate checks a certificate chain as the server does
(block types 4-7, leaf type 6, validity, key from the root, cofactorless
Ed25519); each part is sent with a certificate that verifies it, in
separate updatemytsdata commands when they differ, and cleared on sign-out.
- client_user_tag is set as the official client sets it
({"myts_token","tag","updated"}) on TeamSpeak 6 servers, after a
self-check of the token; cleared on sign-out or an account change.
- Settings -> My Account shows the User Tag and lets the user choose up to
three badges to show. The log says what the server published.
Banners:
- The URL (without query) is logged on the first failure; stalls, connect
failures and missing answers are named; 400/404/410 are retried after
15 minutes, then hourly; 429/503 honour Retry-After.
- Cached pictures are revalidated (ETag, Last-Modified); at most 6
downloads per host; a User-Agent with the app version.
- The desktop portal's proxy (Linux) and the system proxy (Windows, macOS)
are used, SOCKS included; redirects are followed hop by hop.
Gateway, client side:
- Only a refused login stops observing; retries after 1, 2, 5, 10, 20, then
30 s with jitter, at once when voice connects; a 30 s keepalive.
- Discovery asks DNS and the well-known endpoints at once; observing is not
restarted when the found list still holds the gateway in use.
- Info logs for discovery, attempts (with the stage that hung), connections,
losses and the first presence.
tsgw:
- Logging setup (log.level, log.file with size rotation, colour only on a
terminal) and lifecycle logs: startup summary, the address the server
sees for queries, WebSocket connections, logins, refusals, slow requests,
ServerQuery failures, relays and the observer.
- The lookup query connection reconnects after a TeamSpeak restart; query
connects time out after 10 s; a silent server cannot wedge a connection;
SIGTERM, startup while TeamSpeak is down and /health are handled.
- TCP_QUICKACK and one write per line: ~45 ms -> <2 ms per SSH command.
- One flood guard shared by all query connections (9 per 3 s, SSH auth
counted, every connection holds on a 524).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
1 parent
1c2d5efd3a
commit
79a12654c8
56 files changed
+7405
-672
No files matched your search
@@ -17,6 +17,10 @@ thiserror = "2.0.21"
|
||||
tokio = { version = "1.53.1", features = ["net", "io-util", "sync", "time", "rt", "macros"] }
|
||||
tracing = "0.1.44"
|
||||
|
||||
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
|
||||
# TCP_QUICKACK on query connections (src/tcp.rs).
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
//! Transport-independent query client.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::split;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{Instant, timeout_at};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::codec::{Command, Notification, Row};
|
||||
use crate::http::HttpClient;
|
||||
use crate::line::{LineClient, LineOptions};
|
||||
use crate::tcp::QuickAck;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// How long to send nothing after the server dropped an SSH login: its flood
|
||||
/// protection counts per 3 seconds.
|
||||
const SSH_DROP_WAIT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// Seconds between attempts to open a query connection, the last repeating.
|
||||
const RETRY_SECS: [u64; 6] = [1, 2, 3, 5, 10, 30];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Transport {
|
||||
@@ -34,6 +45,39 @@ pub struct Connect {
|
||||
pub line: LineOptions,
|
||||
}
|
||||
|
||||
impl Connect {
|
||||
/// How long to wait after failed attempt `attempt` (counted from 1) to
|
||||
/// open a connection: the next step of [`RETRY_SECS`], or longer if the
|
||||
/// server's flood protection asked for it.
|
||||
pub fn retry_delay(&self, attempt: u32) -> Duration {
|
||||
let step = RETRY_SECS[(attempt.max(1) as usize - 1).min(RETRY_SECS.len() - 1)];
|
||||
Duration::from_secs(step).max(self.line.flood.held_for().unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether failed attempt `attempt` to open a connection is worth a
|
||||
/// warning: the first few are, then every tenth (about every 5 minutes at
|
||||
/// the longest wait). Log the others at debug level.
|
||||
pub fn attempt_worth_a_warning(attempt: u32) -> bool {
|
||||
attempt <= 3 || attempt.is_multiple_of(10)
|
||||
}
|
||||
|
||||
/// Fails at once when the server's flood protection asked to wait past
|
||||
/// `deadline`: the connection could not log in in time anyway.
|
||||
fn flood_wait_fits(options: &LineOptions, addr: &str, deadline: Instant) -> Result<()> {
|
||||
match options.flood.held_for() {
|
||||
Some(held) if Instant::now() + held > deadline => Err(io_timeout(format!(
|
||||
"the server's flood protection asks to wait {} s; not connecting to {addr} now",
|
||||
held.as_secs()
|
||||
))),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn io_timeout(message: String) -> Error {
|
||||
Error::Io(std::io::Error::new(std::io::ErrorKind::TimedOut, message))
|
||||
}
|
||||
|
||||
/// A logged-in query connection with a selected virtual server.
|
||||
#[derive(Clone)]
|
||||
pub enum QueryClient {
|
||||
@@ -47,26 +91,61 @@ impl QueryClient {
|
||||
pub async fn connect(
|
||||
cfg: &Connect,
|
||||
) -> Result<(Self, Option<mpsc::UnboundedReceiver<Notification>>)> {
|
||||
let options = &cfg.line;
|
||||
// Connecting, logging in and selecting the server, all of it.
|
||||
let deadline = Instant::now() + options.connect_timeout;
|
||||
let timed_out = |what: &str| {
|
||||
let wait_s = options.connect_timeout.as_secs_f32();
|
||||
io_timeout(format!("{what} at {} within {wait_s} s", cfg.addr))
|
||||
};
|
||||
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());
|
||||
flood_wait_fits(options, &cfg.addr, deadline)?;
|
||||
let stream = QuickAck::connect(&cfg.addr, options.connect_timeout).await?;
|
||||
let (r, w) = split(stream);
|
||||
let (client, events) = LineClient::spawn(r, w, options.clone());
|
||||
let client = Self::Line(client);
|
||||
client.login_and_use(cfg).await?;
|
||||
timeout_at(deadline, client.login_and_use(cfg))
|
||||
.await
|
||||
.map_err(|_| timed_out("no query login"))??;
|
||||
Ok((client, Some(events)))
|
||||
}
|
||||
Transport::Ssh => {
|
||||
// The server counts the SSH login as a command.
|
||||
flood_wait_fits(options, &cfg.addr, deadline)?;
|
||||
timeout_at(deadline, options.flood.acquire(options.rate_limit))
|
||||
.await
|
||||
.map_err(|_| timed_out("the flood protection allowed no login"))?;
|
||||
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 wait = deadline.saturating_duration_since(Instant::now());
|
||||
let login = crate::ssh::connect(&cfg.addr, &cfg.user, password, wait);
|
||||
let shell = match timeout_at(deadline, login).await {
|
||||
Ok(shell) => shell,
|
||||
Err(_) => Err(timed_out("no SSH login")),
|
||||
};
|
||||
// A server at its flood limit drops new connections during the
|
||||
// login, without saying why.
|
||||
if options.flood.limit(options.rate_limit).is_some()
|
||||
&& matches!(shell, Err(Error::Ssh(russh::Error::Disconnect)))
|
||||
{
|
||||
debug!(addr = %cfg.addr, "SSH login dropped, maybe by the flood protection; waiting");
|
||||
options.flood.hold(SSH_DROP_WAIT);
|
||||
}
|
||||
let shell = shell?;
|
||||
debug!(
|
||||
fingerprint = ?shell.fingerprint,
|
||||
addr = %cfg.addr,
|
||||
conn = %options.label,
|
||||
"ssh query connected"
|
||||
);
|
||||
let (r, w) = split(shell.stream);
|
||||
let (client, events) =
|
||||
LineClient::spawn_with_guard(r, w, cfg.line.clone(), shell.session);
|
||||
LineClient::spawn_with_guard(r, w, options.clone(), shell.session);
|
||||
let client = Self::Line(client);
|
||||
// SSH already authenticated; only select the server.
|
||||
client.use_server(cfg).await?;
|
||||
timeout_at(deadline, client.use_server(cfg))
|
||||
.await
|
||||
.map_err(|_| timed_out("no answer to selecting the server"))??;
|
||||
Ok((client, Some(events)))
|
||||
}
|
||||
Transport::Http => {
|
||||
@@ -134,6 +213,22 @@ impl QueryClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection is gone (HTTP has none).
|
||||
pub fn is_closed(&self) -> bool {
|
||||
match self {
|
||||
QueryClient::Line(c) => c.is_closed(),
|
||||
QueryClient::Http(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves when the connection is gone (never for HTTP).
|
||||
pub async fn closed(&self) {
|
||||
match self {
|
||||
QueryClient::Line(c) => c.closed().await,
|
||||
QueryClient::Http(_) => std::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the transport delivers `notify*` events.
|
||||
pub fn has_events(&self) -> bool {
|
||||
matches!(self, QueryClient::Line(_))
|
||||
@@ -147,3 +242,73 @@ impl QueryClient {
|
||||
.ok_or_else(|| Error::Protocol("whoami without client_id".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A server that accepts connections and never says anything.
|
||||
async fn silent_server() -> String {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap().to_string();
|
||||
tokio::spawn(async move {
|
||||
let mut open = Vec::new();
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
open.push(stream);
|
||||
}
|
||||
});
|
||||
addr
|
||||
}
|
||||
|
||||
fn connect(transport: Transport, addr: &str) -> Connect {
|
||||
Connect {
|
||||
transport,
|
||||
addr: addr.into(),
|
||||
user: "serveradmin".into(),
|
||||
secret: Some("pw".into()),
|
||||
server_port: None,
|
||||
server_id: None,
|
||||
line: LineOptions { connect_timeout: Duration::from_millis(300), ..Default::default() },
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_times_out(cfg: &Connect) {
|
||||
let started = std::time::Instant::now();
|
||||
match QueryClient::connect(cfg).await {
|
||||
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::TimedOut),
|
||||
Err(e) => panic!("{e}"),
|
||||
Ok(_) => panic!("connected to a silent server"),
|
||||
}
|
||||
assert!(started.elapsed() < Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_silent_server_does_not_hold_up_the_login() {
|
||||
let addr = silent_server().await;
|
||||
// In the SSH handshake.
|
||||
assert_times_out(&connect(Transport::Ssh, &addr)).await;
|
||||
// At `login` and `use`, which have a longer timeout of their own.
|
||||
assert_times_out(&connect(Transport::Raw, &addr)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_long_flood_wait_fails_the_connect_at_once() {
|
||||
let addr = silent_server().await;
|
||||
let cfg = connect(Transport::Ssh, &addr);
|
||||
cfg.line.flood.hold(Duration::from_secs(600));
|
||||
let started = std::time::Instant::now();
|
||||
assert!(matches!(QueryClient::connect(&cfg).await, Err(Error::Io(_))));
|
||||
assert!(started.elapsed() < Duration::from_millis(100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waits_grow_and_follow_the_server() {
|
||||
let cfg = connect(Transport::Raw, "h:1");
|
||||
let secs = |attempt| cfg.retry_delay(attempt).as_secs();
|
||||
assert_eq!([secs(1), secs(3), secs(5), secs(6), secs(60)], [1, 3, 10, 30, 30]);
|
||||
cfg.line.flood.hold(Duration::from_secs(600));
|
||||
assert!(cfg.retry_delay(1) > Duration::from_secs(590));
|
||||
let warned: Vec<u32> = (1..=30).filter(|a| attempt_worth_a_warning(*a)).collect();
|
||||
assert_eq!(warned, [1, 2, 3, 10, 20, 30]);
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,12 @@ impl QueryError {
|
||||
self.id == 1281
|
||||
}
|
||||
|
||||
/// The server's flood protection refused the command; `extra_msg` says
|
||||
/// how long to wait (`please wait 1 seconds`).
|
||||
pub fn is_flood(&self) -> bool {
|
||||
self.id == 524
|
||||
}
|
||||
|
||||
pub(crate) fn from_row(row: &Row) -> Self {
|
||||
QueryError {
|
||||
id: row.parse("id").unwrap_or(u32::MAX),
|
||||
|
||||
@@ -17,13 +17,14 @@ mod codec;
|
||||
mod http;
|
||||
mod line;
|
||||
mod ssh;
|
||||
mod tcp;
|
||||
|
||||
pub use client::{Connect, QueryClient, Transport};
|
||||
pub use client::{Connect, QueryClient, Transport, attempt_worth_a_warning};
|
||||
pub use codec::{
|
||||
Command, Line, Notification, QueryError, Row, escape, parse_line, parse_rows, unescape,
|
||||
};
|
||||
pub use http::HttpClient;
|
||||
pub use line::{LineClient, LineOptions};
|
||||
pub use line::{FloodGuard, LineClient, LineOptions};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
|
||||
+501
-79
@@ -5,39 +5,163 @@
|
||||
//! event channel whenever they arrive.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
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 tracing::{Instrument, debug, info_span, trace, warn};
|
||||
|
||||
use crate::codec::{Command, Line, Notification, Row, parse_line};
|
||||
use crate::codec::{Command, Line, Notification, QueryError, Row, parse_line};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Waited on top of what the server asks for: its clock is not ours.
|
||||
const FLOOD_MARGIN: Duration = Duration::from_millis(100);
|
||||
|
||||
/// TeamSpeak refuses the 10th command within 3 seconds from one address,
|
||||
/// the SSH login included.
|
||||
const SERVER_LIMIT: (u32, Duration) = (9, Duration::from_secs(3));
|
||||
|
||||
#[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.
|
||||
/// Flood protection: at most this many commands per window, counted in
|
||||
/// `flood`. `None` when the client IP is on the server's query
|
||||
/// allowlist (until the server refuses a command for flooding: then
|
||||
/// the default applies).
|
||||
pub rate_limit: Option<(u32, Duration)>,
|
||||
/// Give up on a command after this long.
|
||||
/// Give up on a command after this long, time in the queue included.
|
||||
/// A connection whose server leaves a command unanswered for twice as
|
||||
/// long is closed.
|
||||
pub timeout: Duration,
|
||||
/// Give up opening a connection after this long: connecting, logging in
|
||||
/// and selecting the server, waits for the flood protection included.
|
||||
pub connect_timeout: Duration,
|
||||
/// What the connection is for (`lookup`, `observer`, `relay 5`), in
|
||||
/// its log lines.
|
||||
pub label: String,
|
||||
/// Commands sent and waits the server asked for. The server counts
|
||||
/// commands per source address, so clones of these options (and the
|
||||
/// connections opened with them) share one count.
|
||||
pub flood: FloodGuard,
|
||||
}
|
||||
|
||||
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))),
|
||||
rate_limit: Some(SERVER_LIMIT),
|
||||
timeout: Duration::from_secs(15),
|
||||
connect_timeout: Duration::from_secs(10),
|
||||
label: "query".into(),
|
||||
flood: FloodGuard::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The flood protection's state, shared by every connection to one server:
|
||||
/// when recent commands went out, and until when the server asked to wait.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FloodGuard(Arc<Mutex<FloodState>>);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct FloodState {
|
||||
sent: VecDeque<Instant>,
|
||||
hold_until: Option<Instant>,
|
||||
/// The server refused a command although no limit was set: the address
|
||||
/// is not on its allowlist after all.
|
||||
limited: bool,
|
||||
}
|
||||
|
||||
impl FloodState {
|
||||
/// `limit`, or the server's own when it turned out to apply.
|
||||
fn limit(&self, limit: Option<(u32, Duration)>) -> Option<(u32, Duration)> {
|
||||
limit.or(self.limited.then_some(SERVER_LIMIT))
|
||||
}
|
||||
|
||||
/// When the next command may be sent.
|
||||
fn next_slot(&mut self, limit: Option<(u32, Duration)>, now: Instant) -> Instant {
|
||||
let held = self.hold_until.filter(|t| *t > now);
|
||||
self.hold_until = held;
|
||||
let Some((count, window)) = limit else { return held.unwrap_or(now) };
|
||||
while self.sent.front().is_some_and(|t| now.duration_since(*t) >= window) {
|
||||
self.sent.pop_front();
|
||||
}
|
||||
let slot = match self.sent.len().checked_sub(count as usize) {
|
||||
None => now,
|
||||
// Leave a little margin: the server's clock is not ours.
|
||||
Some(oldest) => self.sent[oldest] + window + Duration::from_millis(50),
|
||||
};
|
||||
held.map_or(slot, |held| held.max(slot))
|
||||
}
|
||||
}
|
||||
|
||||
impl FloodGuard {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, FloodState> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Wait until a command may be sent under `limit`, and count it. Safe to
|
||||
/// cancel: the command is only counted when this returns.
|
||||
pub async fn acquire(&self, limit: Option<(u32, Duration)>) {
|
||||
loop {
|
||||
let slot = {
|
||||
let mut state = self.lock();
|
||||
let now = Instant::now();
|
||||
let limit = state.limit(limit);
|
||||
let slot = state.next_slot(limit, now);
|
||||
if slot <= now {
|
||||
if limit.is_some() {
|
||||
state.sent.push_back(now);
|
||||
}
|
||||
return;
|
||||
}
|
||||
slot
|
||||
};
|
||||
sleep_until(slot).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The limit that applies: `limit`, or the server's own once it refused
|
||||
/// a command although `limit` was `None`.
|
||||
pub fn limit(&self, limit: Option<(u32, Duration)>) -> Option<(u32, Duration)> {
|
||||
self.lock().limit(limit)
|
||||
}
|
||||
|
||||
/// Send nothing for `wait`, on any connection sharing this guard.
|
||||
pub fn hold(&self, wait: Duration) {
|
||||
let until = Instant::now() + wait;
|
||||
let mut state = self.lock();
|
||||
state.hold_until = Some(state.hold_until.map_or(until, |held| held.max(until)));
|
||||
}
|
||||
|
||||
/// Keep to the server's limit from now on, also where none was set.
|
||||
/// Whether that is new.
|
||||
fn limit_from_now_on(&self) -> bool {
|
||||
!std::mem::replace(&mut self.lock().limited, true)
|
||||
}
|
||||
|
||||
/// How long sending is still held, if it is.
|
||||
pub fn held_for(&self) -> Option<Duration> {
|
||||
let until = self.lock().hold_until?;
|
||||
until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero())
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the server's flood protection asks to wait
|
||||
/// (`extra_msg=please\swait\s1\sseconds`).
|
||||
fn flood_wait(error: &QueryError) -> Duration {
|
||||
let seconds = error
|
||||
.extra_msg
|
||||
.as_deref()
|
||||
.and_then(|m| m.split(' ').find_map(|word| word.parse::<u64>().ok()))
|
||||
.unwrap_or(3);
|
||||
Duration::from_secs(seconds)
|
||||
}
|
||||
|
||||
type Reply = oneshot::Sender<Result<Vec<Row>>>;
|
||||
|
||||
struct Request {
|
||||
@@ -50,6 +174,8 @@ struct Request {
|
||||
pub struct LineClient {
|
||||
requests: mpsc::Sender<Request>,
|
||||
timeout: Duration,
|
||||
/// [`LineOptions::label`].
|
||||
label: Arc<str>,
|
||||
}
|
||||
|
||||
impl LineClient {
|
||||
@@ -82,11 +208,17 @@ impl LineClient {
|
||||
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)
|
||||
let label = Arc::from(options.label.as_str());
|
||||
// Not a child of whatever opened the connection: it outlives that.
|
||||
let span = info_span!(parent: None, "query", conn = %options.label);
|
||||
tokio::spawn(
|
||||
async move {
|
||||
run(BufReader::new(reader), writer, rx, events_tx, options).await;
|
||||
drop(guard);
|
||||
}
|
||||
.instrument(span),
|
||||
);
|
||||
(Self { requests, timeout, label }, events)
|
||||
}
|
||||
|
||||
/// Send a command and collect its data rows.
|
||||
@@ -97,44 +229,78 @@ impl LineClient {
|
||||
/// Send an already formatted command line.
|
||||
pub async fn send_line(&self, line: String) -> Result<Vec<Row>> {
|
||||
let (reply, rx) = oneshot::channel();
|
||||
let name = command_name(&line).to_owned();
|
||||
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),
|
||||
Err(_) => {
|
||||
let timeout_s = self.timeout.as_secs();
|
||||
debug!(conn = %self.label, command = name, timeout_s, "no answer in time");
|
||||
Err(Error::Timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
self.requests.is_closed()
|
||||
}
|
||||
|
||||
/// Resolves when the connection is gone.
|
||||
pub async fn closed(&self) {
|
||||
self.requests.closed().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Token bucket for the query flood protection.
|
||||
struct RateLimiter {
|
||||
limit: Option<(u32, Duration)>,
|
||||
sent: VecDeque<Instant>,
|
||||
/// The command of a line (`clientlist` of `clientlist -uid`).
|
||||
fn command_name(line: &str) -> &str {
|
||||
line.split(' ').next().unwrap_or_default()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
/// A line as it may appear in the log: never a login's password.
|
||||
fn loggable(line: &str) -> &str {
|
||||
if command_name(line) == "login" { "login (credentials not logged)" } else { line }
|
||||
}
|
||||
|
||||
/// A command on its way out.
|
||||
struct Outgoing {
|
||||
line: String,
|
||||
/// `None` for the keepalive.
|
||||
reply: Option<Reply>,
|
||||
/// Already sent once and refused by the flood protection.
|
||||
retried: bool,
|
||||
}
|
||||
|
||||
impl Outgoing {
|
||||
fn name(&self) -> &str {
|
||||
command_name(&self.line)
|
||||
}
|
||||
|
||||
fn record(&mut self, t: Instant) {
|
||||
if self.limit.is_some() {
|
||||
self.sent.push_back(t);
|
||||
}
|
||||
/// The caller gave up waiting.
|
||||
fn abandoned(&self) -> bool {
|
||||
self.reply.as_ref().is_some_and(oneshot::Sender::is_closed)
|
||||
}
|
||||
}
|
||||
|
||||
/// A command sent and not answered yet.
|
||||
struct Sent {
|
||||
command: Outgoing,
|
||||
at: Instant,
|
||||
rows: Vec<Row>,
|
||||
}
|
||||
|
||||
/// Resolves when the caller of the queued command gives up.
|
||||
async fn given_up(queued: &mut Option<Outgoing>) {
|
||||
match queued.as_mut().and_then(|c| c.reply.as_mut()) {
|
||||
Some(reply) => reply.closed().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn sleep_until_some(at: Option<Instant>) {
|
||||
match at {
|
||||
Some(at) => sleep_until(at).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,21 +314,28 @@ async fn run<R, W>(
|
||||
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 flood = options.flood.clone();
|
||||
let limit = options.rate_limit;
|
||||
// Taken from the queue, waiting for the flood protection.
|
||||
let mut queued: Option<Outgoing> = None;
|
||||
// Sent, waiting for the answer.
|
||||
let mut sent: Option<Sent> = None;
|
||||
let mut last_activity = Instant::now();
|
||||
let mut buf = Vec::new();
|
||||
|
||||
loop {
|
||||
let can_send = pending.is_none() && !keepalive_pending;
|
||||
let idle = queued.is_none() && sent.is_none();
|
||||
let keepalive_at = last_activity + options.keepalive;
|
||||
let stalled_at = sent.as_ref().map(|s| s.at + options.timeout * 2);
|
||||
tokio::select! {
|
||||
read = reader.read_until(b'\n', &mut buf) => {
|
||||
match read {
|
||||
Ok(0) | Err(_) => {
|
||||
debug!("query connection closed");
|
||||
Ok(0) => {
|
||||
debug!("query connection closed by the server");
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
debug!(%error, "query connection failed");
|
||||
break;
|
||||
}
|
||||
Ok(_) => {}
|
||||
@@ -179,59 +352,113 @@ async fn run<R, W>(
|
||||
// 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);
|
||||
if let Some(sent) = &mut sent {
|
||||
sent.rows.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);
|
||||
let Some(Sent { command, at, rows }) = sent.take() else { continue };
|
||||
let elapsed_ms = (at.elapsed().as_secs_f64() * 10_000.0).round() / 10.0;
|
||||
trace!(command = command.name(), id = e.id, rows = rows.len(), elapsed_ms, "query answered");
|
||||
if e.is_flood() {
|
||||
// Every connection waits: the server counts them together,
|
||||
// and two more commands now would get the address banned.
|
||||
// What the server asks for is too short: it still counts
|
||||
// the commands of the last 3 s, the refused ones too.
|
||||
let wait = flood_wait(&e).max(SERVER_LIMIT.1);
|
||||
flood.hold(wait + FLOOD_MARGIN);
|
||||
if limit.is_none() && flood.limit_from_now_on() {
|
||||
warn!(
|
||||
"the server limits this address although it was taken to be on its query allowlist; keeping to 9 commands per 3 s from now on"
|
||||
);
|
||||
}
|
||||
// The keepalive did its job: the server answered.
|
||||
let resend = !command.retried && command.reply.is_some();
|
||||
warn!(
|
||||
command = command.name(),
|
||||
wait_ms = wait.as_millis() as u64,
|
||||
resend,
|
||||
"the server's flood protection refused a command; sending nothing until the wait is over"
|
||||
);
|
||||
if resend {
|
||||
queued = Some(Outgoing { retried: true, ..command });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let name = command.name().to_owned();
|
||||
let Some(reply) = command.reply else { continue };
|
||||
let result = if e.is_ok() || e.is_empty_result() {
|
||||
Ok(rows)
|
||||
} else {
|
||||
debug!(
|
||||
command = name,
|
||||
error = %e,
|
||||
elapsed_ms = at.elapsed().as_millis() as u64,
|
||||
"query command failed"
|
||||
);
|
||||
Err(e.into())
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
req = requests.recv(), if can_send => {
|
||||
req = requests.recv(), if idle => {
|
||||
let Some(req) = req else { break };
|
||||
let slot = limiter.next_slot(Instant::now());
|
||||
if slot > Instant::now() {
|
||||
sleep_until(slot).await;
|
||||
let command = Outgoing { line: req.line, reply: Some(req.reply), retried: false };
|
||||
if command.abandoned() {
|
||||
debug!(command = command.name(), "dropping a command its caller gave up on");
|
||||
} else {
|
||||
queued = Some(command);
|
||||
}
|
||||
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() {
|
||||
() = given_up(&mut queued) => {
|
||||
if let Some(command) = queued.take() {
|
||||
debug!(command = command.name(), "dropping a command its caller gave up on");
|
||||
}
|
||||
}
|
||||
() = flood.acquire(limit), if queued.is_some() && sent.is_none() => {
|
||||
let Some(command) = queued.take() else { continue };
|
||||
if command.abandoned() {
|
||||
debug!(command = command.name(), "dropping a command its caller gave up on");
|
||||
continue;
|
||||
}
|
||||
trace!(line = %loggable(&command.line), "query >");
|
||||
if let Err(e) = write_line(&mut writer, &command.line).await {
|
||||
if let Some(reply) = command.reply {
|
||||
let _ = reply.send(Err(e.into()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
last_activity = Instant::now();
|
||||
keepalive_pending = true;
|
||||
sent = Some(Sent { command, at: last_activity, rows: Vec::new() });
|
||||
}
|
||||
_ = sleep_until(keepalive_at), if idle => {
|
||||
queued = Some(Outgoing { line: "whoami".into(), reply: None, retried: false });
|
||||
}
|
||||
() = sleep_until_some(stalled_at) => {
|
||||
let command = sent.as_ref().map(|s| s.command.name().to_owned()).unwrap_or_default();
|
||||
warn!(
|
||||
command,
|
||||
waited_s = (options.timeout * 2).as_secs(),
|
||||
"the server did not answer; closing the query connection"
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((reply, _)) = pending {
|
||||
if let Some(Sent { command: Outgoing { reply: Some(reply), .. }, .. }) = sent {
|
||||
let _ = reply.send(Err(Error::Closed));
|
||||
}
|
||||
debug!("query connection task ended");
|
||||
}
|
||||
|
||||
/// Write one command in one write: over SSH each write is a packet.
|
||||
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?;
|
||||
let mut bytes = Vec::with_capacity(line.len() + 1);
|
||||
bytes.extend_from_slice(line.as_bytes());
|
||||
bytes.push(b'\n');
|
||||
writer.write_all(&bytes).await?;
|
||||
writer.flush().await
|
||||
}
|
||||
|
||||
@@ -300,15 +527,210 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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() };
|
||||
async fn the_flood_guard_spaces_commands() {
|
||||
let limit = Some((2, Duration::from_secs(3)));
|
||||
let mut state = FloodState::default();
|
||||
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));
|
||||
assert_eq!(state.next_slot(limit, t0), t0);
|
||||
state.sent.extend([t0, t0]);
|
||||
assert!(state.next_slot(limit, t0) >= t0 + Duration::from_secs(3));
|
||||
let later = t0 + Duration::from_secs(4);
|
||||
assert_eq!(limiter.next_slot(later), later);
|
||||
assert_eq!(state.next_slot(limit, later), later);
|
||||
// A wait the server asked for applies with and without a limit.
|
||||
state.hold_until = Some(later + Duration::from_secs(2));
|
||||
assert_eq!(state.next_slot(limit, later), later + Duration::from_secs(2));
|
||||
assert_eq!(state.next_slot(None, later), later + Duration::from_secs(2));
|
||||
}
|
||||
|
||||
/// The commands a fake server got, and when.
|
||||
type Seen = Arc<Mutex<Vec<(String, Instant)>>>;
|
||||
|
||||
/// A fake server that answers every command with `error id=0`, and
|
||||
/// with `refusals` (in order) for the first ones; records when each
|
||||
/// command arrived.
|
||||
fn answering_server(stream: tokio::io::DuplexStream, refusals: Vec<&'static str>) -> Seen {
|
||||
let seen = Arc::new(Mutex::new(Vec::new()));
|
||||
let log = seen.clone();
|
||||
tokio::spawn(async move {
|
||||
let (r, mut w) = tokio::io::split(stream);
|
||||
let mut lines = BufReader::new(r).lines();
|
||||
let mut refusals = refusals.into_iter();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
log.lock().unwrap().push((line, Instant::now()));
|
||||
let answer = refusals.next().unwrap_or("error id=0 msg=ok");
|
||||
if w.write_all(format!("{answer}\n\r").as_bytes()).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
seen
|
||||
}
|
||||
|
||||
fn client(options: &LineOptions) -> (LineClient, Seen) {
|
||||
client_refused(options, Vec::new())
|
||||
}
|
||||
|
||||
fn client_refused(options: &LineOptions, refusals: Vec<&'static str>) -> (LineClient, Seen) {
|
||||
let (client_io, server_io) = duplex(4096);
|
||||
let seen = answering_server(server_io, refusals);
|
||||
let (r, w) = tokio::io::split(client_io);
|
||||
let (client, _events) = LineClient::spawn(r, w, options.clone());
|
||||
(client, seen)
|
||||
}
|
||||
|
||||
const FLOOD: &str =
|
||||
"error id=524 msg=client\\sis\\sflooding extra_msg=please\\swait\\s2\\sseconds";
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn connections_share_the_flood_limit() {
|
||||
// TeamSpeak counts the commands of all connections from one address.
|
||||
let options =
|
||||
LineOptions { rate_limit: Some((2, Duration::from_secs(3))), ..Default::default() };
|
||||
let (a, seen_a) = client(&options);
|
||||
let (b, seen_b) = client(&options.clone());
|
||||
let t0 = Instant::now();
|
||||
a.send(&Command::new("whoami")).await.unwrap();
|
||||
a.send(&Command::new("whoami")).await.unwrap();
|
||||
b.send(&Command::new("version")).await.unwrap();
|
||||
let at = |seen: &Seen, i: usize| seen.lock().unwrap()[i].1;
|
||||
assert_eq!(at(&seen_a, 1), t0);
|
||||
assert!(at(&seen_b, 0) >= t0 + Duration::from_secs(3), "the third command waited");
|
||||
// Options built separately count separately.
|
||||
let (c, seen_c) = client(&LineOptions {
|
||||
rate_limit: Some((2, Duration::from_secs(3))),
|
||||
..Default::default()
|
||||
});
|
||||
let t1 = Instant::now();
|
||||
c.send(&Command::new("whoami")).await.unwrap();
|
||||
assert_eq!(at(&seen_c, 0), t1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_flood_refusal_holds_every_connection_then_resends_once() {
|
||||
let options = LineOptions { rate_limit: None, ..Default::default() };
|
||||
let (a, seen_a) = client_refused(&options, vec![FLOOD]);
|
||||
let (b, seen_b) = client(&options);
|
||||
let t0 = Instant::now();
|
||||
let first = tokio::spawn(async move { a.send(&Command::new("clientlist")).await });
|
||||
// While the server's wait lasts, the other connection sends nothing.
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
b.send(&Command::new("whoami")).await.unwrap();
|
||||
assert!(first.await.unwrap().is_ok(), "resent after the wait");
|
||||
// At least the server's 3 s window, longer than it asked for.
|
||||
let wait = Duration::from_millis(3100);
|
||||
let seen_a = seen_a.lock().unwrap().clone();
|
||||
assert_eq!(seen_a.len(), 2);
|
||||
assert_eq!(seen_a[0].0, "clientlist");
|
||||
assert!(seen_a[1].1 >= t0 + wait);
|
||||
assert!(seen_b.lock().unwrap()[0].1 >= t0 + wait);
|
||||
|
||||
// Refused again: the caller gets the error, and sending still waits.
|
||||
let (c, seen_c) = client_refused(&options, vec![FLOOD, FLOOD]);
|
||||
match c.send(&Command::new("clientlist")).await {
|
||||
Err(Error::Query(e)) => assert!(e.is_flood()),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_eq!(seen_c.lock().unwrap().len(), 2);
|
||||
assert!(options.flood.held_for().is_some_and(|d| d > Duration::from_secs(2)));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_refusal_without_a_limit_brings_the_servers_limit() {
|
||||
// Taken to be on the allowlist, and it is not.
|
||||
let options = LineOptions { rate_limit: None, ..Default::default() };
|
||||
let (a, seen) = client_refused(&options, vec![FLOOD]);
|
||||
for _ in 0..10 {
|
||||
a.send(&Command::new("whoami")).await.unwrap();
|
||||
}
|
||||
let seen = seen.lock().unwrap().clone();
|
||||
// Refused, resent, then 8 more at once and the 9th after 3 s.
|
||||
assert_eq!(seen.len(), 11);
|
||||
let resent = seen[1].1;
|
||||
assert!(seen[9].1 - resent < Duration::from_secs(1));
|
||||
assert!(seen[10].1 - resent >= Duration::from_secs(3));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn commands_whose_caller_gave_up_are_not_sent() {
|
||||
let options =
|
||||
LineOptions { rate_limit: None, timeout: Duration::from_secs(1), ..Default::default() };
|
||||
let (a, seen) = client(&options);
|
||||
options.flood.hold(Duration::from_secs(5));
|
||||
assert!(matches!(a.send(&Command::new("clientlist")).await, Err(Error::Timeout)));
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
a.send(&Command::new("whoami")).await.unwrap();
|
||||
let sent: Vec<String> = seen.lock().unwrap().iter().map(|(l, _)| l.clone()).collect();
|
||||
assert_eq!(sent, ["whoami"]);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_server_that_stops_answering_is_left() {
|
||||
let (client_io, server_io) = duplex(4096);
|
||||
// Reads commands and never answers.
|
||||
tokio::spawn(async move {
|
||||
let mut lines = BufReader::new(server_io).lines();
|
||||
while let Ok(Some(_)) = lines.next_line().await {}
|
||||
});
|
||||
let (r, w) = tokio::io::split(client_io);
|
||||
let options =
|
||||
LineOptions { rate_limit: None, timeout: Duration::from_secs(1), ..Default::default() };
|
||||
let (client, _events) = LineClient::spawn(r, w, options);
|
||||
assert!(matches!(client.send(&Command::new("whoami")).await, Err(Error::Timeout)));
|
||||
assert!(!client.is_closed());
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
assert!(client.is_closed());
|
||||
assert!(matches!(client.send(&Command::new("whoami")).await, Err(Error::Closed)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wait_comes_from_the_refusal() {
|
||||
let refusal = |extra: Option<&str>| QueryError {
|
||||
id: 524,
|
||||
msg: "client is flooding".into(),
|
||||
extra_msg: extra.map(Into::into),
|
||||
failed_permid: None,
|
||||
};
|
||||
assert_eq!(flood_wait(&refusal(Some("please wait 600 seconds"))).as_secs(), 600);
|
||||
assert_eq!(flood_wait(&refusal(None)).as_secs(), 3);
|
||||
assert_eq!(
|
||||
loggable("login client_login_name=a client_login_password=secret").find("secret"),
|
||||
None
|
||||
);
|
||||
assert_eq!(loggable("whoami"), "whoami");
|
||||
}
|
||||
|
||||
/// Records each write it gets.
|
||||
struct Writes(Vec<Vec<u8>>);
|
||||
|
||||
impl AsyncWrite for Writes {
|
||||
fn poll_write(
|
||||
mut self: std::pin::Pin<&mut Self>,
|
||||
_: &mut std::task::Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> std::task::Poll<std::io::Result<usize>> {
|
||||
self.0.push(buf.to_vec());
|
||||
std::task::Poll::Ready(Ok(buf.len()))
|
||||
}
|
||||
|
||||
fn poll_flush(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
std::task::Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(
|
||||
self: std::pin::Pin<&mut Self>,
|
||||
_: &mut std::task::Context<'_>,
|
||||
) -> std::task::Poll<std::io::Result<()>> {
|
||||
std::task::Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_command_goes_out_in_one_write() {
|
||||
let mut writes = Writes(Vec::new());
|
||||
write_line(&mut writes, "clientlist -uid").await.unwrap();
|
||||
assert_eq!(writes.0, [b"clientlist -uid\n".to_vec()]);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use std::time::Duration;
|
||||
use russh::client;
|
||||
use russh::keys::PublicKeyOrCertificate;
|
||||
|
||||
use crate::tcp::QuickAck;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Accepts any host key. ServerQuery hosts generate their key on first start
|
||||
@@ -38,16 +39,24 @@ pub(crate) struct Shell {
|
||||
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> {
|
||||
/// Open an SSH session and start the query shell, giving up on the TCP
|
||||
/// connection after `timeout`.
|
||||
pub(crate) async fn connect(
|
||||
addr: &str,
|
||||
user: &str,
|
||||
password: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<Shell> {
|
||||
let config = Arc::new(client::Config {
|
||||
inactivity_timeout: None,
|
||||
keepalive_interval: Some(Duration::from_secs(60)),
|
||||
nodelay: true,
|
||||
..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 stream = QuickAck::connect(addr, timeout).await?;
|
||||
let mut session = client::connect_stream(config, stream, handler).await?;
|
||||
let auth = session.authenticate_password(user, password).await?;
|
||||
if !auth.success() {
|
||||
return Err(Error::SshAuth);
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! TCP for the line-based transports.
|
||||
//!
|
||||
//! TeamSpeak sends a reply in more than one segment and waits for the
|
||||
//! client's ACK of the first before it sends the rest. Linux delays that ACK
|
||||
//! by about 40 ms, so every query command took about 45 ms. Re-arming
|
||||
//! `TCP_QUICKACK` after each read that returned data (the kernel clears it
|
||||
//! by itself) makes the ACK go out at once: a command then takes under 1 ms.
|
||||
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
/// A TCP connection that acknowledges what it receives at once.
|
||||
pub(crate) struct QuickAck(TcpStream);
|
||||
|
||||
impl QuickAck {
|
||||
/// Connect to `addr`, giving up after `timeout`.
|
||||
pub(crate) async fn connect(addr: &str, timeout: Duration) -> io::Result<Self> {
|
||||
let stream =
|
||||
tokio::time::timeout(timeout, TcpStream::connect(addr)).await.map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
format!("no connection to {addr} within {} s", timeout.as_secs()),
|
||||
)
|
||||
})??;
|
||||
stream.set_nodelay(true)?;
|
||||
let stream = Self(stream);
|
||||
stream.rearm();
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
fn rearm(&self) {
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
let _ = socket2::SockRef::from(&self.0).set_tcp_quickack(true);
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for QuickAck {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
let before = buf.filled().len();
|
||||
let poll = Pin::new(&mut self.0).poll_read(cx, buf);
|
||||
if matches!(poll, Poll::Ready(Ok(()))) && buf.filled().len() > before {
|
||||
self.rearm();
|
||||
}
|
||||
poll
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for QuickAck {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.0).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_write_vectored(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
bufs: &[io::IoSlice<'_>],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.0).poll_write_vectored(cx, bufs)
|
||||
}
|
||||
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
self.0.is_write_vectored()
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.0).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.0).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user