artifactize-foundation 0.27.0

Native file, path and executable primitives for Artifactize.
Documentation
//! Invoke the system interpreter on the selected script without Windows Command
//! resolving a different application first. Keep cmd.exe's argument-vector encoding in this layer.

use std::{
    ffi::{OsStr, OsString},
    fs::File,
    io,
    os::windows::{
        ffi::{OsStrExt, OsStringExt},
        process::CommandExt,
    },
    path::{Component, Path, PathBuf, Prefix},
};
use tokio::process::Command;
use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW;

pub(super) fn command(path: &Path, args: &[OsString]) -> io::Result<Command> {
    let interpreter = std::fs::canonicalize(system_interpreter()?)?;
    let mut command = std::process::Command::new(interpreter);
    command.raw_arg(command_line(path, args)?);
    Ok(Command::from(command))
}

pub(super) fn verified_command(path: &Path, args: &[OsString]) -> io::Result<(Command, Vec<File>)> {
    let command = command(path, args)?;
    let interpreter = Path::new(command.as_std().get_program());
    let mut guards = super::pin_ancestors(interpreter)?;
    guards.push(super::open_executable(interpreter)?);
    Ok((command, guards))
}

pub(in crate::platform) fn check_working_directory(cwd: &Path) -> io::Result<()> {
    let cwd = std::path::absolute(cwd)?;
    if matches!(cwd.components().next(), Some(Component::Prefix(prefix))
        if matches!(prefix.kind(), Prefix::UNC(..) | Prefix::VerbatimUNC(..)))
    {
        // cmd silently substitutes the Windows directory for a UNC working directory.
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "Windows batch launches require a local working directory",
        ));
    }
    Ok(())
}

fn command_line(path: &Path, args: &[OsString]) -> io::Result<OsString> {
    // cmd.exe must see an ordinary absolute path. Do not let its percent expansion rewrite it.
    let path = super::super::super::files::plain(path).ok_or_else(invalid_arguments)?;
    let script = path.as_os_str();
    if script
        .as_encoded_bytes()
        .iter()
        .any(|byte| b"\0\r\n\"%".contains(byte))
    {
        return Err(invalid_arguments());
    }
    // Disable AutoRun and delayed expansion. /s removes exactly the outer quote pair.
    let mut line: Vec<u16> = "/e:ON /v:OFF /d /s /c \"\"".encode_utf16().collect();
    line.extend(script.encode_wide());
    line.push(u16::from(b'"'));
    for arg in args {
        line.push(u16::from(b' '));
        append_argument(&mut line, arg)?;
    }
    line.push(u16::from(b'"'));
    Ok(OsString::from_wide(&line))
}

fn invalid_arguments() -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidInput,
        "invalid Windows batch path or arguments",
    )
}

fn append_argument(line: &mut Vec<u16>, arg: &OsStr) -> io::Result<()> {
    // As in std's batch encoder, quote everything except known inert shell characters.
    const UNQUOTED: &str = r"#$*+-./:?@\_";
    const QUOTE: u16 = b'"' as u16;
    const SLASH: u16 = b'\\' as u16;
    const PERCENT: u16 = b'%' as u16;
    let bytes = arg.as_encoded_bytes();
    if bytes.iter().any(|byte| b"\0\r\n".contains(byte)) {
        return Err(invalid_arguments());
    }
    let quote = bytes.is_empty()
        || bytes.ends_with(b"\\")
        || arg.to_string_lossy().chars().any(|c| {
            c.is_control() || (c.is_ascii() && !c.is_ascii_alphanumeric() && !UNQUOTED.contains(c))
        });
    if quote {
        line.push(QUOTE);
    }
    let mut slashes = 0;
    for unit in arg.encode_wide() {
        match unit {
            SLASH => slashes += 1,
            QUOTE => {
                line.extend(std::iter::repeat_n(SLASH, slashes));
                line.push(QUOTE);
                slashes = 0;
            }
            PERCENT => {
                // The same empty CD substring as std uses to prevent expanding %variables%.
                line.extend("%%cd:~,".encode_utf16());
                slashes = 0;
            }
            _ => slashes = 0,
        }
        line.push(unit);
    }
    if quote {
        line.extend(std::iter::repeat_n(SLASH, slashes));
        line.push(QUOTE);
    }
    Ok(())
}

fn system_interpreter() -> io::Result<PathBuf> {
    // GetSystemDirectoryW reports a required size including NUL if the buffer is too small.
    const MAX_WIDE_PATH: usize = 32_768;
    let mut buffer = vec![0; MAX_WIDE_PATH];
    // SAFETY: the buffer is writable for the supplied number of UTF-16 units.
    let length = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) } as usize;
    if length == 0 {
        return Err(io::Error::last_os_error());
    }
    let units = buffer.get(..length).ok_or(io::ErrorKind::InvalidData)?;
    Ok(PathBuf::from(OsString::from_wide(units)).join("cmd.exe"))
}