//! 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::client::{self, Handle}; use russh::keys::{HashAlg, PublicKeyOrCertificate}; use russh_sftp::client::SftpSession; use tokio::runtime::Runtime; use tunal_core::{Error, Result}; use crate::auth::{HostKeyInfo, Prompts, authenticate}; use crate::known_hosts::{self, HostCheck, KnownHosts}; use crate::ssh_config::Resolved; const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); const KEEPALIVE: Duration = Duration::from_secs(30); const IDLE_CLOSE: Duration = Duration::from_secs(300); const SWEEP: Duration = Duration::from_secs(30); fn runtime() -> &'static Runtime { static RT: OnceLock = 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(fut: impl Future) -> 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, pub sftp: SftpSession, last_used: Mutex, } 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>>, prompts: Arc, } impl Pool { pub fn new(prompts: Arc) -> Arc { let pool = Arc::new(Self { conns: 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. pub fn get(&self, key: &ConnKey, resolved: &Resolved) -> Result> { if let Some(c) = self.conns.lock().unwrap().get(key).filter(|c| c.alive()) { c.touch(); return Ok(c.clone()); } let conn = block_on(connect(key, resolved, &self.prompts))?; self.conns.lock().unwrap().insert(key.clone(), conn.clone()); Ok(conn) } /// Forgets a connection that failed mid-operation so the next `get` reconnects. pub fn drop_conn(&self, key: &ConnKey, conn: &Arc) { let mut conns = self.conns.lock().unwrap(); if conns.get(key).is_some_and(|c| Arc::ptr_eq(c, conn)) { conns.remove(key); } } /// Closes connections unused for `IDLE_CLOSE` that nothing else holds (open streams do). async fn close_idle(&self) { let stale: Vec> = { let mut conns = self.conns.lock().unwrap(); let mut out = Vec::new(); conns.retain(|_, c| { let idle = c.last_used.lock().unwrap().elapsed() > 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, prompts: &Arc, ) -> Result> { if resolved.unsupported_proxy { return Err(Error::Remote( "hosts behind ProxyJump / ProxyCommand are not supported".into(), )); } let config = Arc::new(client::Config { keepalive_interval: Some(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(), }; let connecting = client::connect(config, (key.host.as_str(), key.port), client); let mut handle = match tokio::time::timeout(CONNECT_TIMEOUT, connecting).await { Err(_) => { return Err(Error::Remote(format!( "connecting to {} timed out", key.host ))); } Ok(Err(e)) => { let reason = failure.lock().unwrap().take(); return Err(Error::Remote(reason.unwrap_or_else(|| e.to_string()))); } Ok(Ok(h)) => h, }; authenticate(&mut handle, &key.user, &key.host, resolved, prompts).await?; let remote = |e: &dyn std::fmt::Display| Error::Remote(e.to_string()); let channel = handle .channel_open_session() .await .map_err(|e| remote(&e))?; channel .request_subsystem(true, "sftp") .await .map_err(|e| remote(&e))?; let sftp = SftpSession::new(channel.into_stream()) .await .map_err(|e| remote(&e))?; Ok(Arc::new(Conn { handle, sftp, last_used: Mutex::new(Instant::now()), })) } /// russh handler: checks the server key against known_hosts. struct Client { host: String, port: u16, known: KnownHosts, prompts: Arc, /// Why the key was refused, for a readable error. failure: Arc>>, } impl client::Handler for Client { type Error = russh::Error; async fn check_server_key( &mut self, key: &PublicKeyOrCertificate, ) -> std::result::Result { // 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); match self.known.check(&self.host, self.port, &key_type, &blob) { HostCheck::Match => Ok(true), HostCheck::Mismatch => { fail(format!( "host key of {} changed ({fingerprint}); someone may be intercepting the connection", self.host )); Ok(false) } HostCheck::Revoked => { fail(format!( "host key of {} is revoked ({fingerprint})", self.host )); Ok(false) } HostCheck::Unknown => { let info = HostKeyInfo { host: self.host.clone(), port: self.port, key_type: key_type.clone(), fingerprint, }; let prompts = self.prompts.clone(); let ask = info.clone(); let accepted = tokio::task::spawn_blocking(move || prompts.confirm_host_key(&ask)) .await .unwrap_or(false); if !accepted { fail(format!("host key of {} was not accepted", self.host)); return Ok(false); } if let Some(own) = known_hosts::own_file() { let _ = known_hosts::accept_key(&own, &self.host, self.port, &key_type, &blob); } Ok(true) } } } }