artifactize-core 0.27.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Unix private file modes, process control, signals, and termios.
//! Pinned file access lives in artifactize-tools.

pub(crate) mod ipc;

use std::{future::Future, io, path::Path};

use tokio::signal::unix::{SignalKind, signal};

pub(crate) use artifactize_foundation::platform::process::{
    Child, hide_console_window, kill_saved_group, kill_saved_session, spawn_detached, spawn_gated,
    spawn_run, spawn_watched,
};

/// Give the heap memory freed so far back to the system. glibc keeps freed memory in its
/// arenas for reuse, so a long-lived process that once read much stays that large; macOS's
/// allocator returns it by itself.
pub(crate) fn release_free_memory() {
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    // SAFETY: malloc_trim only releases memory that is already free, under glibc's own locks.
    unsafe {
        libc::malloc_trim(0);
    }
}

/// POSIX file locks are advisory, and unlinking a name never invalidates another handle's
/// access to it, so a plain metadata or open race like Windows's never happens here.
pub(crate) fn transient_file_access(_error: &io::Error) -> bool {
    false
}

/// Permission bits granting access to group or other users.
pub(crate) const GROUP_OTHER_BITS: u32 = 0o077;

/// Group and other write bits permit system aliases or IPC parents to be replaced.
const GROUP_OTHER_WRITE_BITS: u32 = 0o022;

/// Environment variable names compare exactly.
pub(crate) const ENV_NAMES_IGNORE_CASE: bool = false;

/// The variable naming the user's home directory.
pub(crate) const HOME_VARIABLES: &[&str] = &["HOME"];

/// Variables programs read their temporary directory from. `TMP` and `TEMP` are set too, for
/// programs written for Windows.
pub(crate) const TEMP_VARIABLES: &[&str] = &["TMPDIR", "TMP", "TEMP"];

/// Variables naming a per-user state directory, in order; artifactize keeps its state in an
/// `artifactize` folder below the first one set, and otherwise below `HOME`.
pub(crate) const STATE_VARIABLES: &[&str] = &["XDG_STATE_HOME"];

/// The variables naming the signed-in user, in order.
pub(crate) const USER_VARIABLES: &[&str] = &["USER", "LOGNAME"];

/// The user's home directory.
pub(crate) fn home_directory() -> Option<std::path::PathBuf> {
    std::env::var_os(HOME_VARIABLES[0])
        .filter(|path| !path.is_empty())
        .map(Into::into)
}

/// A path from the raw bytes a tool such as git prints: any bytes name a Unix path.
pub(crate) fn path_from_bytes(bytes: &[u8]) -> std::path::PathBuf {
    use std::os::unix::ffi::OsStringExt;
    std::ffi::OsString::from_vec(bytes.to_vec()).into()
}

/// Unix programs end a line with LF only.
pub(crate) const CRLF_LINE_ENDINGS: bool = false;

/// Whether a terminal that cannot hide input is still read, visibly, after a warning. A Unix
/// terminal always can; failing to hide input is an error.
pub const VISIBLE_INPUT_FALLBACK: bool = false;

/// The operating system's host name, without depending on a proc filesystem.
pub(crate) fn host_name() -> Option<String> {
    hostname::get().ok()?.into_string().ok()
}

/// The absolute form of `path` with a leading macOS system alias (`/tmp`, `/var`, `/etc`)
/// replaced by its fixed `/private` target. The alias and its parents must be root-owned
/// and not replaceable; descendants are left for the caller to open without following links.
#[cfg(target_os = "macos")]
pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
    use std::{fs, os::unix::fs::MetadataExt};
    let absolute = std::path::absolute(path)?;
    for name in ["tmp", "var", "etc"] {
        let alias = Path::new("/").join(name);
        if let Ok(suffix) = absolute.strip_prefix(&alias) {
            let metadata = alias.symlink_metadata()?;
            let target = Path::new("/private").join(name);
            let link = fs::read_link(&alias)?;
            let link = if link.is_absolute() {
                link
            } else {
                Path::new("/").join(link)
            };
            if !metadata.is_symlink() || metadata.uid() != 0 || link != target {
                return Err(io::Error::other(format!(
                    "Refusing an untrusted system alias: {}",
                    alias.display()
                )));
            }
            for parent in [Path::new("/"), Path::new("/private")] {
                let metadata = parent.symlink_metadata()?;
                if !metadata.is_dir()
                    || metadata.uid() != 0
                    || metadata.mode() & GROUP_OTHER_WRITE_BITS != 0
                {
                    return Err(io::Error::other(
                        "System alias parents must not be replaceable.",
                    ));
                }
            }
            return Ok(target.join(suffix));
        }
    }
    Ok(absolute)
}

/// The absolute form of `path`; this system has no aliased system roots.
#[cfg(not(target_os = "macos"))]
pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
    std::path::absolute(path)
}

/// Register now: an interrupt, termination request or controlling-terminal hangup stops work.
pub fn stop_requested() -> io::Result<impl Future<Output = ()> + Send + 'static> {
    let mut interrupt = signal(SignalKind::interrupt())?;
    let mut terminate = signal(SignalKind::terminate())?;
    let mut hangup = signal(SignalKind::hangup())?;
    Ok(async move {
        tokio::select! {
            _ = interrupt.recv() => {},
            _ = terminate.recv() => {},
            _ = hangup.recv() => {},
        }
    })
}

/// Turns terminal echo off until dropped, so a pasted secret is not shown.
pub struct HiddenInput(libc::termios);

impl HiddenInput {
    pub fn new() -> io::Result<Self> {
        let mut termios = std::mem::MaybeUninit::uninit();
        // SAFETY: tcgetattr fills the struct on success; it is read only then.
        let saved = unsafe {
            if libc::tcgetattr(libc::STDIN_FILENO, termios.as_mut_ptr()) != 0 {
                return Err(io::Error::last_os_error());
            }
            termios.assume_init()
        };
        let mut hidden = saved;
        hidden.c_lflag &= !libc::ECHO;
        // SAFETY: a valid termios for the same descriptor.
        if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &hidden) } != 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(Self(saved))
    }
}

impl Drop for HiddenInput {
    fn drop(&mut self) {
        // SAFETY: restores the attributes read in `new`.
        unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &self.0) };
    }
}

#[cfg(test)]
mod tests;