use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
use std::time::Duration;
use super::no_console;
use crate::Result;
use crate::error::Error;
use crate::name::RunName;
use crate::process::ProcessSpec;
use crate::process::ledger::Recorded;
use crate::project::platform::Protocol;
use crate::runner::Runner;
use crate::ssh::Login;
const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
const OPENING: Duration = Duration::from_secs(20);
const SAYING_WHY: Duration = Duration::from_secs(2);
const STEP: &str = "console";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct To {
pub(crate) via: Login,
pub(crate) host: String,
pub(crate) port: u16,
pub(crate) key: Option<PathBuf>,
pub(crate) known_hosts: Option<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Purpose<'a> {
Console(&'a str),
Endpoint(&'a str),
}
impl Purpose<'_> {
pub(crate) fn refused(self, why: impl Into<String>) -> Error {
match self {
Purpose::Console(machine) => no_console(machine, why),
Purpose::Endpoint(name) => Error::ToolFailed {
step: "endpoint".to_owned(),
reason: format!("`{name}`: {}", why.into()),
},
}
}
}
#[derive(Debug)]
pub struct Tunnel {
local: SocketAddr,
via: String,
ssh: tokio::process::Child,
drain: Option<tokio::task::JoinHandle<()>>,
_recorded: Option<Recorded>,
}
impl Drop for Tunnel {
fn drop(&mut self) {
if let Err(e) = self.ssh.start_kill() {
tracing::debug!(error = %e, "a console's tunnel had ended already");
}
if let Some(drain) = self.drain.take() {
drain.abort();
}
}
}
impl Tunnel {
#[must_use]
pub fn local(&self) -> SocketAddr {
self.local
}
pub(crate) fn runs(&mut self) -> bool {
matches!(self.ssh.try_wait(), Ok(None))
}
#[must_use]
pub fn via(&self) -> &str {
&self.via
}
pub async fn closed(&mut self) -> String {
match self.ssh.wait().await {
Ok(status) => match status.code() {
Some(code) => format!("its ssh exited with code {code}"),
None => "its ssh was ended by a signal".to_owned(),
},
Err(e) => format!("its ssh couldn't be waited for: {e}"),
}
}
async fn why_closed(&mut self) -> Option<String> {
use tokio::io::AsyncReadExt;
if tokio::time::timeout(SAYING_WHY, self.ssh.wait()).await.is_err()
&& let Err(e) = self.ssh.start_kill()
{
tracing::debug!(error = %e, "a console's tunnel couldn't be stopped");
}
let mut stderr = self.ssh.stderr.take()?;
let mut said = Vec::new();
if let Ok(Err(e)) = tokio::time::timeout(SAYING_WHY, stderr.read_to_end(&mut said)).await {
tracing::debug!(error = %e, "a console's tunnel's standard error couldn't be read");
}
String::from_utf8_lossy(&said)
.lines()
.map(str::trim)
.rfind(|l| !l.is_empty())
.map(str::to_owned)
}
fn drain(&mut self) {
let Some(stderr) = self.ssh.stderr.take() else { return };
self.drain = Some(tokio::spawn(async move {
use tokio::io::AsyncBufReadExt;
let mut lines = tokio::io::BufReader::new(stderr).lines();
while let Ok(Some(line)) = lines.next_line().await {
tracing::debug!(%line, "a console's tunnel's ssh said");
}
}));
}
}
fn ssh_spec(purpose: Purpose<'_>, to: &To, key: &Path, state_dir: &Path, local: u16) -> Result<ProcessSpec> {
let address = |h: &str| !h.is_empty() && !h.starts_with('-') && h.chars().all(|c| c.is_ascii_alphanumeric() || ".:-".contains(c));
if !address(&to.host) {
return Err(purpose.refused(format!("its address `{}` isn't one a tunnel goes to", to.host.escape_debug())));
}
let forward = format!("{LOOPBACK}:{local}:{}:{}", bracketed(&to.host), to.port);
let mut args = crate::ssh::options(key, state_dir, crate::ssh::First::given(to.known_hosts.as_deref()))?;
args.extend(["-N", "-o", "ExitOnForwardFailure=yes", "-L", &forward].map(String::from));
args.push(to.via.target());
let mut spec = ProcessSpec::new("ssh", args);
spec.cwd = Some(state_dir.to_path_buf());
Ok(spec)
}
fn bracketed(host: &str) -> String {
if host.contains(':') { format!("[{host}]") } else { host.to_owned() }
}
pub(crate) async fn open(runner: &Runner, run: &RunName, state_dir: &Path, purpose: Purpose<'_>, to: &To) -> Result<Tunnel> {
let config = &runner.config;
crate::ssh::ready(
config.processes.as_ref(),
state_dir,
&to.via.host,
crate::ssh::First::given(to.known_hosts.as_deref()),
)
.await?;
let key = to.key.clone().unwrap_or_else(|| crate::ssh::key_path(&config.home));
let free = runner
.pick_unreserved(run, Protocol::Tcp)
.map_err(Error::io("a tcp port on 127.0.0.1", "bound"))?
.ok_or_else(|| purpose.refused("no free port on this computer's loopback for its tunnel"))?;
let local = free.port.get();
drop(free);
let spec = ssh_spec(purpose, to, &key, state_dir, local)?;
let ledger = state_dir.join(crate::process::ledger::DIR);
let mut tunnel = started(purpose, &spec, SocketAddr::new(LOOPBACK, local), &to.via.target(), &ledger)?;
let probe = || config.ports.reachable(LOOPBACK_TEXT, local, PROBE);
if !answers(&mut tunnel, probe, OPENING).await {
let because = tunnel.why_closed().await.map_or_else(String::new, |line| format!(": ssh said `{line}`"));
return Err(purpose.refused(format!(
"its tunnel through {} didn't open (SSH refused, or {}:{} doesn't answer from there){because}",
tunnel.via, to.host, to.port
)));
}
tunnel.drain();
Ok(tunnel)
}
const PROBE: Duration = Duration::from_secs(2);
const POLL: Duration = Duration::from_millis(200);
const LOOPBACK_TEXT: &str = "127.0.0.1";
async fn answers<'a>(tunnel: &mut Tunnel, probe: impl Fn() -> crate::BoxFuture<'a, bool>, within: Duration) -> bool {
let deadline = tokio::time::Instant::now() + within;
loop {
if probe().await {
return true;
}
if !tunnel.runs() || tokio::time::Instant::now() >= deadline {
return false;
}
tokio::time::sleep(POLL).await;
}
}
fn started(purpose: Purpose<'_>, spec: &ProcessSpec, local: SocketAddr, via: &str, ledger: &Path) -> Result<Tunnel> {
start(spec, local, via, ledger).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => Error::ToolMissing {
step: STEP.to_owned(),
tool: spec.program.clone(),
},
_ => purpose.refused(format!("its tunnel's `{}` didn't start: {e}", spec.program)),
})
}
#[expect(
clippy::disallowed_methods,
reason = "the SSH tunnel is a long-lived child its `Tunnel` owns and stops, not a call the process module waits on"
)]
fn start(spec: &ProcessSpec, local: SocketAddr, via: &str, ledger: &Path) -> std::io::Result<Tunnel> {
let mut command = tokio::process::Command::new(&spec.program);
command
.args(&spec.args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
if let Some(cwd) = &spec.cwd {
command.current_dir(cwd);
}
own_group(&mut command);
let ssh = command.spawn()?;
let recorded = ssh.id().and_then(|pid| Recorded::tunnel(ledger, pid));
Ok(Tunnel {
local,
via: via.to_owned(),
ssh,
drain: None,
_recorded: recorded,
})
}
#[cfg(unix)]
fn own_group(command: &mut tokio::process::Command) {
command.process_group(0);
}
#[cfg(windows)]
fn own_group(command: &mut tokio::process::Command) {
use windows::Win32::System::Threading::CREATE_NO_WINDOW;
command.creation_flags(CREATE_NO_WINDOW.0);
}
#[cfg(test)]
mod tests {
use super::*;
fn to(host: &str) -> To {
To {
via: Login::new("admin", "203.0.113.7").unwrap(),
host: host.to_owned(),
port: 3389,
key: None,
known_hosts: None,
}
}
#[test]
fn the_forward_listens_on_the_loopback_and_checks_the_pinned_keys() {
use crate::process::fake::CallView as _;
let dir = tempfile::tempdir().unwrap();
let spec = ssh_spec(Purpose::Console("dc"), &to("10.9.0.20"), Path::new("/k/id"), dir.path(), 40000).unwrap();
assert_eq!(spec.flag("-L"), Some("127.0.0.1:40000:10.9.0.20:3389"), "{:?}", spec.args);
for never_waits in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ConnectTimeout=10"] {
assert!(spec.has_run(&["-o", never_waits]), "{never_waits}: {:?}", spec.args);
}
assert!(!spec.args.iter().any(|a| a.ends_with("=accept-new")), "{:?}", spec.args);
assert_eq!((spec.flag("-F"), spec.flag("-i")), (Some("none"), Some("/k/id")), "{:?}", spec.args);
assert_eq!(spec.args.last().map(String::as_str), Some("admin@203.0.113.7"));
let refused = ssh_spec(Purpose::Console("dc"), &to("-oProxyCommand=x"), Path::new("/k"), dir.path(), 1).unwrap_err();
assert_eq!(refused.code(), crate::ErrorCode::NoConsole, "an option, never an address: {refused}");
}
#[test]
fn an_ipv6_host_is_bracketed_in_the_forward() {
assert_eq!(bracketed("fd00::5"), "[fd00::5]");
assert_eq!(bracketed("10.0.1.5"), "10.0.1.5");
}
#[test]
fn a_missing_ssh_is_a_tool_missing() {
let dir = tempfile::tempdir().unwrap();
let spec = ProcessSpec::new("isothrum-no-such-ssh", ["-N"]);
let err = started(Purpose::Console("dc"), &spec, "127.0.0.1:1".parse().unwrap(), "a@b", dir.path()).unwrap_err();
assert_eq!(err.code(), crate::ErrorCode::ToolMissing, "{err}");
}
#[cfg(unix)]
fn stand_in(script: &str, dir: &Path) -> Tunnel {
let spec = ProcessSpec::new("sh", ["-c", script]);
start(&spec, "127.0.0.1:1".parse().unwrap(), "admin@203.0.113.7", dir).unwrap()
}
#[cfg(unix)]
#[tokio::test]
async fn a_tunnel_that_closed_says_the_last_line_its_ssh_said() {
let dir = tempfile::tempdir().unwrap();
let mut refused = stand_in("echo 'debug1: x' >&2; echo 'Host key verification failed.' >&2; exit 255", dir.path());
assert_eq!(refused.why_closed().await.as_deref(), Some("Host key verification failed."));
assert_eq!(stand_in("exit 255", dir.path()).why_closed().await, None, "nothing said, nothing made up");
}
#[cfg(unix)]
#[tokio::test]
async fn a_tunnel_says_when_its_ssh_ended() {
let dir = tempfile::tempdir().unwrap();
let mut tunnel = stand_in("exit 255", dir.path());
tunnel.drain();
let said = tokio::time::timeout(Duration::from_secs(10), tunnel.closed()).await.expect("seen closing");
assert_eq!(said, "its ssh exited with code 255");
}
#[cfg(unix)]
#[tokio::test]
async fn a_tunnel_is_waited_for_while_its_ssh_opens_it_and_given_up_once_it_ended() {
let dir = tempfile::tempdir().unwrap();
let mut opening = stand_in("sleep 30", dir.path());
let probes = std::sync::atomic::AtomicUsize::new(0);
let third = || -> crate::BoxFuture<'_, bool> {
let n = probes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Box::pin(async move { n >= 2 })
};
assert!(answers(&mut opening, third, Duration::from_secs(10)).await, "answering at the third probe");
let mut ended = stand_in("exit 255", dir.path());
tokio::time::sleep(Duration::from_millis(300)).await;
let never = || -> crate::BoxFuture<'_, bool> { Box::pin(async { false }) };
let started = std::time::Instant::now();
assert!(!answers(&mut ended, never, Duration::from_secs(10)).await);
assert!(started.elapsed() < Duration::from_secs(5), "given up once its ssh ended");
}
}