artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
//! Literal program lookup, shared by preflight and process launches.

use std::{
    env,
    ffi::{OsStr, OsString},
    io,
    path::{Path, PathBuf},
};

/// The variable listing the directories a bare program name is looked up in.
const SEARCH_PATH: &str = "PATH";
/// The Windows variable listing the extensions an extensionless name is tried with.
const EXTENSIONS: &str = "PATHEXT";

/// Look up a pathname using the child environment, not the caller's PATH. This is for
/// inspection only. Use [`super::process::resolve_with`] to select an image for execution.
/// `variable` may be a case-sensitive lookup into a stored environment snapshot.
pub fn resolve_with(
    program: &Path,
    cwd: &Path,
    variable: impl Fn(&str) -> Option<OsString>,
) -> io::Result<PathBuf> {
    resolve_from(
        program,
        cwd,
        lookup_variable(&variable, SEARCH_PATH).as_deref(),
        extensions(&variable).as_deref(),
    )
}

#[cfg(unix)]
fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
    variable(name)
}

#[cfg(windows)]
fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
    // Our only lookup keys are the short, ASCII-alphabetic PATH and PATHEXT. Try their
    // spellings in reverse map order, so the last entry wins just as in Command::envs.
    // A native environment lookup succeeds on the first spelling whenever set.
    let mut spelling = name.as_bytes().to_owned();
    (0..(1 << name.len())).rev().find_map(|variant| {
        for (bit, byte) in spelling.iter_mut().rev().enumerate() {
            *byte = if variant & (1 << bit) == 0 {
                byte.to_ascii_uppercase()
            } else {
                byte.to_ascii_lowercase()
            };
        }
        variable(std::str::from_utf8(&spelling).expect("ASCII environment key"))
    })
}

fn extensions(variable: &impl Fn(&str) -> Option<OsString>) -> Option<OsString> {
    USES_PATHEXT
        .then(|| lookup_variable(variable, EXTENSIONS))
        .flatten()
}

fn resolve_from(
    program: &Path,
    cwd: &Path,
    path: Option<&OsStr>,
    pathext: Option<&OsStr>,
) -> io::Result<PathBuf> {
    lookup_paths(program, cwd, path, pathext)
        .into_iter()
        .find(|candidate| is_executable(candidate))
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "Program is unavailable: {}",
                    super::files::path_text(program)
                ),
            )
        })
}

fn lookup_paths(
    program: &Path,
    cwd: &Path,
    path: Option<&OsStr>,
    pathext: Option<&OsStr>,
) -> Vec<PathBuf> {
    let candidates = candidates_from(program, pathext);
    if program.has_root()
        || program.components().count() > 1
        || matches!(
            program.components().next(),
            Some(std::path::Component::Prefix(_))
        )
    {
        return candidates
            .into_iter()
            .filter_map(|candidate| anchor(cwd, &candidate))
            .collect();
    }
    path.into_iter()
        .flat_map(env::split_paths)
        .filter_map(|directory| anchor(cwd, &directory))
        .flat_map(|directory| {
            candidates
                .iter()
                .map(move |candidate| directory.join(candidate))
        })
        .collect()
}

#[cfg(unix)]
fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
    Some(cwd.join(path))
}

#[cfg(windows)]
fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
    use std::path::{Component, Prefix};

    let mut components = path.components();
    if let Some(Component::Prefix(prefix)) = components.next()
        && !path.is_absolute()
    {
        // Resolve C:tool against the *child's* directory on C:, never the parent's
        // implicit per-drive working directory. No base was given for other drives.
        let drive = |prefix| match prefix {
            Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => Some(drive.to_ascii_uppercase()),
            _ => None,
        };
        let Some(Component::Prefix(base)) = cwd.components().next() else {
            return None;
        };
        return (cwd.is_absolute()
            && drive(prefix.kind()).is_some()
            && drive(prefix.kind()) == drive(base.kind()))
        .then(|| cwd.join(components.as_path()));
    }
    Some(cwd.join(path))
}

/// Candidate paths in lookup order. A scoped caller validates candidates inside its own
/// access boundary before allowing them to reach a process launcher.
pub fn candidates(program: &Path, variable: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
    candidates_from(program, extensions(&variable).as_deref())
}

fn candidates_from(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
    if USES_PATHEXT && program.extension().is_none() {
        pathext_candidates(program, pathext)
    } else {
        vec![program.to_owned()]
    }
}

/// The Windows default when the variable is absent, not when explicitly empty.
const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";

/// One candidate per `PATHEXT` suffix, in its order.
fn pathext_candidates(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
    let pathext = pathext.unwrap_or_else(|| OsStr::new(DEFAULT_PATHEXT));
    // Split the native string itself, so an extension keeps every byte or UTF-16 unit it was
    // given rather than a lossy text copy.
    split_list(pathext)
        .into_iter()
        .filter(|extension| {
            let bytes = extension.as_encoded_bytes();
            bytes.first() == Some(&b'.') && !bytes.iter().any(|byte| matches!(byte, b'/' | b'\\'))
        })
        .map(|extension| {
            let mut candidate = program.as_os_str().to_owned();
            candidate.push(extension);
            PathBuf::from(candidate)
        })
        .collect()
}

/// The `;`-separated entries of a native list, each exactly as the OS string holds it.
#[cfg(windows)]
fn split_list(list: &OsStr) -> Vec<OsString> {
    use std::os::windows::ffi::{OsStrExt, OsStringExt};
    let units: Vec<u16> = list.encode_wide().collect();
    units
        .split(|unit| *unit == u16::from(b';'))
        .map(OsString::from_wide)
        .collect()
}

/// The `;`-separated entries of a native list, each exactly as the OS string holds it.
#[cfg(unix)]
fn split_list(list: &OsStr) -> Vec<OsString> {
    use std::os::unix::ffi::{OsStrExt, OsStringExt};
    list.as_bytes()
        .split(|byte| *byte == b';')
        .map(|entry| OsString::from_vec(entry.to_vec()))
        .collect()
}

#[cfg(unix)]
/// Unix names programs exactly; extensions carry no meaning for lookup.
const USES_PATHEXT: bool = false;

#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
    use rustix::fs::{Access, AtFlags, CWD, accessat};

    path.is_file() && accessat(CWD, path, Access::EXEC_OK, AtFlags::EACCESS).is_ok()
}

#[cfg(windows)]
/// An extensionless program name is tried with each `PATHEXT` suffix.
const USES_PATHEXT: bool = true;

/// Windows has no execute bit; any regular file is a lookup candidate, including batch shims.
#[cfg(windows)]
fn is_executable(path: &Path) -> bool {
    path.is_file()
}

#[cfg(test)]
mod tests;