use std::collections::VecDeque;
use std::ffi::OsString;
use std::io::{ErrorKind, Read};
use std::net::Shutdown;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use super::Entry;
use crate::serve::endpoint::Stream;
pub(super) const STDERR_TAIL: usize = 4096;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
pub host: String,
pub port: Option<u16>,
}
pub fn parse_target(target: &str) -> Result<Target> {
if target.is_empty() {
bail!("empty ssh target");
}
if target.chars().any(|c| c.is_whitespace() || c.is_control()) {
bail!("ssh target `{}` has whitespace or control characters", target.escape_debug());
}
let Some(rest) = target.strip_prefix("ssh://") else {
if target.starts_with('-') {
bail!("ssh target `{target}` starts with `-`");
}
return Ok(Target { host: target.into(), port: None });
};
let rest = rest.strip_suffix('/').unwrap_or(rest);
if rest.contains('/') {
bail!("ssh target `{target}`: a URL takes no path");
}
let (user, hostport) = match rest.rsplit_once('@') {
Some((user, hostport)) if !user.is_empty() => (Some(user), hostport),
Some(_) => bail!("ssh target `{target}`: empty user"),
None => (None, rest),
};
let (host, port) = if let Some(v6) = hostport.strip_prefix('[') {
let (host, after) = v6.split_once(']').with_context(|| format!("ssh target `{target}`: unclosed `[`"))?;
match after {
"" => (host, None),
_ => (host, Some(after.strip_prefix(':').with_context(|| format!("ssh target `{target}`: junk after `]`"))?)),
}
} else {
match hostport.split_once(':') {
Some((host, port)) => (host, Some(port)),
None => (hostport, None),
}
};
if host.is_empty() {
bail!("ssh target `{target}`: empty host");
}
let port = match port {
None => None,
Some(p) => match p.parse::<u16>() {
Ok(n) if n > 0 => Some(n),
_ => bail!("ssh target `{target}`: bad port `{p}`"),
},
};
let host = match user {
Some(user) => format!("{user}@{host}"),
None => host.to_string(),
};
if host.starts_with('-') {
bail!("ssh target `{target}` starts with `-`");
}
Ok(Target { host, port })
}
pub fn quote(word: &str) -> String {
format!("'{}'", word.replace('\'', r"'\''"))
}
pub fn remote_command(command: &str, args: &[impl AsRef<str>]) -> String {
let mut cmd = format!("exec {command}");
for arg in args {
cmd.push(' ');
cmd.push_str("e(arg.as_ref()));
}
format!("exec \"$SHELL\" -lc {}", quote(&cmd))
}
pub fn probe_argv(entry: &Entry, client: &str) -> Result<Vec<OsString>> {
argv(entry, &["-T", "-o", "BatchMode=yes"], &["api", "--stdio", "--client", client, "--sentinel"])
}
pub fn add_cli_argv(entry: &Entry, remote_args: &[impl AsRef<str>]) -> Result<Vec<OsString>> {
argv(entry, &["-T"], remote_args)
}
pub fn script_argv(entry: &Entry, script: &str, args: &[impl AsRef<str>]) -> Result<Vec<OsString>> {
let mut remote_args = vec!["-c", script, "sh"];
remote_args.extend(args.iter().map(AsRef::as_ref));
argv_with(entry, &["-T"], "sh", &remote_args)
}
fn argv(entry: &Entry, opts: &[&str], remote_args: &[impl AsRef<str>]) -> Result<Vec<OsString>> {
argv_with(entry, opts, entry.command(), remote_args)
}
fn argv_with(entry: &Entry, opts: &[&str], program: &str, remote_args: &[impl AsRef<str>]) -> Result<Vec<OsString>> {
target_argv(entry.ssh_target()?, opts, program, remote_args)
}
pub(crate) fn target_argv(target: &str, opts: &[&str], program: &str, remote_args: &[impl AsRef<str>]) -> Result<Vec<OsString>> {
let target = parse_target(target)?;
let mut argv: Vec<OsString> = ["ssh"].iter().chain(opts).map(OsString::from).collect();
if let Some(port) = target.port {
argv.extend(["-p".into(), port.to_string().into()]);
}
argv.extend(["--".into(), target.host.into(), remote_command(program, remote_args).into()]);
Ok(argv)
}
pub type Dial = Arc<dyn Fn(&Entry) -> Result<Duplex> + Send + Sync>;
pub type RouteDial = Arc<dyn Fn(&str) -> Result<Duplex> + Send + Sync>;
pub fn probe_dial(client: String) -> Dial {
Arc::new(move |entry: &Entry| spawn(&probe_argv(entry, &client)?))
}
pub struct Duplex {
pub stream: Stream,
pub peer: Peer,
}
impl Duplex {
pub fn socket(stream: Stream) -> Self {
Self { stream, peer: Peer::default() }
}
}
#[derive(Default)]
pub struct Peer {
child: Option<Child>,
stderr: Option<Arc<Tail>>,
}
impl Peer {
pub fn close(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
pub fn stderr_tail(&self, wait: Duration) -> String {
self.stderr.as_ref().map(|t| t.read(wait)).unwrap_or_default()
}
}
impl Drop for Peer {
fn drop(&mut self) {
self.close();
}
}
#[derive(Default)]
pub struct Tail {
state: Mutex<(VecDeque<u8>, bool)>,
eof: Condvar,
}
impl Tail {
pub fn collect(mut stream: impl Read + Send + 'static, name: &str) -> std::io::Result<Arc<Tail>> {
let tail = Arc::new(Tail::default());
let filled = Arc::clone(&tail);
std::thread::Builder::new().name(name.into()).spawn(move || {
let mut buf = [0u8; 1024];
loop {
match stream.read(&mut buf) {
Ok(0) => break,
Ok(n) => filled.push(&buf[..n]),
Err(e) if e.kind() == ErrorKind::Interrupted => {}
Err(_) => break,
}
}
filled.finish();
})?;
Ok(tail)
}
fn push(&self, bytes: &[u8]) {
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
state.0.extend(bytes);
let over = state.0.len().saturating_sub(STDERR_TAIL);
state.0.drain(..over);
}
fn finish(&self) {
self.state.lock().unwrap_or_else(|e| e.into_inner()).1 = true;
self.eof.notify_all();
}
pub fn read(&self, wait: Duration) -> String {
let deadline = Instant::now() + wait;
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
while !state.1 {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
break;
}
state = self.eof.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner()).0;
}
String::from_utf8_lossy(state.0.make_contiguous()).trim().to_string()
}
}
pub fn spawn(argv: &[OsString]) -> Result<Duplex> {
let (program, args) = argv.split_first().context("empty ssh argv")?;
let mut cmd = Command::new(program);
cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().with_context(|| format!("cannot run {}", program.to_string_lossy()))?;
let peer_of = |child| Peer { child: Some(child), stderr: None };
let (Some(mut stdin), Some(mut stdout), Some(stderr)) = (child.stdin.take(), child.stdout.take(), child.stderr.take())
else {
drop(peer_of(child));
bail!("ssh's pipes are missing");
};
let mut peer = peer_of(child);
let (ours, theirs) = Stream::pair().context("cannot make a socket pair")?;
let up = theirs.try_clone().context("cannot clone the socket pair")?;
peer.stderr = Some(Tail::collect(stderr, "machine-ssh-stderr").context("cannot start the ssh pumps")?);
let threads = [
std::thread::Builder::new().name("machine-ssh-down".into()).spawn(move || {
pipe(&mut stdout, &mut &theirs);
let _ = theirs.shutdown(Shutdown::Write);
}),
std::thread::Builder::new().name("machine-ssh-up".into()).spawn(move || {
pipe(&mut &up, &mut stdin);
}),
];
for t in threads {
t.context("cannot start the ssh pumps")?;
}
Ok(Duplex { stream: ours, peer })
}
fn pipe(from: &mut impl Read, to: &mut impl std::io::Write) {
let mut buf = [0u8; 64 * 1024];
loop {
let n = match from.read(&mut buf) {
Ok(0) => return,
Ok(n) => n,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(_) => return,
};
if to.write_all(&buf[..n]).and_then(|()| to.flush()).is_err() {
return;
}
}
}
const NOISE_CHARS: usize = 200;
#[derive(Debug)]
pub enum SkipError<E> {
Eof,
TooLong,
Io(std::io::Error),
Refused(E),
}
pub fn skip_lines<T, E>(
r: &mut impl Read,
limit: usize,
noise: &mut Option<String>,
mut matcher: impl FnMut(&[u8]) -> Result<Option<T>, E>,
) -> Result<T, SkipError<E>> {
let mut line = Vec::new();
let mut total = 0;
let mut byte = [0u8; 1];
let keep = |noise: &mut Option<String>, line: &[u8]| {
let text = String::from_utf8_lossy(line);
let text = text.trim();
if noise.is_none() && !text.is_empty() {
*noise = Some(text.chars().take(NOISE_CHARS).collect());
}
};
loop {
match r.read(&mut byte) {
Ok(0) => {
keep(noise, &line);
return Err(SkipError::Eof);
}
Ok(_) => {}
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => {
keep(noise, &line);
return Err(SkipError::Io(e));
}
}
total += 1;
if total > limit {
keep(noise, &line);
return Err(SkipError::TooLong);
}
if byte[0] != b'\n' {
line.push(byte[0]);
continue;
}
if let Some(found) = matcher(&line).map_err(SkipError::Refused)? {
return Ok(found);
}
keep(noise, &line);
line.clear();
}
}
#[cfg(test)]
pub(crate) mod test_support {
use super::*;
pub fn with_stderr(stream: Stream, stderr: impl Read + Send + 'static) -> Result<Duplex> {
Ok(Duplex { stream, peer: Peer { child: None, stderr: Some(Tail::collect(stderr, "test-ssh-stderr")?) } })
}
pub fn relayed(daemon: Stream) -> Result<Duplex> {
let (ours, theirs) = Stream::pair()?;
crate::serve::relay::write_sentinel(&mut &theirs)?;
let (theirs_up, daemon_down) = (theirs.try_clone()?, daemon.try_clone()?);
std::thread::spawn(move || {
pipe(&mut &theirs_up, &mut &daemon);
let _ = daemon.shutdown(Shutdown::Write);
});
std::thread::spawn(move || {
pipe(&mut &daemon_down, &mut &theirs);
let _ = theirs.shutdown(Shutdown::Write);
});
Ok(Duplex::socket(ours))
}
}
#[cfg(test)]
mod tests {
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use super::*;
fn entry(target: &str, command: Option<&str>) -> Entry {
Entry { command: command.map(Into::into), ..Entry::ssh("m", target) }
}
#[test]
fn every_argv_refuses_an_inbound_machine() {
let e = Entry::inbound("lap", Vec::new());
let refusals = [probe_argv(&e, "c"), add_cli_argv(&e, &["ps"]), script_argv(&e, "true", &[] as &[&str])];
for r in refusals {
let err = format!("{:#}", r.unwrap_err());
assert!(err.contains("machine `lap` links to this host from its end") && err.contains("not ssh"), "{err}");
}
}
fn strs(argv: &[OsString]) -> Vec<&str> {
argv.iter().map(|a| a.to_str().unwrap()).collect()
}
#[test]
fn targets_parse_urls_and_pass_the_rest_through() {
let t = |host: &str, port| Target { host: host.into(), port };
assert_eq!(parse_target("me@host").unwrap(), t("me@host", None));
assert_eq!(parse_target("my-alias").unwrap(), t("my-alias", None));
assert_eq!(parse_target("ssh://me@host:2222").unwrap(), t("me@host", Some(2222)));
assert_eq!(parse_target("ssh://host").unwrap(), t("host", None));
assert_eq!(parse_target("ssh://host/").unwrap(), t("host", None));
assert_eq!(parse_target("ssh://me@[::1]:22").unwrap(), t("me@::1", Some(22)));
assert_eq!(parse_target("ssh://[fe80::1]").unwrap(), t("fe80::1", None));
assert_eq!(parse_target("me@host:22").unwrap(), t("me@host:22", None));
for bad in ["", " ", "me@ho st", "host\n", "-oProxyCommand=x", "ssh://", "ssh://-o@x", "ssh://host:0", "ssh://host:x",
"ssh://host:99999", "ssh://@host", "ssh://host/path", "ssh://[::1", "ssh://[::1]x", "ssh://me@:22"]
{
assert!(parse_target(bad).is_err(), "{bad:?} parsed");
}
let err = parse_target("ssh://-oProxyCommand=x").unwrap_err();
assert!(format!("{err:#}").contains("starts with `-`"), "{err:#}");
}
#[test]
fn quoting_is_posix_single_quotes() {
assert_eq!(quote("plain"), "'plain'");
assert_eq!(quote(""), "''");
assert_eq!(quote("it's"), r"'it'\''s'");
assert_eq!(remote_command("devsandbox", &["ps"]), r#"exec "$SHELL" -lc 'exec devsandbox '\''ps'\'''"#);
}
#[test]
fn add_time_argvs() {
let probe = probe_argv(&entry("ssh://me@box:2200", None), "machine:laptop").unwrap();
let remote = remote_command("devsandbox", &["api", "--stdio", "--client", "machine:laptop", "--sentinel"]);
assert_eq!(strs(&probe), ["ssh", "-T", "-o", "BatchMode=yes", "-p", "2200", "--", "me@box", remote.as_str()]);
let e = entry("box", Some("~/bin/devsandbox"));
let cli = add_cli_argv(&e, &["machine", "roots", "add", "/srv/it's here"]).unwrap();
let remote = remote_command("~/bin/devsandbox", &["machine", "roots", "add", "/srv/it's here"]);
assert_eq!(strs(&cli), ["ssh", "-T", "--", "box", remote.as_str()]);
assert!(remote.contains("~/bin/devsandbox"), "the command is shell text: {remote}");
let script = script_argv(&entry("ssh://box:2200", Some("~/bin/devsandbox")), "echo \"$1\"", &["it's"]).unwrap();
let remote = remote_command("sh", &["-c", "echo \"$1\"", "sh", "it's"]);
assert_eq!(strs(&script), ["ssh", "-T", "-p", "2200", "--", "box", remote.as_str()]);
assert!(!strs(&script).contains(&"BatchMode=yes"), "a person is there");
for argv in [&probe, &cli, &script] {
assert!(!strs(argv).contains(&"-A"), "{argv:?}");
}
assert!(probe_argv(&entry("-oProxyCommand=x", None), "c").is_err());
}
fn echo_args(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("dsv-ssh-{tag}-{}", std::process::id())).join("it's here");
std::fs::create_dir_all(&dir).unwrap();
let script = dir.join("echo-args");
std::fs::write(&script, "#!/bin/sh\nfor a in \"$@\"; do printf '[%s]\\n' \"$a\"; done\n").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
script
}
#[test]
fn remote_commands_survive_both_shells() {
let script = echo_args("quote");
let home = script.parent().unwrap();
let args = ["plain", "two words", "it's", r#"say "hi""#, "$HOME", "`id`", "a\\b", "", "-l", "*"];
let remote = remote_command("e(script.to_str().unwrap()), &args);
let out = Command::new("/bin/sh")
.arg("-c")
.arg(&remote)
.env_clear()
.env("SHELL", "/bin/sh")
.env("HOME", home)
.env("PATH", "/usr/bin:/bin")
.current_dir(home)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let want: String = args.iter().map(|a| format!("[{a}]\n")).collect();
assert_eq!(String::from_utf8_lossy(&out.stdout), want);
let _ = std::fs::remove_dir_all(home.parent().unwrap());
}
#[test]
fn scripts_survive_both_shells() {
let home = std::env::temp_dir().join(format!("dsv-ssh-script-{}", std::process::id()));
std::fs::create_dir_all(&home).unwrap();
let script = r#"printf '<%s>' "$0"; for a in "$@"; do printf '[%s]' "$a"; done"#;
let args = ["plain", "two words", "it's", "$HOME", "`id`", "", "-l"];
let argv = script_argv(&entry("box", None), script, &args).unwrap();
let out = Command::new("/bin/sh")
.arg("-c")
.arg(argv.last().unwrap())
.env_clear()
.env("SHELL", "/bin/sh")
.env("HOME", &home)
.env("PATH", "/usr/bin:/bin")
.current_dir(&home)
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let want: String = std::iter::once("<sh>".to_string()).chain(args.iter().map(|a| format!("[{a}]"))).collect();
assert_eq!(String::from_utf8_lossy(&out.stdout), want);
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn spawned_pipes_reach_the_socket_and_stderr_is_kept() {
let argv: Vec<OsString> = ["sh", "-c", "echo to-stderr >&2; read l; echo \"got $l\"; exec cat"]
.into_iter()
.map(Into::into)
.collect();
let mut duplex = spawn(&argv).unwrap();
duplex.stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
let mut reader = BufReader::new(duplex.stream.try_clone().unwrap());
duplex.stream.write_all(b"one\ntwo\n").unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(line, "got one\n");
line.clear();
reader.read_line(&mut line).unwrap();
assert_eq!(line, "two\n");
duplex.stream.shutdown(Shutdown::Write).unwrap();
line.clear();
assert_eq!(reader.read_line(&mut line).unwrap(), 0);
assert_eq!(duplex.peer.stderr_tail(Duration::from_secs(5)), "to-stderr");
duplex.peer.close();
duplex.peer.close();
}
#[test]
fn the_stderr_tail_is_bounded_and_close_kills() {
let argv: Vec<OsString> =
["sh", "-c", "i=0; while [ $i -lt 600 ]; do echo line-$i >&2; i=$((i+1)); done; exec sleep 60"]
.into_iter()
.map(Into::into)
.collect();
let mut duplex = spawn(&argv).unwrap();
let started = Instant::now();
let deadline = Instant::now() + Duration::from_secs(5);
while !duplex.peer.stderr_tail(Duration::ZERO).ends_with("line-599") && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
let tail = duplex.peer.stderr_tail(Duration::from_millis(50));
assert!(tail.len() <= STDERR_TAIL && tail.ends_with("line-599") && !tail.contains("line-0\n"), "{tail}");
duplex.peer.close();
assert!(started.elapsed() < Duration::from_secs(30), "close didn't kill");
let mut rest = Vec::new();
duplex.stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
assert_eq!(duplex.stream.read_to_end(&mut rest).unwrap(), 0, "the socket sees the child's end");
}
#[test]
fn a_missing_program_is_an_error() {
let err = spawn(&["/nonexistent/ssh".into()]).err().unwrap();
assert!(format!("{err:#}").contains("cannot run /nonexistent/ssh"), "{err:#}");
assert!(spawn(&[]).is_err());
}
}