use std::borrow::Cow;
use std::process::Stdio as ProcessStdio;
use std::sync::Arc;
use askama::Template;
use executor_core::{AnyExecutor, Executor};
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
use super::child::{ChildExit, Descendants, KillHandle, SandboxedChild, Streams, exit_watch};
use super::{
EnvSource, Pipe, RemoteLaunch, Sandbox, SpawnCommand, SpawnError, SpawnSpec, script_reading,
};
use crate::SshServer;
use crate::process_tree::{KillTreeError, kill_process_tree};
use crate::ssh::SshClient;
use crate::terminal::{inject_env_exports, shell_launch};
#[derive(Template)]
#[template(path = "ssh_tool_execution.sh", escape = "none")]
struct SshToolExecutionTemplate<'a> {
binary: Cow<'a, str>,
tools_dir: Cow<'a, str>,
uv_grant: Option<String>,
program: Cow<'a, str>,
arguments: String,
}
pub fn remote_command(
launch: &RemoteLaunch,
heel: Option<&str>,
script: &str,
) -> Result<String, askama::Error> {
let script = launch.wrap_script(script)?;
let (program, args) = shell_launch(launch.shell(), &script);
let Some(binary) = heel else {
return Ok(shell_words::join(
std::iter::once(program.as_str()).chain(args.iter().map(String::as_str)),
));
};
let uv_grant = launch
.writable_dir()
.map(|dir| shell_words::quote(&format!("{dir}=rwx")).into_owned());
SshToolExecutionTemplate {
binary: shell_words::quote(binary),
tools_dir: shell_words::quote(launch.bin_dir()),
uv_grant,
program: shell_words::quote(&program),
arguments: shell_words::join(&args),
}
.render()
}
#[derive(Template)]
#[template(path = "ssh_job_start.sh", escape = "none")]
struct SshJobStartTemplate<'a> {
pidfile: &'a str,
command: &'a str,
}
#[derive(Template)]
#[template(path = "ssh_job_kill.sh", escape = "none")]
struct SshJobKillTemplate<'a> {
pidfile: &'a str,
}
#[derive(Debug)]
pub struct RemoteJob {
client: SshClient,
server: SshServer,
pidfile: String,
local: u32,
}
impl RemoteJob {
pub(crate) async fn kill(&self) -> Result<(), KillTreeError> {
let script = SshJobKillTemplate {
pidfile: &self.pidfile,
}
.render()
.map_err(|error| KillTreeError::Signal(std::io::Error::other(error)))?;
let command = self
.client
.command(&self.server, &script)
.await
.map_err(|error| KillTreeError::Signal(std::io::Error::other(error)))?;
let output = async_process::Command::from(command)
.stdin(ProcessStdio::null())
.output()
.await
.map_err(KillTreeError::Signal)?;
if !output.status.success() {
return Err(KillTreeError::Signal(std::io::Error::other(format!(
"ending the job on {} failed ({}): {}",
self.server.name,
output.status,
String::from_utf8_lossy(&output.stderr).trim()
))));
}
let local = kill_process_tree(self.local).await;
#[cfg(unix)]
if matches!(&local, Err(KillTreeError::Signal(error)) if error.raw_os_error() == Some(libc::ESRCH))
{
return Ok(());
}
local
}
}
const fn process_stdio(pipe: Pipe) -> fn() -> ProcessStdio {
match pipe {
Pipe::Null => ProcessStdio::null,
Pipe::Piped => ProcessStdio::piped,
}
}
impl Sandbox {
pub(super) async fn spawn_ssh(
&self,
server: &SshServer,
server_heel: Option<&str>,
launch: &RemoteLaunch,
spec: SpawnSpec,
) -> Result<SandboxedChild, SpawnError> {
let failed = |error: &dyn std::fmt::Display| SpawnError::Setup(error.to_string());
let SpawnSpec {
command,
env,
cwd,
stdio,
grants,
ipc,
lifetime: _,
info,
} = spec;
if !grants.is_empty() {
return Err(SpawnError::Unsupported {
backend: "ssh",
what: "a grant",
});
}
if ipc.is_some() {
return Err(SpawnError::Unsupported {
backend: "ssh",
what: "a way back to the host's commands",
});
}
if cwd.is_some() {
return Err(SpawnError::Setup(
"an SSH process starts in the server's login directory: a host path names nothing there"
.into(),
));
}
let heel = if self.inner.unconfined {
None
} else {
Some(server_heel.ok_or_else(|| {
SpawnError::Setup(format!(
"the server {} has no heel, so a process on it cannot be sandboxed",
server.name
))
})?)
};
let script = match command {
SpawnCommand::Script(script) => script,
SpawnCommand::Program { program, args } => {
shell_words::join(std::iter::once(&program).chain(&args))
}
};
let script = script_reading(stdio.stdin, script)?;
let spec_env: Arc<dyn EnvSource> = Arc::new(env);
let script = inject_env_exports(script, Some(&spec_env), &info).map_err(|e| failed(&e))?;
let remote = remote_command(launch, heel, &script).map_err(|e| failed(&e))?;
let pidfile = shell_words::quote(&format!(
"/tmp/aither-spawn-{}.pgid",
uuid::Uuid::new_v4().simple()
))
.into_owned();
let remote = SshJobStartTemplate {
pidfile: &pidfile,
command: &remote,
}
.render()
.map_err(|e| failed(&e))?;
let command = self
.inner
.ssh_client
.command(server, &remote)
.await
.map_err(|error| SpawnError::Start(error.to_string()))?;
#[cfg(unix)]
let command = {
let mut command = command;
std::os::unix::process::CommandExt::process_group(&mut command, 0);
command
};
let mut child = async_process::Command::from(command)
.stdin(process_stdio(stdio.stdin)())
.stdout(process_stdio(stdio.stdout)())
.stderr(process_stdio(stdio.stderr)())
.spawn()
.map_err(|error| SpawnError::Start(error.to_string()))?;
let id = child.id();
let executor = &self.inner.executor;
let streams = pipe_streams(executor, &mut child);
let watch = watch_exit(executor, child);
Ok(SandboxedChild::new(
id,
streams,
KillHandle::Remote(RemoteJob {
client: self.inner.ssh_client.clone(),
server: server.clone(),
pidfile,
local: id,
}),
watch,
))
}
}
fn watch_exit(
executor: &AnyExecutor,
mut child: async_process::Child,
) -> Arc<super::child::ExitWatch> {
let (setter, watch) = exit_watch();
executor
.spawn(async move {
setter.finish(
match child.status().await {
Ok(status) => ChildExit::Exited(status),
Err(error) => ChildExit::Failed(error.to_string()),
},
Descendants::Unobserved,
);
})
.detach();
watch
}
fn pipe_streams(executor: &AnyExecutor, child: &mut async_process::Child) -> Streams {
let mut streams = Streams::default();
if let Some(mut stdin) = child.stdin.take() {
let (tx, rx) = async_channel::unbounded::<Vec<u8>>();
streams.stdin = Some(tx);
executor
.spawn(async move {
while let Ok(bytes) = rx.recv().await {
if stdin.write_all(&bytes).await.is_err() || stdin.flush().await.is_err() {
break;
}
}
})
.detach();
}
if let Some(stdout) = child.stdout.take() {
let (tx, rx) = async_channel::unbounded();
streams.stdout = Some(rx);
executor.spawn(pump(stdout, tx)).detach();
}
if let Some(stderr) = child.stderr.take() {
let (tx, rx) = async_channel::unbounded();
streams.stderr = Some(rx);
executor.spawn(pump(stderr, tx)).detach();
}
streams
}
async fn pump(
mut reader: impl futures_lite::AsyncRead + Unpin,
tx: async_channel::Sender<Vec<u8>>,
) {
let mut buffer = vec![0_u8; 8192];
while let Ok(count) = reader.read(&mut buffer).await {
if count == 0 || tx.send(buffer[..count].to_vec()).await.is_err() {
break;
}
}
}