Skip to main content

artifactize_core/
platform.rs

1//! Operating-system specifics behind one interface: owner-only files and directories, scoped
2//! opens and listings that never follow a link, process trees held until admitted, stop
3//! signals, hidden terminal input, and host details.
4//!
5//! Unix uses modes, `openat` with `O_NOFOLLOW`, `/proc`, and process groups. Windows uses
6//! protected owner-only DACLs, handle-relative opens that refuse every reparse point, and
7//! kill-on-close Job Objects.
8//!
9//! Kept as is (#201): process-wrap 10.0.1 is used for Unix process groups, but its Windows
10//! JobObject assigns a job after spawning and waits for the whole job, not just the leader.
11//! It exposes neither creation-time job assignment nor our separately owned admission gate;
12//! keep the current suspended-spawn/assignment and detached-launch policy on Windows.
13//! rpassword 7.5.4 exposes blocking password reads, not a caller-owned mode guard that can
14//! restore the terminal when a pending read is cancelled. Keep the echo-only guard and the
15//! bounded stdin reader; its restoration contract is tested in `hidden_input`.
16//! Program lookup and desktop-opener crate choices are documented in artifactize-tools'
17//! platform module, where those implementations live.
18
19pub mod environment;
20mod hidden_input;
21pub(crate) mod path_serde;
22pub(crate) mod paths;
23pub(crate) mod program;
24#[cfg(unix)]
25mod unix;
26#[cfg(windows)]
27mod windows;
28
29#[cfg(unix)]
30use unix as os;
31#[cfg(windows)]
32use windows as os;
33
34pub(crate) use os::{
35    CRLF_LINE_ENDINGS, Child, DEFAULT_EDITOR, ENV_NAMES_IGNORE_CASE, HOME_VARIABLE, HiddenInput,
36    PrivateTempDir, STATE_VARIABLES, TEMP_VARIABLES, USER_VARIABLES, VISIBLE_INPUT_FALLBACK,
37    create_private_dir, create_private_dir_all, editor, exit_signal, file_identity, home_directory,
38    host_name, ipc, is_owner_only, is_private_dir, is_private_file, kill_saved_group,
39    kill_saved_session, path_from_bytes, private_options, private_tempdir_in, process_start_time,
40    remove_abandoned_directory, resolve_system_aliases, restrict_file, running_process_start_time,
41    spawn_detached, spawn_gated, spawn_run, stop_requested, sync_dir, transient_file_access,
42};
43pub(crate) use os::{PRIVATE_DIRECTORY, PRIVATE_FILE};
44
45/// A file's identity on its volume. Two open files with equal identities are the same file,
46/// whatever paths reached them; a replaced file gets a new identity.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub(crate) struct FileIdentity {
49    volume: u64,
50    index: u64,
51}
52
53/// How a finished process ended.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub(crate) enum ProcessEnd {
56    /// It exited with this code.
57    Exited(i32),
58    /// It was ended without an exit code: on Unix by a signal, when known.
59    Signaled(Option<i32>),
60}
61
62/// How the process whose `status` this is ended.
63pub(crate) fn process_end(status: &std::process::ExitStatus) -> ProcessEnd {
64    match status.code() {
65        Some(code) => ProcessEnd::Exited(code),
66        None => ProcessEnd::Signaled(exit_signal(status)),
67    }
68}
69
70/// How a finished process ended, for a message: its exit code, or on Unix the signal that
71/// ended it, in the system's own wording.
72pub(crate) fn exit_description(status: &std::process::ExitStatus) -> String {
73    status.to_string()
74}
75
76/// Poll contended process-shared file locks without blocking the async runtime;
77/// 25 ms keeps session sends and credential refreshes responsive without busy-waiting.
78pub(crate) const FILE_LOCK_RETRY_INTERVAL: std::time::Duration =
79    std::time::Duration::from_millis(25);
80
81pub use artifactize_tools::files::path_text;
82pub(crate) use artifactize_tools::files::{
83    EntryName, FileKind, canonicalize, entry_kind, link_target, open_directory, open_entry,
84    open_no_follow, open_nonblocking, read_dir,
85};
86
87/// Open an existing regular file for reading without following a link in its last
88/// component (on Windows, any reparse point), and check what was opened.
89pub fn open_regular(path: &std::path::Path) -> std::io::Result<std::fs::File> {
90    let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
91    if file.metadata()?.is_file() {
92        Ok(file)
93    } else {
94        Err(std::io::Error::new(
95            std::io::ErrorKind::InvalidInput,
96            "not a regular file",
97        ))
98    }
99}
100
101/// Decode one native tool path line. Unix paths may end in a literal carriage return;
102/// only Windows accepts CRLF as the line terminator rather than part of the path.
103pub(crate) fn path_from_line(bytes: &[u8]) -> std::path::PathBuf {
104    let path = if CRLF_LINE_ENDINGS {
105        bytes
106            .strip_suffix(b"\r\n")
107            .or_else(|| bytes.strip_suffix(b"\n"))
108            .unwrap_or(bytes)
109    } else {
110        bytes.strip_suffix(b"\n").unwrap_or(bytes)
111    };
112    path_from_bytes(path)
113}
114
115/// Default state directory policy belongs with the platform's environment names.
116pub(crate) fn state_directory() -> Option<std::path::PathBuf> {
117    resolve_state_directory(
118        environment::var("ARTIFACTIZE_STATE_HOME").map(Into::into),
119        STATE_VARIABLES
120            .iter()
121            .find_map(|name| environment::var(name).filter(|v| !v.is_empty()))
122            .map(Into::into),
123        home_directory(),
124    )
125}
126
127fn resolve_state_directory(
128    artifactize: Option<std::path::PathBuf>,
129    state: Option<std::path::PathBuf>,
130    home: Option<std::path::PathBuf>,
131) -> Option<std::path::PathBuf> {
132    artifactize
133        .filter(|p| !p.as_os_str().is_empty())
134        .or_else(|| {
135            state
136                .filter(|p| !p.as_os_str().is_empty())
137                .map(|p| p.join("artifactize"))
138        })
139        .or_else(|| {
140            home.filter(|p| !p.as_os_str().is_empty())
141                .map(|p| p.join(".local/state/artifactize"))
142        })
143}
144
145/// Printable user metadata, not an authenticated principal.
146pub(crate) fn user_name() -> Option<String> {
147    USER_VARIABLES
148        .iter()
149        .find_map(|name| environment::var_text(name).filter(|value| !value.is_empty()))
150}
151
152/// Strip one platform-supported script line ending and name the accepted endings.
153pub(crate) fn fingerprint_line_ending(stdout: &[u8]) -> (&[u8], &'static str) {
154    if CRLF_LINE_ENDINGS {
155        (
156            stdout
157                .strip_suffix(b"\r\n")
158                .or_else(|| stdout.strip_suffix(b"\n"))
159                .unwrap_or(stdout),
160            "LF or CRLF",
161        )
162    } else {
163        (stdout.strip_suffix(b"\n").unwrap_or(stdout), "LF")
164    }
165}
166
167/// Classify the final component without following links or Windows reparse points.
168pub(crate) fn path_kind(path: &std::path::Path) -> std::io::Result<FileKind> {
169    match (path.parent(), path.file_name()) {
170        (Some(parent), Some(name)) => entry_kind(&open_directory(parent)?, name),
171        _ => open_directory(path).map(|_| FileKind::Directory),
172    }
173}
174
175/// Render serialized path lists with portable separators, just like single saved paths.
176pub(crate) fn serialize_paths<S: serde::Serializer>(
177    paths: &[std::path::PathBuf],
178    serializer: S,
179) -> Result<S::Ok, S::Error> {
180    use serde::Serialize;
181    paths
182        .iter()
183        .map(|path| path_text(path))
184        .collect::<Vec<_>>()
185        .serialize(serializer)
186}
187
188#[cfg(test)]
189mod state_directory_tests {
190    use super::*;
191    use std::path::PathBuf;
192
193    #[test]
194    fn state_home_precedence_and_empty_values() {
195        let artifactize = PathBuf::from("custom/state");
196        let state = PathBuf::from("state");
197        let home = PathBuf::from("reviewer");
198        assert_eq!(
199            resolve_state_directory(
200                Some(artifactize.clone()),
201                Some(state.clone()),
202                Some(home.clone())
203            ),
204            Some(artifactize)
205        );
206        assert_eq!(
207            resolve_state_directory(None, Some(state.clone()), Some(home.clone())),
208            Some(state.join("artifactize"))
209        );
210        assert_eq!(
211            resolve_state_directory(None, None, Some(home.clone())),
212            Some(home.join(".local/state/artifactize"))
213        );
214        let empty = Some(PathBuf::new());
215        assert_eq!(
216            resolve_state_directory(empty.clone(), empty.clone(), Some(home.clone())),
217            Some(home.join(".local/state/artifactize"))
218        );
219        assert_eq!(
220            resolve_state_directory(empty.clone(), empty.clone(), empty),
221            None
222        );
223        assert_eq!(resolve_state_directory(None, None, None), None);
224    }
225}
226
227mod console;
228pub(crate) use console::pause_after_help;
229
230mod interaction;
231pub use interaction::{PrivateTempFile, private_temp_file, run_editor, selected_editor};
232pub(crate) use interaction::{is_within, label, paths_equal, private_anonymous_file};
233
234/// Whether an entry exists without following links (including dangling links).
235pub(crate) fn entry_exists(path: &std::path::Path) -> std::io::Result<bool> {
236    let Some(parent) = path.parent() else {
237        return Ok(false);
238    };
239    let directory = match open_directory(parent) {
240        Ok(directory) => directory,
241        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
242        Err(error) => return Err(error),
243    };
244    let Some(name) = path.file_name() else {
245        return Ok(false);
246    };
247    match entry_kind(&directory, name) {
248        Ok(_) => Ok(true),
249        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
250        Err(error) => Err(error),
251    }
252}
253
254/// A no-follow stat of `path`. Unlike [`entry_exists`], this never opens `path`'s parent, so
255/// it still works on a search-only ancestor (executable but unreadable): opening a directory
256/// needs read permission on it, while naming one of its entries by an exact path needs only
257/// search (execute) permission on every ancestor up to it.
258pub(crate) fn marker_metadata(path: &std::path::Path) -> std::io::Result<std::fs::Metadata> {
259    path.symlink_metadata()
260}