use std::path::PathBuf;
use std::time::Duration;
use super::Module;
use super::route::{JUMP_KNOWN_HOSTS_VAR, JUMP_VAR};
use crate::Result;
use crate::error::Error;
use crate::events::Stream;
use crate::process::ProcessSpec;
use crate::ssh::Login;
pub(crate) const KEY_VAR: &str = "ssh_jump_key_file";
pub(crate) const PROXY_HOST_VAR: &str = "TF_VAR_ssh_proxy_host";
pub(crate) const PROXY_PORT_VAR: &str = "TF_VAR_ssh_proxy_port";
const LOOPBACK: &str = "127.0.0.1";
const OPENING: Duration = Duration::from_secs(30);
const POLL: Duration = Duration::from_millis(200);
const STEP: &str = "jump";
fn jump(module: &Module<'_, '_>) -> Result<Option<(Login, PathBuf, Option<PathBuf>)>> {
let cx = module.cx;
let Some(jump) = cx.var(JUMP_VAR) else { return Ok(None) };
let refused = |why: String| Error::ToolFailed {
step: STEP.to_owned(),
reason: why,
};
let (user, host) = jump
.split_once('@')
.ok_or_else(|| refused(format!("the run's `{JUMP_VAR}` value `{}` isn't `user@host`", jump.escape_debug())))?;
let login = Login::new(user, host).ok_or_else(|| refused(format!("the run's `{JUMP_VAR}` value `{}` isn't an SSH login", jump.escape_debug())))?;
let key = cx
.var(KEY_VAR)
.or_else(|| cx.var(super::tunnelled::KEY_VAR))
.map_or_else(|| cx.ssh_key.to_path_buf(), PathBuf::from);
Ok(Some((login, key, cx.var(JUMP_KNOWN_HOSTS_VAR).map(PathBuf::from))))
}
fn proxy_spec(module: &Module<'_, '_>, login: &Login, key: &std::path::Path, first: crate::ssh::First<'_>, port: u16) -> Result<ProcessSpec> {
let mut args = crate::ssh::options(key, module.cx.state_dir, first)?;
args.extend([
"-N".to_owned(),
"-o".to_owned(),
"ExitOnForwardFailure=yes".to_owned(),
"-D".to_owned(),
format!("{LOOPBACK}:{port}"),
]);
args.push(login.target());
let mut spec = ProcessSpec::new("ssh", args);
spec.cwd = Some(module.cx.state_dir.to_path_buf());
Ok(spec)
}
fn free_port() -> Result<u16> {
let taken = std::net::TcpListener::bind((LOOPBACK, 0)).map_err(Error::io("a tcp port on 127.0.0.1", "bound"))?;
Ok(taken.local_addr().map_err(Error::io("a tcp port on 127.0.0.1", "read"))?.port())
}
pub(super) async fn through<T>(module: &Module<'_, '_>, op: impl AsyncFnOnce(&Module<'_, '_>) -> Result<T>) -> Result<T> {
let Some((login, key, known_hosts)) = jump(module)? else {
return op(module).await;
};
let cx = module.cx;
let first = crate::ssh::First::given(known_hosts.as_deref());
crate::ssh::ready(cx.processes, cx.state_dir, &login.host, first).await?;
let port = free_port()?;
let spec = proxy_spec(module, &login, &key, first, port)?;
let said = std::sync::Mutex::new(String::new());
let mut keep = |stream: Stream, line: &str| {
if stream == Stream::Stderr && !line.trim().is_empty() {
line.trim().clone_into(&mut said.lock().unwrap_or_else(std::sync::PoisonError::into_inner));
}
};
let ssh = cx.processes.run(&spec, &mut keep);
tokio::pin!(ssh);
let ended = |how: String| {
let last = said.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
let because = if last.is_empty() { String::new() } else { format!(": ssh said `{last}`") };
Error::ToolFailed {
step: STEP.to_owned(),
reason: format!("the SSH proxy through {} {how}{because}", login.target()),
}
};
let deadline = tokio::time::Instant::now() + OPENING;
loop {
if tokio::net::TcpStream::connect((LOOPBACK, port)).await.is_ok() {
break;
}
if tokio::time::Instant::now() >= deadline {
return Err(ended(format!("didn't open within {}s", OPENING.as_secs())));
}
tokio::select! {
exit = &mut ssh => return Err(ended(exit.map_or_else(|e| e.to_string(), |exit| format!("ended ({exit})")))),
() = tokio::time::sleep(POLL) => {}
}
}
let proxied = module.with_env(&[(PROXY_HOST_VAR, LOOPBACK.to_owned()), (PROXY_PORT_VAR, port.to_string())]);
tokio::select! {
done = op(&proxied) => done,
exit = &mut ssh => Err(ended(exit.map_or_else(|e| e.to_string(), |exit| format!("ended during the step ({exit})")))),
}
}