use std::{
collections::BTreeMap,
ffi::OsString,
fs::File,
future::Future,
io::{self, Read, Seek, SeekFrom},
path::{Path, PathBuf},
};
use super::process::{self, Child, ChildIdentity, ResolvedCommand};
use sha2::{Digest, Sha256};
#[cfg(not(target_os = "linux"))]
use {super::private::PrivateTempDir, std::sync::Arc};
#[cfg(unix)]
pub(super) mod unix;
#[cfg(windows)]
pub(super) mod windows;
#[cfg(unix)]
use unix as os;
#[cfg(windows)]
use windows as os;
pub use os::{open_executable, open_verified_directory, same_directory, same_file};
const COPY_BUFFER: usize = 64 * 1024;
type DigestBytes = [u8; 32];
fn digest(reader: &mut impl Read) -> io::Result<DigestBytes> {
let mut digest = Sha256::new();
let mut buffer = [0; COPY_BUFFER];
loop {
let read = reader.read(&mut buffer)?;
if read == 0 {
return Ok(digest.finalize().into());
}
digest.update(&buffer[..read]);
}
}
fn file_digest(file: &mut File) -> io::Result<DigestBytes> {
file.seek(SeekFrom::Start(0))?;
let digest = digest(file)?;
file.seek(SeekFrom::Start(0))?;
Ok(digest)
}
pub struct Executable {
path: PathBuf,
file: File,
digest: DigestBytes,
}
impl Executable {
pub fn open(path: &Path) -> io::Result<Self> {
require_absolute(path)?;
Self::snapshot(path, open_executable(path)?)
}
pub fn from_file(path: &Path, file: File) -> io::Result<Self> {
require_absolute(path)?;
if !file.metadata()?.is_file() || !same_file(&file, path)? {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"executable handle does not match the resolved file",
));
}
Self::snapshot(path, file)
}
fn snapshot(path: &Path, mut file: File) -> io::Result<Self> {
let digest = file_digest(&mut file)?;
Ok(Self {
path: path.to_owned(),
file,
digest,
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn sha256(&self) -> String {
self.digest
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
}
fn require_absolute(path: &Path) -> io::Result<()> {
if !path.is_absolute() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"executable requires a resolved absolute path",
));
}
Ok(())
}
fn verify_image(image: &mut File, expected: DigestBytes) -> io::Result<()> {
if file_digest(image)? != expected {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"verified executable changed before spawn",
));
}
Ok(())
}
pub struct Launch<'a> {
pub executable: Executable,
pub cwd: &'a Path,
pub directory: File,
pub args: &'a [OsString],
pub environment: &'a BTreeMap<OsString, OsString>,
}
#[derive(Clone, Default)]
pub(super) struct Lease {
#[cfg(not(target_os = "linux"))]
kind: Option<Arc<LeaseKind>>,
}
#[cfg(not(target_os = "linux"))]
enum LeaseKind {
#[cfg(not(target_os = "linux"))]
Staged {
#[cfg(windows)]
_guards: Vec<File>,
_directory: PrivateTempDir,
},
#[cfg(windows)]
Pinned { _files: Vec<File> },
}
impl Lease {
#[cfg(not(target_os = "linux"))]
fn staged(directory: PrivateTempDir, #[cfg(windows)] guards: Vec<File>) -> Self {
Self {
kind: Some(Arc::new(LeaseKind::Staged {
#[cfg(windows)]
_guards: guards,
_directory: directory,
})),
}
}
#[cfg(windows)]
fn pinned(files: Vec<File>) -> Self {
Self {
kind: Some(Arc::new(LeaseKind::Pinned { _files: files })),
}
}
#[cfg(not(target_os = "linux"))]
pub(super) fn has_resources(&self) -> bool {
self.kind.is_some()
}
}
struct Prepared {
command: ResolvedCommand,
lease: Lease,
}
pub struct Admission {
pub identity: ChildIdentity,
pub image: PathBuf,
}
#[derive(Clone, Copy, Default)]
pub enum Console {
#[default]
Inherit,
Hidden,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ImageKind {
Executable,
Native,
}
impl Launch<'_> {
pub async fn spawn(self) -> io::Result<Child> {
let (child, ()) = self
.spawn_registered(Console::Inherit, async |_| Ok(()))
.await?;
Ok(child)
}
pub async fn spawn_registered<R, F>(
self,
console: Console,
before_admit: impl FnOnce(Admission) -> F,
) -> io::Result<(Child, R)>
where
F: Future<Output = io::Result<R>>,
{
self.spawn_prepared(ImageKind::Executable, console, before_admit)
.await
}
pub async fn spawn_native_registered<R, F>(
self,
console: Console,
before_admit: impl FnOnce(Admission) -> F,
) -> io::Result<(Child, R)>
where
F: Future<Output = io::Result<R>>,
{
self.spawn_prepared(ImageKind::Native, console, before_admit)
.await
}
async fn spawn_prepared<R, F>(
self,
kind: ImageKind,
console: Console,
before_admit: impl FnOnce(Admission) -> F,
) -> io::Result<(Child, R)>
where
F: Future<Output = io::Result<R>>,
{
if !self.cwd.is_absolute() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"verified launch requires an absolute working directory",
));
}
let Launch {
executable,
cwd,
directory,
args,
environment,
} = self;
let cwd = cwd.to_owned();
let args = args.to_vec();
let environment = environment.clone();
let Prepared { command, lease } = tokio::task::spawn_blocking(move || {
os::prepare(
Launch {
executable,
cwd: &cwd,
directory,
args: &args,
environment: &environment,
},
kind,
)
})
.await
.map_err(|error| {
if error.is_panic() {
std::panic::resume_unwind(error.into_panic());
}
io::Error::other(error)
})??;
let image = PathBuf::from(command.as_std().get_program());
let (gate, spawning) = process::spawn_for_admission(command, console)?;
let admitted = async {
let gate = gate.identify().await?;
let admission = Admission {
identity: process::child_identity(gate.pid())?,
image,
};
let registration = before_admit(admission).await?;
gate.admit()?;
Ok::<_, io::Error>(registration)
}
.await;
let registration = match admitted {
Ok(registration) => registration,
Err(error) => {
let _ = spawning.await;
return Err(error);
}
};
let mut child = spawning.await.map_err(io::Error::other)??;
child.retain_image(lease);
Ok((child, registration))
}
}
#[cfg(test)]
mod tests;