artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
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,
    },
};

/// Open a regular file without following reparse points, with `FILE_SHARE_READ` only.
/// This excludes writers but does not verify a launch; use [`super::Executable`] to bind the
/// file's bytes to a subsequent spawn.
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",
        ))
    }
}

/// Open a verified working directory directory without following reparse points and without
/// `FILE_SHARE_DELETE`, preventing rename or deletion of the directory until the handle closes
///.
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",
        ))
    }
}

/// Whether `path` currently resolves (without following reparse points) to the exact same
/// regular file identity as `file`.
pub fn same_file(file: &File, path: &Path) -> io::Result<bool> {
    let current = open_executable(path)?;
    Ok(file_identity(file)? == file_identity(&current)?)
}

/// Whether `path` currently resolves (without following reparse points) to the exact same
/// directory identity as `dir`.
pub fn same_directory(dir: &File, path: &Path) -> io::Result<bool> {
    let current = open_verified_directory(path)?;
    Ok(file_identity(dir)? == file_identity(&current)?)
}

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 {
    /// Execute an exact `.exe` name, dispatch a batch script, or stage an extensionless
    /// native image so Rust's appended `.exe` search never selects a different file.
    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,
        ))
    }
}

/// Keep a native executable image section live until the loader takes its own reference.
/// This protects the file contents without changing application-relative DLL lookups.
pub(in crate::platform) struct ImageView(MEMORY_MAPPED_VIEW_ADDRESS);

// SAFETY: a mapped view belongs to the process, not its creating thread. The address is
// never dereferenced and only this owner calls UnmapViewOfFile on it.
unsafe impl Send for ImageView {}

impl ImageView {
    fn open(file: &File) -> io::Result<Self> {
        // SAFETY: the handle borrows a pinned readable file. No security attributes or name
        // are supplied; the object is anonymous and the handle is not inheritable.
        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());
        }
        // SAFETY: this is a new kernel handle owned by this function.
        let mapping = unsafe { OwnedHandle::from_raw_handle(mapping) };
        // SAFETY: request a view of the complete existing image. A live view keeps the image
        // section referenced even after its mapping handle closes. Nothing executes the view.
        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) {
        // SAFETY: this owner holds a mapped view from MapViewOfFile and unmaps it once.
        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),
            // Some filesystems can supply bytes but do not expose executable sections.
            // They may launch only via the same verified private copy as extensionless images.
            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() {
        // CreateProcess opens the exact pathname. Keep its ancestors and file identity pinned
        // and hash only after the kernel has bound a live executable section to that file.
        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)?;
        // Keep the script's original directory for shims that use %~dp0. The
        // interpreter opens it after process creation, potentially more than once.
        // The read-only share mode excludes writable opens while the lease lives.
        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 {
        // Hash the private copy CreateProcess will open, not the source pathname.
        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>> {
    // Start at the root: pinning from the leaf would accept an ancestor substituted
    // between opening its child and opening the ancestor itself.
    let ancestors = path.ancestors().skip(1).collect::<Vec<_>>();
    ancestors
        .into_iter()
        .rev()
        .map(open_verified_directory)
        .collect()
}