artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
//! Parse and resolve the interpreter arguments for verified Unix launches.

use std::{
    ffi::{OsStr, OsString},
    fs::File,
    io,
    os::unix::{ffi::OsStrExt, fs::FileExt},
    path::{Path, PathBuf},
};

/// Darwin forbids recursive shebang redirection; Linux permits a bounded chain.
#[cfg(target_os = "macos")]
pub(in crate::platform) const MAX_DEPTH: usize = 1;
#[cfg(target_os = "linux")]
pub(in crate::platform) const MAX_DEPTH: usize = 4;

pub(in crate::platform) struct Shebang {
    pub path: PathBuf,
    pub options: Vec<OsString>,
}

pub(in crate::platform) fn read(file: &File) -> io::Result<Option<Shebang>> {
    // Linux caps the entire first line at 256 bytes. Darwin's image activator accepts
    // longer lines; inspect up to its 512-byte header rather than reading script content.
    #[cfg(target_os = "linux")]
    const HEADER_LIMIT: usize = 256;
    #[cfg(not(target_os = "linux"))]
    const HEADER_LIMIT: usize = 512;
    const MARKER: &[u8] = b"#!";
    let mut header = [0_u8; HEADER_LIMIT];
    let read = file.metadata()?.len().min(HEADER_LIMIT as u64) as usize;
    file.read_exact_at(&mut header[..read], 0)?;
    let Some(body) = header[..read].strip_prefix(MARKER) else {
        return Ok(None);
    };
    let (line, options) = split_shebang(body, HEADER_LIMIT - MARKER.len())?;
    let interpreter = PathBuf::from(OsStr::from_bytes(line));
    if !interpreter.is_absolute() {
        return Err(invalid_shebang());
    }
    Ok(Some(Shebang {
        path: interpreter,
        options,
    }))
}

fn split_shebang(body: &[u8], limit: usize) -> io::Result<(&[u8], Vec<OsString>)> {
    let whitespace = |byte: &u8| matches!(byte, b' ' | b'\t');
    #[cfg(target_os = "linux")]
    let end = body.iter().position(|byte| *byte == b'\n');
    #[cfg(target_os = "macos")]
    let end = body.iter().position(|byte| matches!(byte, b'\n' | b'#'));
    #[cfg(target_os = "macos")]
    if end.is_none() {
        return Err(invalid_shebang());
    }
    let line = &body[..end.unwrap_or(body.len())];
    if line.len() == limit || line.contains(&0) {
        return Err(invalid_shebang());
    }
    let first = line
        .iter()
        .position(|byte| !whitespace(byte))
        .ok_or_else(invalid_shebang)?;
    let last = line
        .iter()
        .rposition(|byte| !whitespace(byte))
        .expect("nonempty line");
    let line = &line[first..=last];
    let end = line.iter().position(whitespace).unwrap_or(line.len());
    #[cfg(target_os = "linux")]
    let args = line[end..]
        .iter()
        .position(|byte| !whitespace(byte))
        .map(|first| OsStr::from_bytes(&line[end + first..]).to_owned())
        .into_iter()
        .collect();
    #[cfg(target_os = "macos")]
    let args = line[end..]
        .split(whitespace)
        .filter(|arg| !arg.is_empty())
        .map(|arg| OsStr::from_bytes(arg).to_owned())
        .collect();
    Ok((&line[..end], args))
}

impl Shebang {
    /// Recognize the system env shim, including a protected alias to it.
    pub fn uses_env(&self, canonical: &Path) -> bool {
        let system_env = [Path::new("/usr/bin/env"), Path::new("/bin/env")];
        system_env.contains(&self.path.as_path())
            || (self.path.file_name() == Some(OsStr::new("env"))
                || canonical.file_name() == Some(OsStr::new("env")))
                && system_env.iter().any(|path| {
                    std::fs::canonicalize(path).is_ok_and(|resolved| resolved == canonical)
                })
    }

    /// Resolve the simple env forwarder in the launcher's lookup environment. Callers
    /// execute the selected path directly rather than allow env to search again.
    pub fn env_target(&self, cwd: &Path, search: Option<&OsStr>) -> io::Result<(&OsStr, PathBuf)> {
        let [name] = self.options.as_slice() else {
            return Err(invalid_shebang());
        };
        let bytes = name.as_bytes();
        if bytes.starts_with(b"-")
            || bytes
                .iter()
                .any(|byte| byte.is_ascii_whitespace() || *byte == b'=')
        {
            return Err(invalid_shebang());
        }
        let path = Path::new(name);
        let resolved = if path.is_absolute() {
            path.to_owned()
        } else {
            // An env target is either absolute or a bare name. Fail closed on
            // dynamic env syntax instead of interpreting it as a different launch.
            if bytes.contains(&b'/') {
                return Err(invalid_shebang());
            }
            let search = search.ok_or_else(invalid_shebang)?;
            crate::platform::program::resolve_with(path, cwd, |key| {
                (key == "PATH").then(|| search.to_owned())
            })?
        };
        Ok((name, resolved))
    }
}

fn invalid_shebang() -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidData,
        "unsupported verified script interpreter declaration",
    )
}