use std::net::SocketAddr;
use std::time::Duration;
use isoloom_manifest::{Machine, Protocol};
use super::{LOOPBACK, none};
use crate::Result;
use crate::error::Error;
use crate::executor::Cx;
use crate::process::ProcessSpec;
const OPENING: Duration = Duration::from_secs(20);
const STEP: &str = "console";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct To {
pub(super) via: String,
pub(super) user: String,
pub(super) host: String,
pub(super) port: u16,
}
#[derive(Debug)]
pub(crate) struct Tunnel {
pub(super) local: SocketAddr,
ssh: tokio::process::Child,
}
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");
}
}
}
pub(super) fn spec(cx: &Cx<'_>, to: &To, local: u16) -> Result<ProcessSpec> {
let login = crate::ssh::Login::new(&to.user, &to.via, cx.ssh_jump.as_deref(), "")?;
if !to.host.chars().all(|c| c.is_ascii_alphanumeric() || ".:-".contains(c)) || to.host.is_empty() {
return Err(Error::Malformed {
at: "a console's tunnel".to_owned(),
reason: format!("`{}` isn't an address", to.host),
});
}
let forward = format!("{LOOPBACK}:{local}:{}:{}", bracketed(&to.host), to.port);
let mut spec = crate::ssh::spec(cx, &login, "", Vec::new())?;
spec.args.pop();
let target = spec.args.pop().unwrap_or_default();
spec.args.extend(["-N", "-o", "ExitOnForwardFailure=yes", "-L", &forward].map(String::from));
spec.args.push(target);
Ok(spec)
}
fn bracketed(host: &str) -> String {
if host.contains(':') { format!("[{host}]") } else { host.to_owned() }
}
pub(super) async fn open(cx: &Cx<'_>, machine: &Machine, to: &To) -> Result<Tunnel> {
let free = cx
.run
.runner
.pick_unreserved(cx.run.name(), Protocol::Tcp)
.map_err(Error::io("a tcp port on 127.0.0.1", "bound"))?
.ok_or_else(|| none(machine, "no free port on this computer's loopback for its tunnel"))?;
let local = free.port;
drop(free);
let mut tunnel = started(machine, &spec(cx, to, local)?, SocketAddr::new(LOOPBACK, local))?;
if !cx.run.runner.config.ports.reachable(&LOOPBACK.to_string(), local, OPENING).await {
let said = tunnel.why_closed().await;
let because = said.map_or_else(String::new, |line| format!(": ssh said `{}`", cx.events.mask(&line)));
return Err(none(
machine,
format!(
"its tunnel through {} didn't open (SSH refused or {}:{} doesn't answer){because}",
to.via, to.host, to.port
),
));
}
tunnel.drain();
Ok(tunnel)
}
fn started(machine: &Machine, spec: &ProcessSpec, local: SocketAddr) -> Result<Tunnel> {
start(spec, local).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => Error::ToolMissing {
step: STEP.to_owned(),
tool: spec.program.clone(),
},
_ => none(machine, format!("its tunnel's `{}` didn't start: {e}", spec.program)),
})
}
pub(super) fn start(spec: &ProcessSpec, local: SocketAddr) -> 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);
}
Ok(Tunnel { local, ssh: command.spawn()? })
}
impl Tunnel {
async fn why_closed(&mut self) -> Option<String> {
use tokio::io::AsyncReadExt;
if tokio::time::timeout(Duration::from_secs(2), 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(Duration::from_secs(2), 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 };
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");
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn a_missing_ssh_is_a_tool_missing() {
let web: Machine = serde_json::from_value(serde_json::json!({ "name": "web", "role": "member", "addresses": {} })).unwrap();
let spec = ProcessSpec::new("isothrum-no-such-ssh", ["-N"]);
let err = started(&web, &spec, "127.0.0.1:1".parse().unwrap()).unwrap_err();
assert_eq!(err.code(), crate::ErrorCode::ToolMissing, "{err}");
assert!(err.to_string().contains("isothrum-no-such-ssh"), "{err}");
}
#[cfg(unix)]
#[tokio::test]
async fn a_tunnel_that_closed_says_what_ssh_said() {
let spec = ProcessSpec::new("sh", ["-c", "echo 'debug1: x' >&2; echo 'Host key verification failed.' >&2; exit 255"]);
let mut tunnel = start(&spec, "127.0.0.1:1".parse().unwrap()).unwrap();
assert_eq!(tunnel.why_closed().await.as_deref(), Some("Host key verification failed."));
let quiet = ProcessSpec::new("sh", ["-c", "exit 255"]);
assert_eq!(start(&quiet, "127.0.0.1:1".parse().unwrap()).unwrap().why_closed().await, None);
}
#[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");
}
#[cfg(unix)]
#[tokio::test]
async fn a_tunnel_stops_its_process_when_dropped() {
let dir = tempfile::tempdir().unwrap();
let mark = dir.path().join("alive");
let script = format!("touch {}; sleep 30", mark.display());
let spec = ProcessSpec::new("sh", ["-c", script.as_str()]);
let tunnel = start(&spec, "127.0.0.1:1".parse().unwrap()).unwrap();
let pid = tunnel.ssh.id().unwrap();
for _ in 0..100 {
if mark.exists() {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert!(mark.exists(), "the process ran");
drop(tunnel);
tokio::time::sleep(Duration::from_millis(200)).await;
let ps = std::process::Command::new("ps").args(["-o", "stat=", "-p", &pid.to_string()]).output().unwrap();
let stat = String::from_utf8_lossy(&ps.stdout).trim().to_owned();
assert!(stat.is_empty() || stat.starts_with('Z'), "the process went with the tunnel: {stat}");
}
}