//! com.fedfork.exec.ssh.exec: one command over ssh -> { exit, stdout, stderr }; com.fedfork.exec.ssh.session: a //! subscription, each output line a message { stream, line }, then { exit }; a send { data } writes stdin; closing it //! disconnects. Input { dest, command, env?, stdin?, stdinFile? }: dest and stdinFile are names the host configured //! (`Dest`, `stdin_files`), never a key or a path from the module. use std::collections::HashMap; use std::path::PathBuf; use std::process::Stdio; use std::sync::Arc; use atlibs_host::BoxFut; use atlibs_host::run::{Call, Request, Sub, SubCmd}; use atlibs_host::transport::Transport; use serde::Deserialize; use serde_json::{Value, json}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::sync::mpsc; pub const EXEC: &str = "com.fedfork.exec.ssh.exec"; pub const SESSION: &str = "com.fedfork.exec.ssh.session"; pub const NSIDS: &[&str] = &[EXEC, SESSION]; const OUT_MAX: usize = 1 << 20; /// An ssh destination: `user@host` (or an alias), its port, the private key, known hosts (accept-new into it when /// none is pinned yet). `-F /dev/null` always: no user config changes what runs. #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Dest { pub dest: String, #[serde(default)] pub port: Option, #[serde(default)] pub key: Option, #[serde(default)] pub known_hosts: Option, /// use ~/.ssh/config (an alias such as hat-7) instead of -F /dev/null #[serde(default)] pub user_config: bool, } pub struct Ssh { dests: std::sync::Mutex>, stdin_files: std::sync::Mutex>, } fn env_ok(k: &str, v: &str) -> bool { !k.is_empty() && k.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') && !v.contains(['\n', '\r', '\0', ' ']) } impl Ssh { pub fn new(dests: HashMap, stdin_files: HashMap) -> Arc { Arc::new(Self { dests: dests.into(), stdin_files: stdin_files.into() }) } /// A destination the host learned during the run (a key it registered for it). pub fn add_dest(&self, name: &str, d: Dest) { self.dests.lock().unwrap().insert(name.into(), d); } pub fn add_stdin_file(&self, name: &str, path: PathBuf) { self.stdin_files.lock().unwrap().insert(name.into(), path); } pub fn transport(self: &Arc) -> Transport { Transport { provides: NSIDS, call: self.clone() } } fn command(&self, input: &Value) -> Result<(tokio::process::Command, Stdin), String> { let name = input["dest"].as_str().ok_or("dest is required")?; let d = self.dests.lock().unwrap().get(name).cloned().ok_or_else(|| format!("no ssh dest {name} on this host"))?; let remote = input["command"].as_str().ok_or("command is required")?; let mut c = tokio::process::Command::new("ssh"); if !d.user_config { c.args(["-F", "/dev/null"]); } c.args(["-o", "BatchMode=yes"]); if let Some(p) = d.port { c.args(["-p", &p.to_string()]); } if let Some(k) = &d.key { c.arg("-i").arg(k).args(["-o", "IdentitiesOnly=yes"]); } if let Some(kh) = &d.known_hosts { c.args(["-o", "StrictHostKeyChecking=accept-new"]).arg("-o").arg(format!("UserKnownHostsFile={}", kh.display())); } for (k, v) in input["env"].as_object().into_iter().flatten() { let v = v.as_str().unwrap_or_default(); if !env_ok(k, v) { return Err(format!("env {k}: an upper-case name and a value without spaces")); } c.arg("-o").arg(format!("SetEnv={k}={v}")); } c.arg(&d.dest).arg(remote).kill_on_drop(true); let stdin = match (input["stdin"].as_str(), input["stdinFile"].as_str()) { (Some(text), _) => Stdin::Text(text.into()), (None, Some(f)) => Stdin::File(self.stdin_files.lock().unwrap().get(f).cloned().ok_or_else(|| format!("no stdin file {f} on this host"))?), (None, None) => Stdin::None, }; Ok((c, stdin)) } } enum Stdin { None, Text(String), File(PathBuf), } fn input_of(request: &Request) -> Value { request.input.clone().unwrap_or_else(|| Value::Object(request.params.clone().unwrap_or_default())) } impl Call for Ssh { fn call(&self, nsid: String, request: Request) -> BoxFut<'_, Result, String>> { Box::pin(async move { if nsid != EXEC { return Err(format!("{nsid} is a subscription or not ssh")); } let (mut c, stdin) = self.command(&input_of(&request))?; c.stdout(Stdio::piped()).stderr(Stdio::piped()); match &stdin { Stdin::File(p) => { c.stdin(std::fs::File::open(p).map_err(|e| format!("stdin file: {e}"))?); } Stdin::Text(_) => { c.stdin(Stdio::piped()); } Stdin::None => { c.stdin(Stdio::null()); } } let mut child = c.spawn().map_err(|e| format!("ssh: {e}"))?; if let (Stdin::Text(t), Some(mut w)) = (stdin, child.stdin.take()) { w.write_all(t.as_bytes()).await.map_err(|e| e.to_string())?; } let out = child.wait_with_output().await.map_err(|e| e.to_string())?; let cut = |b: &[u8]| String::from_utf8_lossy(&b[..b.len().min(OUT_MAX)]).to_string(); Ok(Some(json!({ "exit": out.status.code(), "stdout": cut(&out.stdout), "stderr": cut(&out.stderr) }))) }) } fn subscribe(&self, nsid: String, request: Request) -> BoxFut<'_, Result> { Box::pin(async move { if nsid != SESSION { return Err(format!("{nsid} is not a subscription")); } let (mut c, stdin) = self.command(&input_of(&request))?; c.stdout(Stdio::piped()).stderr(Stdio::piped()); if let Stdin::File(p) = &stdin { c.stdin(std::fs::File::open(p).map_err(|e| format!("stdin file: {e}"))?); } else { c.stdin(Stdio::piped()); } let mut child = c.spawn().map_err(|e| format!("ssh: {e}"))?; let mut w = child.stdin.take(); if let (Stdin::Text(t), Some(w)) = (&stdin, w.as_mut()) { w.write_all(t.as_bytes()).await.map_err(|e| e.to_string())?; } let (tx, messages) = mpsc::unbounded_channel(); let (commands, mut cmds) = mpsc::unbounded_channel(); for (stream, pipe) in [("stdout", child.stdout.take().map(|p| Box::new(p) as Box)), ("stderr", child.stderr.take().map(|p| Box::new(p) as _))] { let (tx, Some(pipe)) = (tx.clone(), pipe) else { continue }; tokio::spawn(async move { let mut lines = BufReader::new(pipe).lines(); while let Ok(Some(line)) = lines.next_line().await { if tx.send(Ok(json!({ "stream": stream, "line": line }))).is_err() { break; } } }); } tokio::spawn(async move { loop { tokio::select! { st = child.wait() => { let _ = tx.send(Ok(json!({ "exit": st.ok().and_then(|s| s.code()) }))); break; } cmd = cmds.recv() => match cmd { Some(SubCmd::Send(data, reply)) => { let text = data["data"].as_str().map(String::from).unwrap_or_default(); let r = match w.as_mut() { Some(w) => w.write_all(text.as_bytes()).await.map_err(|e| e.to_string()), None => Err("the session's stdin is a file".into()), }; let _ = reply.send(r); } Some(SubCmd::Close) | None => { let _ = child.kill().await; break; } }, } } }); Ok(Sub { messages, commands }) }) } }