Skip to main content

artifactize_core/platform/
unix.rs

1//! Unix private file modes, process control, signals, and termios.
2//! Pinned file access lives in artifactize-tools.
3
4pub(crate) mod ipc;
5
6use std::{future::Future, io, path::Path};
7
8use tokio::signal::unix::{SignalKind, signal};
9
10pub(crate) use artifactize_foundation::platform::process::{
11    Child, hide_console_window, kill_saved_group, kill_saved_session, spawn_detached, spawn_gated,
12    spawn_run, spawn_watched,
13};
14
15/// Give the heap memory freed so far back to the system. glibc keeps freed memory in its
16/// arenas for reuse, so a long-lived process that once read much stays that large; macOS's
17/// allocator returns it by itself.
18pub(crate) fn release_free_memory() {
19    #[cfg(all(target_os = "linux", target_env = "gnu"))]
20    // SAFETY: malloc_trim only releases memory that is already free, under glibc's own locks.
21    unsafe {
22        libc::malloc_trim(0);
23    }
24}
25
26/// POSIX file locks are advisory, and unlinking a name never invalidates another handle's
27/// access to it, so a plain metadata or open race like Windows's never happens here.
28pub(crate) fn transient_file_access(_error: &io::Error) -> bool {
29    false
30}
31
32/// Permission bits granting access to group or other users.
33pub(crate) const GROUP_OTHER_BITS: u32 = 0o077;
34
35/// Group and other write bits permit system aliases or IPC parents to be replaced.
36const GROUP_OTHER_WRITE_BITS: u32 = 0o022;
37
38/// Environment variable names compare exactly.
39pub(crate) const ENV_NAMES_IGNORE_CASE: bool = false;
40
41/// The variable naming the user's home directory.
42pub(crate) const HOME_VARIABLES: &[&str] = &["HOME"];
43
44/// Variables programs read their temporary directory from. `TMP` and `TEMP` are set too, for
45/// programs written for Windows.
46pub(crate) const TEMP_VARIABLES: &[&str] = &["TMPDIR", "TMP", "TEMP"];
47
48/// Variables naming a per-user state directory, in order; artifactize keeps its state in an
49/// `artifactize` folder below the first one set, and otherwise below `HOME`.
50pub(crate) const STATE_VARIABLES: &[&str] = &["XDG_STATE_HOME"];
51
52/// The variables naming the signed-in user, in order.
53pub(crate) const USER_VARIABLES: &[&str] = &["USER", "LOGNAME"];
54
55/// The user's home directory.
56pub(crate) fn home_directory() -> Option<std::path::PathBuf> {
57    std::env::var_os(HOME_VARIABLES[0])
58        .filter(|path| !path.is_empty())
59        .map(Into::into)
60}
61
62/// A path from the raw bytes a tool such as git prints: any bytes name a Unix path.
63pub(crate) fn path_from_bytes(bytes: &[u8]) -> std::path::PathBuf {
64    use std::os::unix::ffi::OsStringExt;
65    std::ffi::OsString::from_vec(bytes.to_vec()).into()
66}
67
68/// Unix programs end a line with LF only.
69pub(crate) const CRLF_LINE_ENDINGS: bool = false;
70
71/// Whether a terminal that cannot hide input is still read, visibly, after a warning. A Unix
72/// terminal always can; failing to hide input is an error.
73pub const VISIBLE_INPUT_FALLBACK: bool = false;
74
75/// The operating system's host name, without depending on a proc filesystem.
76pub(crate) fn host_name() -> Option<String> {
77    hostname::get().ok()?.into_string().ok()
78}
79
80/// The absolute form of `path` with a leading macOS system alias (`/tmp`, `/var`, `/etc`)
81/// replaced by its fixed `/private` target. The alias and its parents must be root-owned
82/// and not replaceable; descendants are left for the caller to open without following links.
83#[cfg(target_os = "macos")]
84pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
85    use std::{fs, os::unix::fs::MetadataExt};
86    let absolute = std::path::absolute(path)?;
87    for name in ["tmp", "var", "etc"] {
88        let alias = Path::new("/").join(name);
89        if let Ok(suffix) = absolute.strip_prefix(&alias) {
90            let metadata = alias.symlink_metadata()?;
91            let target = Path::new("/private").join(name);
92            let link = fs::read_link(&alias)?;
93            let link = if link.is_absolute() {
94                link
95            } else {
96                Path::new("/").join(link)
97            };
98            if !metadata.is_symlink() || metadata.uid() != 0 || link != target {
99                return Err(io::Error::other(format!(
100                    "Refusing an untrusted system alias: {}",
101                    alias.display()
102                )));
103            }
104            for parent in [Path::new("/"), Path::new("/private")] {
105                let metadata = parent.symlink_metadata()?;
106                if !metadata.is_dir()
107                    || metadata.uid() != 0
108                    || metadata.mode() & GROUP_OTHER_WRITE_BITS != 0
109                {
110                    return Err(io::Error::other(
111                        "System alias parents must not be replaceable.",
112                    ));
113                }
114            }
115            return Ok(target.join(suffix));
116        }
117    }
118    Ok(absolute)
119}
120
121/// The absolute form of `path`; this system has no aliased system roots.
122#[cfg(not(target_os = "macos"))]
123pub(crate) fn resolve_system_aliases(path: &Path) -> io::Result<std::path::PathBuf> {
124    std::path::absolute(path)
125}
126
127/// Register now: an interrupt, termination request or controlling-terminal hangup stops work.
128pub fn stop_requested() -> io::Result<impl Future<Output = ()> + Send + 'static> {
129    let mut interrupt = signal(SignalKind::interrupt())?;
130    let mut terminate = signal(SignalKind::terminate())?;
131    let mut hangup = signal(SignalKind::hangup())?;
132    Ok(async move {
133        tokio::select! {
134            _ = interrupt.recv() => {},
135            _ = terminate.recv() => {},
136            _ = hangup.recv() => {},
137        }
138    })
139}
140
141/// Turns terminal echo off until dropped, so a pasted secret is not shown.
142pub struct HiddenInput(libc::termios);
143
144impl HiddenInput {
145    pub fn new() -> io::Result<Self> {
146        let mut termios = std::mem::MaybeUninit::uninit();
147        // SAFETY: tcgetattr fills the struct on success; it is read only then.
148        let saved = unsafe {
149            if libc::tcgetattr(libc::STDIN_FILENO, termios.as_mut_ptr()) != 0 {
150                return Err(io::Error::last_os_error());
151            }
152            termios.assume_init()
153        };
154        let mut hidden = saved;
155        hidden.c_lflag &= !libc::ECHO;
156        // SAFETY: a valid termios for the same descriptor.
157        if unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &hidden) } != 0 {
158            return Err(io::Error::last_os_error());
159        }
160        Ok(Self(saved))
161    }
162}
163
164impl Drop for HiddenInput {
165    fn drop(&mut self) {
166        // SAFETY: restores the attributes read in `new`.
167        unsafe { libc::tcsetattr(libc::STDIN_FILENO, libc::TCSANOW, &self.0) };
168    }
169}
170
171#[cfg(test)]
172mod tests;