use super::super::private::{
create_private_file, file_identity, is_owner_only, private_tempdir_in,
};
use super::super::process::{Program, ResolvedCommand};
use super::{DigestBytes, Executable, ImageKind, Launch, Lease, Prepared, verify_image};
use std::{
ffi::{OsStr, OsString},
fs::{File, OpenOptions},
io::{self, Seek, SeekFrom},
os::windows::{
fs::OpenOptionsExt,
io::{AsRawHandle, FromRawHandle, OwnedHandle},
},
path::Path,
process::Stdio,
ptr,
};
use tokio::process::Command;
use windows_sys::Win32::{
Foundation::{ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED},
Storage::FileSystem::{FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_READ},
System::Memory::{
CreateFileMappingW, FILE_MAP_READ, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile,
PAGE_READONLY, SEC_IMAGE, UnmapViewOfFile,
},
};
pub fn open_executable(path: &Path) -> io::Result<File> {
let mut options = OpenOptions::new();
options.read(true).share_mode(FILE_SHARE_READ);
let file = super::super::files::open_no_follow(&mut options, path)?;
if file.metadata()?.is_file() {
Ok(file)
} else {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a regular file",
))
}
}
pub fn open_verified_directory(path: &Path) -> io::Result<File> {
let mut options = OpenOptions::new();
options
.read(true)
.share_mode(FILE_SHARE_READ)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
let file = super::super::files::open_no_follow(&mut options, path)?;
if file.metadata()?.is_dir() {
Ok(file)
} else {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a directory",
))
}
}
pub fn same_file(file: &File, path: &Path) -> io::Result<bool> {
let current = open_executable(path)?;
Ok(file_identity(file)? == file_identity(¤t)?)
}
pub fn same_directory(dir: &File, path: &Path) -> io::Result<bool> {
let current = open_verified_directory(path)?;
Ok(file_identity(dir)? == file_identity(¤t)?)
}
pub(in crate::platform) mod batch;
pub(in crate::platform) fn extension_is(path: &Path, suffix: &str) -> bool {
path.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case(suffix))
}
fn is_batch(path: &Path) -> bool {
extension_is(path, "cmd") || extension_is(path, "bat")
}
impl Program {
pub fn command(
self,
args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> io::Result<ResolvedCommand> {
let canonical = self.canonical_path();
if extension_is(canonical, "exe") {
let mut command = Command::new(canonical);
command.args(args);
return Ok(ResolvedCommand::ordinary(command, Lease::default(), false));
}
let args = args
.into_iter()
.map(|arg| arg.as_ref().to_owned())
.collect::<Vec<_>>();
if is_batch(canonical) {
let command = batch::command(canonical, &args)?;
return Ok(ResolvedCommand::ordinary(command, Lease::default(), true));
}
let mut source = File::open(canonical)?;
let stage = private_tempdir_in("artifactize-image-", &std::env::temp_dir())?;
let target = stage.path().join("exec.exe");
copy_image(&mut source, &target)?;
let mut command = Command::new(&target);
command.args(args);
Ok(ResolvedCommand::ordinary(
command,
Lease::staged(stage, Vec::new()),
false,
))
}
}
pub(in crate::platform) struct ImageView(MEMORY_MAPPED_VIEW_ADDRESS);
unsafe impl Send for ImageView {}
impl ImageView {
fn open(file: &File) -> io::Result<Self> {
let mapping = unsafe {
CreateFileMappingW(
file.as_raw_handle(),
ptr::null(),
PAGE_READONLY | SEC_IMAGE,
0,
0,
ptr::null(),
)
};
if mapping.is_null() {
return Err(io::Error::last_os_error());
}
let mapping = unsafe { OwnedHandle::from_raw_handle(mapping) };
let view = unsafe { MapViewOfFile(mapping.as_raw_handle(), FILE_MAP_READ, 0, 0, 0) };
if view.Value.is_null() {
return Err(io::Error::last_os_error());
}
Ok(Self(view))
}
}
impl Drop for ImageView {
fn drop(&mut self) {
unsafe { UnmapViewOfFile(self.0) };
}
}
pub(super) fn prepare(launch: Launch<'_>, kind: ImageKind) -> io::Result<Prepared> {
let Launch {
executable: Executable { path, file, digest },
cwd,
directory,
args,
environment,
} = launch;
let path = std::fs::canonicalize(path)?;
let cwd = super::super::files::canonicalize(cwd)?;
let executable_guards = pin_ancestors(&path)?;
let mut until_spawn = pin_ancestors(&cwd)?;
let mut pinned_file = open_executable(&path)?;
let pinned_cwd = open_verified_directory(&cwd)?;
if file_identity(&pinned_file)? != file_identity(&file)?
|| file_identity(&pinned_cwd)? != file_identity(&directory)?
{
return Err(changed());
}
until_spawn.push(pinned_cwd);
let image = if extension_is(&path, "exe") {
match ImageView::open(&pinned_file) {
Ok(image) => Some(image),
Err(error)
if matches!(
error.raw_os_error().map(|code| code as u32),
Some(ERROR_NOT_SUPPORTED | ERROR_INVALID_FUNCTION)
) =>
{
None
}
Err(error) => return Err(error),
}
} else {
None
};
let (mut command, lease) = if image.is_some() {
verify_image(&mut pinned_file, digest)?;
until_spawn.extend(executable_guards.into_iter().chain([pinned_file]));
let mut command = Command::new(&path);
command.args(args);
(command, Lease::default())
} else if is_batch(&path) {
if kind == ImageKind::Native {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"native launch does not accept scripts",
));
}
batch::check_working_directory(&cwd)?;
verify_image(&mut pinned_file, digest)?;
let files = executable_guards.into_iter().chain([pinned_file]).collect();
let (command, interpreter_guards) = batch::verified_command(&path, args)?;
until_spawn.extend(interpreter_guards);
(command, Lease::pinned(files))
} else {
let (command, stage, guards) = stage_native(pinned_file, args, digest)?;
until_spawn.extend(guards);
(command, Lease::staged(stage, Vec::new()))
};
command
.current_dir(cwd)
.env_clear()
.envs(environment.iter())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let command =
ResolvedCommand::verified(command, lease.clone(), is_batch(&path), until_spawn, image)?;
Ok(Prepared { command, lease })
}
fn stage_native(
mut source: File,
args: &[OsString],
digest: DigestBytes,
) -> io::Result<(Command, super::PrivateTempDir, Vec<File>)> {
let parent = std::fs::canonicalize(std::env::temp_dir())?;
let mut guards = pin_ancestors(&parent)?;
guards.push(open_verified_directory(&parent)?);
let stage = private_tempdir_in("artifactize-image-", &parent)?;
let directory = open_verified_directory(stage.path())?;
if !is_owner_only(&directory)? {
return Err(changed());
}
let target = stage.path().join("exec.exe");
let staged = copy_image(&mut source, &target)?;
let identity = file_identity(&staged)?;
drop(staged);
let mut pinned = open_executable(&target)?;
if file_identity(&pinned)? != identity {
return Err(changed());
}
verify_image(&mut pinned, digest)?;
guards.extend([directory, pinned]);
let mut command = Command::new(&target);
command.args(args);
Ok((command, stage, guards))
}
fn copy_image(source: &mut File, target: &Path) -> io::Result<File> {
let mut staged = create_private_file(target)?;
source.seek(SeekFrom::Start(0))?;
io::copy(source, &mut staged)?;
Ok(staged)
}
fn changed() -> io::Error {
io::Error::new(
io::ErrorKind::PermissionDenied,
"verified executable or working directory changed before spawn",
)
}
fn pin_ancestors(path: &Path) -> io::Result<Vec<File>> {
let ancestors = path.ancestors().skip(1).collect::<Vec<_>>();
ancestors
.into_iter()
.rev()
.map(open_verified_directory)
.collect()
}