russh sends the subsystem request without waiting for its reply, so a server
that refuses SFTP, or an account with a forced command that accepts the request
and closes the channel at once, surfaced as the raw "sender dropped" of the
SFTP greeting. Read the reply first and map each case to a plain message
("<host> doesn't offer file access (SFTP)", "... to this account", "didn't
start file access (SFTP) in time"). Sign-in failures now say what was refused
(key, password, a key left locked). Messages name the host as written (the ssh
config alias).
One connect attempt per host at a time: callers that wait for it share its
connection or its error, and a second click on a Network entry while its home
folder is looked up does nothing, so a double click no longer shows two toasts.
Tests: refused subsystem, forced command, channel closed without reply,
concurrent requests sharing one attempt, specific auth errors.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
405 lines
13 KiB
Rust
405 lines
13 KiB
Rust
//! Background tokio runtime and the connection manager: one SFTP session per
|
|
//! (user, host, port), reused, kept alive, reconnected after a drop and closed when idle.
|
|
|
|
use std::collections::HashMap;
|
|
use std::future::Future;
|
|
use std::sync::{Arc, Mutex, OnceLock};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use russh::ChannelMsg;
|
|
use russh::client::{self, Handle};
|
|
use russh::keys::{HashAlg, PublicKeyOrCertificate};
|
|
use russh_sftp::client::SftpSession;
|
|
use russh_sftp::client::error::Error as SftpError;
|
|
use tokio::runtime::Runtime;
|
|
use tunal_core::{Error, Result};
|
|
|
|
use crate::auth::{AuthPref, HostKeyChoice, HostKeyInfo, Prompts, authenticate};
|
|
use crate::known_hosts::{self, HostCheck, KnownHosts};
|
|
use crate::ssh_config::Resolved;
|
|
|
|
const SWEEP: Duration = Duration::from_secs(30);
|
|
|
|
/// Connection settings; new values apply to connections made afterwards (idle close at once).
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Options {
|
|
pub connect_timeout: Duration,
|
|
/// `None`: no keepalive messages.
|
|
pub keepalive: Option<Duration>,
|
|
pub idle_close: Duration,
|
|
}
|
|
|
|
impl Default for Options {
|
|
fn default() -> Self {
|
|
Self {
|
|
connect_timeout: Duration::from_secs(15),
|
|
keepalive: Some(Duration::from_secs(30)),
|
|
idle_close: Duration::from_secs(300),
|
|
}
|
|
}
|
|
}
|
|
|
|
static OPTIONS: Mutex<Options> = Mutex::new(Options {
|
|
connect_timeout: Duration::from_secs(15),
|
|
keepalive: Some(Duration::from_secs(30)),
|
|
idle_close: Duration::from_secs(300),
|
|
});
|
|
|
|
pub fn set_options(options: Options) {
|
|
*OPTIONS.lock().unwrap() = options;
|
|
}
|
|
|
|
fn options() -> Options {
|
|
*OPTIONS.lock().unwrap()
|
|
}
|
|
|
|
fn runtime() -> &'static Runtime {
|
|
static RT: OnceLock<Runtime> = OnceLock::new();
|
|
RT.get_or_init(|| {
|
|
tokio::runtime::Builder::new_multi_thread()
|
|
.worker_threads(2)
|
|
.thread_name("tunal-net")
|
|
.enable_all()
|
|
.build()
|
|
.expect("tokio runtime")
|
|
})
|
|
}
|
|
|
|
/// Runs `fut` on the network runtime and blocks the calling (non-runtime) thread.
|
|
pub(crate) fn block_on<T>(fut: impl Future<Output = T>) -> T {
|
|
runtime().block_on(fut)
|
|
}
|
|
|
|
/// Where a connection goes.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
pub(crate) struct ConnKey {
|
|
pub user: String,
|
|
pub host: String,
|
|
pub port: u16,
|
|
}
|
|
|
|
/// A live SSH connection with its SFTP session.
|
|
pub(crate) struct Conn {
|
|
handle: Handle<Client>,
|
|
pub sftp: SftpSession,
|
|
last_used: Mutex<Instant>,
|
|
}
|
|
|
|
impl Conn {
|
|
fn touch(&self) {
|
|
*self.last_used.lock().unwrap() = Instant::now();
|
|
}
|
|
|
|
fn alive(&self) -> bool {
|
|
!self.handle.is_closed()
|
|
}
|
|
|
|
async fn close(&self) {
|
|
let _ = self.sftp.close().await;
|
|
let _ = self
|
|
.handle
|
|
.disconnect(russh::Disconnect::ByApplication, "", "en")
|
|
.await;
|
|
}
|
|
}
|
|
|
|
/// Connection pool. Cheap to clone via `Arc`.
|
|
pub(crate) struct Pool {
|
|
conns: Mutex<HashMap<ConnKey, Arc<Conn>>>,
|
|
/// Held while connecting to a key; holds the last failed attempt and when it ended.
|
|
attempts: Mutex<HashMap<ConnKey, Arc<Mutex<Attempt>>>>,
|
|
prompts: Arc<dyn Prompts>,
|
|
}
|
|
|
|
type Attempt = Option<(Instant, Error)>;
|
|
|
|
impl Pool {
|
|
pub fn new(prompts: Arc<dyn Prompts>) -> Arc<Self> {
|
|
let pool = Arc::new(Self {
|
|
conns: Mutex::default(),
|
|
attempts: Mutex::default(),
|
|
prompts,
|
|
});
|
|
let weak = Arc::downgrade(&pool);
|
|
runtime().spawn(async move {
|
|
loop {
|
|
tokio::time::sleep(SWEEP).await;
|
|
let Some(pool) = weak.upgrade() else { return };
|
|
pool.close_idle().await;
|
|
}
|
|
});
|
|
pool
|
|
}
|
|
|
|
/// A live connection for `key`, connecting (and authenticating) when needed. One attempt
|
|
/// per key at a time: callers that waited for it share its connection or its error.
|
|
pub fn get(&self, key: &ConnKey, resolved: &Resolved, pref: &AuthPref) -> Result<Arc<Conn>> {
|
|
let asked = Instant::now();
|
|
if let Some(c) = self.live(key) {
|
|
return Ok(c);
|
|
}
|
|
let slot = self
|
|
.attempts
|
|
.lock()
|
|
.unwrap()
|
|
.entry(key.clone())
|
|
.or_default()
|
|
.clone();
|
|
let mut last = slot.lock().unwrap();
|
|
if let Some(c) = self.live(key) {
|
|
return Ok(c);
|
|
}
|
|
if let Some((at, e)) = &*last
|
|
&& *at >= asked
|
|
{
|
|
return Err(e.clone());
|
|
}
|
|
match block_on(connect(key, resolved, pref, &self.prompts)) {
|
|
Ok(conn) => {
|
|
*last = None;
|
|
self.conns.lock().unwrap().insert(key.clone(), conn.clone());
|
|
Ok(conn)
|
|
}
|
|
Err(e) => {
|
|
*last = Some((Instant::now(), e.clone()));
|
|
Err(e)
|
|
}
|
|
}
|
|
}
|
|
|
|
fn live(&self, key: &ConnKey) -> Option<Arc<Conn>> {
|
|
let conns = self.conns.lock().unwrap();
|
|
let c = conns.get(key).filter(|c| c.alive())?;
|
|
c.touch();
|
|
Some(c.clone())
|
|
}
|
|
|
|
/// Forgets a connection that failed mid-operation so the next `get` reconnects.
|
|
pub fn drop_conn(&self, key: &ConnKey, conn: &Arc<Conn>) {
|
|
let mut conns = self.conns.lock().unwrap();
|
|
if conns.get(key).is_some_and(|c| Arc::ptr_eq(c, conn)) {
|
|
conns.remove(key);
|
|
}
|
|
}
|
|
|
|
pub fn is_connected(&self, key: &ConnKey) -> bool {
|
|
self.conns
|
|
.lock()
|
|
.unwrap()
|
|
.get(key)
|
|
.is_some_and(|c| c.alive())
|
|
}
|
|
|
|
/// Closes the connection to `key` (streams still open on it fail).
|
|
pub fn disconnect(&self, key: &ConnKey) {
|
|
let conn = self.conns.lock().unwrap().remove(key);
|
|
if let Some(conn) = conn {
|
|
block_on(conn.close());
|
|
}
|
|
}
|
|
|
|
/// Closes connections unused for `IDLE_CLOSE` that nothing else holds (open streams do).
|
|
async fn close_idle(&self) {
|
|
let stale: Vec<Arc<Conn>> = {
|
|
let mut conns = self.conns.lock().unwrap();
|
|
let mut out = Vec::new();
|
|
conns.retain(|_, c| {
|
|
let idle = c.last_used.lock().unwrap().elapsed() > options().idle_close;
|
|
let drop_it = !c.alive() || (idle && Arc::strong_count(c) == 1);
|
|
if drop_it {
|
|
out.push(c.clone());
|
|
}
|
|
!drop_it
|
|
});
|
|
out
|
|
};
|
|
for c in stale {
|
|
c.close().await;
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn connect(
|
|
key: &ConnKey,
|
|
resolved: &Resolved,
|
|
pref: &AuthPref,
|
|
prompts: &Arc<dyn Prompts>,
|
|
) -> Result<Arc<Conn>> {
|
|
let opts = options();
|
|
if resolved.unsupported_proxy {
|
|
return Err(Error::Remote(
|
|
"hosts behind ProxyJump / ProxyCommand are not supported".into(),
|
|
));
|
|
}
|
|
let config = Arc::new(client::Config {
|
|
keepalive_interval: opts.keepalive,
|
|
keepalive_max: 3,
|
|
..Default::default()
|
|
});
|
|
let failure = Arc::new(Mutex::new(None));
|
|
let client = Client {
|
|
host: key.host.clone(),
|
|
port: key.port,
|
|
known: KnownHosts::load_default(),
|
|
prompts: prompts.clone(),
|
|
failure: failure.clone(),
|
|
};
|
|
// Messages name the host as the user wrote it (an ssh config alias, say).
|
|
let name = resolved.alias.as_str();
|
|
let connecting = client::connect(config, (key.host.as_str(), key.port), client);
|
|
let mut handle = match tokio::time::timeout(opts.connect_timeout, connecting).await {
|
|
Err(_) => return Err(Error::Remote(format!("connecting to {name} timed out"))),
|
|
Ok(Err(e)) => {
|
|
let reason = failure.lock().unwrap().take();
|
|
return Err(Error::Remote(reason.unwrap_or_else(|| why(&e, name))));
|
|
}
|
|
Ok(Ok(h)) => h,
|
|
};
|
|
authenticate(&mut handle, &key.user, name, resolved, pref, prompts).await?;
|
|
let sftp = tokio::time::timeout(opts.connect_timeout, open_sftp(&handle, name))
|
|
.await
|
|
.map_err(|_| sftp_timeout(name))??;
|
|
Ok(Arc::new(Conn {
|
|
handle,
|
|
sftp,
|
|
last_used: Mutex::new(Instant::now()),
|
|
}))
|
|
}
|
|
|
|
fn sftp_timeout(name: &str) -> Error {
|
|
Error::Remote(format!("{name} didn't start file access (SFTP) in time"))
|
|
}
|
|
|
|
/// Opens the `sftp` subsystem on a new channel. A server that only runs a fixed command for
|
|
/// the account (a forced command, as on code hosting servers) accepts the request and then
|
|
/// closes the channel without the SFTP greeting.
|
|
async fn open_sftp(handle: &Handle<Client>, name: &str) -> Result<SftpSession> {
|
|
let refused = || Error::Remote(format!("{name} doesn't offer file access (SFTP)"));
|
|
let mut channel = handle
|
|
.channel_open_session()
|
|
.await
|
|
.map_err(|e| Error::Remote(why(&e, name)))?;
|
|
channel
|
|
.request_subsystem(true, "sftp")
|
|
.await
|
|
.map_err(|e| Error::Remote(why(&e, name)))?;
|
|
// russh doesn't wait for the reply: read it here, before the stream takes the channel.
|
|
loop {
|
|
match channel.wait().await {
|
|
Some(ChannelMsg::Success) => break,
|
|
Some(
|
|
ChannelMsg::Failure
|
|
| ChannelMsg::Eof
|
|
| ChannelMsg::Close
|
|
| ChannelMsg::ExitStatus { .. }
|
|
| ChannelMsg::ExitSignal { .. },
|
|
)
|
|
| None => return Err(refused()),
|
|
Some(_) => {}
|
|
}
|
|
}
|
|
SftpSession::new(channel.into_stream())
|
|
.await
|
|
.map_err(|e| match e {
|
|
SftpError::Timeout => sftp_timeout(name),
|
|
_ => Error::Remote(format!(
|
|
"{name} doesn't offer file access (SFTP) to this account"
|
|
)),
|
|
})
|
|
}
|
|
|
|
/// A russh failure in plain words.
|
|
fn why(e: &russh::Error, host: &str) -> String {
|
|
use std::io::ErrorKind::*;
|
|
match e {
|
|
russh::Error::IO(io) => match io.kind() {
|
|
ConnectionRefused => format!("{host} refused the connection"),
|
|
TimedOut => format!("{host} didn't answer in time"),
|
|
ConnectionReset | UnexpectedEof | BrokenPipe => format!("{host} closed the connection"),
|
|
_ if io.to_string().contains("lookup") || io.to_string().contains("resolve") => {
|
|
format!("couldn't find {host}")
|
|
}
|
|
_ => format!("couldn't reach {host}"),
|
|
},
|
|
russh::Error::Disconnect | russh::Error::HUP => format!("{host} closed the connection"),
|
|
_ => format!("couldn't connect to {host}"),
|
|
}
|
|
}
|
|
|
|
/// russh handler: checks the server key against known_hosts.
|
|
struct Client {
|
|
host: String,
|
|
port: u16,
|
|
known: KnownHosts,
|
|
prompts: Arc<dyn Prompts>,
|
|
/// Why the key was refused, for a readable error.
|
|
failure: Arc<Mutex<Option<String>>>,
|
|
}
|
|
|
|
impl Client {
|
|
fn info(&self, key_type: &str, fingerprint: String) -> HostKeyInfo {
|
|
HostKeyInfo {
|
|
host: self.host.clone(),
|
|
port: self.port,
|
|
key_type: key_type.to_owned(),
|
|
fingerprint,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl client::Handler for Client {
|
|
type Error = russh::Error;
|
|
|
|
async fn check_server_key(
|
|
&mut self,
|
|
key: &PublicKeyOrCertificate,
|
|
) -> std::result::Result<bool, Self::Error> {
|
|
// Certificate hosts are not supported: the CA lines are ignored (S027).
|
|
let PublicKeyOrCertificate::PublicKey { key, .. } = key else {
|
|
*self.failure.lock().unwrap() = Some("host certificates are not supported".into());
|
|
return Ok(false);
|
|
};
|
|
let fingerprint = key.fingerprint(HashAlg::Sha256).to_string();
|
|
let key_type = key.algorithm().to_string();
|
|
let blob = key
|
|
.to_openssh()
|
|
.ok()
|
|
.and_then(|l| l.split_whitespace().nth(1).map(str::to_owned));
|
|
let Some(blob) = blob else { return Ok(false) };
|
|
let fail = |msg: String| *self.failure.lock().unwrap() = Some(msg);
|
|
let check = self.known.check(&self.host, self.port, &key_type, &blob);
|
|
match check {
|
|
HostCheck::Match => Ok(true),
|
|
HostCheck::Mismatch | HostCheck::Revoked => {
|
|
let revoked = check == HostCheck::Revoked;
|
|
let info = self.info(&key_type, fingerprint);
|
|
let prompts = self.prompts.clone();
|
|
let _ = tokio::task::spawn_blocking(move || prompts.host_key_changed(&info)).await;
|
|
fail(if revoked {
|
|
format!("the host key of {} is revoked", self.host)
|
|
} else {
|
|
format!(
|
|
"the host key of {} changed; someone may be intercepting the connection",
|
|
self.host
|
|
)
|
|
});
|
|
Ok(false)
|
|
}
|
|
HostCheck::Unknown => {
|
|
let info = self.info(&key_type, fingerprint);
|
|
let prompts = self.prompts.clone();
|
|
let choice = tokio::task::spawn_blocking(move || prompts.confirm_host_key(&info))
|
|
.await
|
|
.unwrap_or(HostKeyChoice::Refuse);
|
|
if choice == HostKeyChoice::Refuse {
|
|
fail(format!("the host key of {} was not accepted", self.host));
|
|
return Ok(false);
|
|
}
|
|
if let (HostKeyChoice::Always, Some(own)) = (choice, known_hosts::own_file()) {
|
|
let _ = known_hosts::accept_key(&own, &self.host, self.port, &key_type, &blob);
|
|
}
|
|
Ok(true)
|
|
}
|
|
}
|
|
}
|
|
}
|