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(crate) mod desktop_app;
20pub use desktop_app::launch as launch_desktop;
21pub mod desktop_commands;
22mod detached;
23pub mod environment;
24mod executable;
25pub use executable::current_executable;
26mod hidden_input;
27pub(crate) mod install;
28pub(crate) mod net;
29pub(crate) mod path_serde;
30pub(crate) mod paths;
31pub(crate) mod program;
32#[cfg(unix)]
33mod unix;
34#[cfg(windows)]
35mod windows;
36
37#[cfg(unix)]
38use unix as os;
39#[cfg(windows)]
40use windows as os;
41
42pub(crate) use detached::{DetachedChild, spawn_detached, spawn_run, spawn_watched};
43pub use hidden_input::{SecretInput, secret_input, stdin_is_terminal};
44pub use os::HiddenInput;
45pub use os::stop_requested;
46pub(crate) use os::{
47    CRLF_LINE_ENDINGS, Child, ENV_NAMES_IGNORE_CASE, PrivateTempDir, TEMP_VARIABLES,
48    USER_VARIABLES, create_private_dir, create_private_dir_all, file_identity, hide_console_window,
49    home_directory, host_name, ipc, is_owner_only, is_private_dir, is_private_file,
50    kill_saved_group, kill_saved_session, path_from_bytes, private_named_dir, private_options,
51    private_tempdir_in, process_start_time, release_free_memory, remove_tree,
52    resolve_system_aliases, restrict_file, running_process_start_time, spawn_gated, spawn_now,
53    spawn_windowless, sync_dir, transient_file_access,
54};
55pub(crate) use os::{PRIVATE_DIRECTORY, PRIVATE_FILE};
56
57/// A share in a large read's memory, such as an opened Run's: everyone who keeps part of the
58/// read keeps a share, declared after what it keeps so that it is dropped last. When the last
59/// share goes, the read's memory has been freed, and it is given back to the system then, once
60/// (see [`release_free_memory`]), rather than staying with a long-lived process.
61#[derive(Debug, Clone)]
62pub struct Footprint {
63    _release: std::sync::Arc<Release>,
64}
65
66impl Footprint {
67    pub(crate) fn new() -> Self {
68        Self {
69            _release: std::sync::Arc::new(Release),
70        }
71    }
72}
73
74#[derive(Debug)]
75struct Release;
76
77impl Drop for Release {
78    fn drop(&mut self) {
79        release_free_memory();
80    }
81}
82
83/// A file's identity on its volume. Two open files with equal identities are the same file,
84/// whatever paths reached them; a replaced file gets a new identity.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
86pub(crate) struct FileIdentity {
87    volume: u64,
88    index: u64,
89}
90
91pub use artifactize_tools::launch::{ProcessEnd, ProcessOutcome};
92
93/// Poll contended process-shared file locks without blocking the async runtime;
94/// 25 ms keeps session sends and credential refreshes responsive without busy-waiting.
95pub(crate) const FILE_LOCK_RETRY_INTERVAL: std::time::Duration =
96    std::time::Duration::from_millis(25);
97
98pub(crate) use artifactize_tools::files::{
99    EntryName, FileKind, canonicalize, entry_kind, link_target, open_directory, open_entry,
100    open_no_follow, read_dir,
101};
102pub use artifactize_tools::files::{current_directory, open_nonblocking, path_text};
103
104/// The absolute local folder a `file:` URI names, by this OS's path rules (a drive letter
105/// or UNC host on Windows); `None` for another scheme, a remote host or a relative path.
106pub fn file_uri_path(uri: &str) -> Option<std::path::PathBuf> {
107    url::Url::parse(uri)
108        .ok()?
109        .to_file_path()
110        .ok()
111        .filter(|path| path.is_absolute())
112}
113
114/// The absolute folder a caller names; a relative one would resolve against this
115/// process's working directory, which the caller cannot see.
116pub fn absolute_folder(text: &str) -> Option<std::path::PathBuf> {
117    Some(std::path::PathBuf::from(text)).filter(|path| path.is_absolute())
118}
119
120/// Whether native lookup reaches a regular file, following links and honoring the volume's
121/// name matching. Missing or inaccessible entries do not count.
122pub fn is_regular_file(path: &std::path::Path) -> bool {
123    path.is_file()
124}
125
126/// Open a caller-selected file, following links but never blocking on a special file.
127/// Returns `None` when the opened handle is not a regular file.
128pub fn open_regular_input(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
129    let file = open_nonblocking(path)?;
130    Ok(file.metadata()?.is_file().then_some(file))
131}
132
133/// Open an existing regular file for reading without following a link in its last
134/// component (on Windows, any reparse point), and check what was opened.
135pub fn open_regular(path: &std::path::Path) -> std::io::Result<std::fs::File> {
136    let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
137    if file.metadata()?.is_file() {
138        Ok(file)
139    } else {
140        Err(std::io::Error::new(
141            std::io::ErrorKind::InvalidInput,
142            "not a regular file",
143        ))
144    }
145}
146
147/// A program's textual output, lossy only where its bytes are not UTF-8.
148pub fn output_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
149    String::from_utf8_lossy(bytes)
150}
151
152/// A program's textual output as lines ending in `\n`, whichever ending the program wrote.
153pub fn output_lines(bytes: &[u8]) -> String {
154    output_text(bytes).replace("\r\n", "\n")
155}
156
157/// An OS string (an argument, a file name) as Unicode text: `None` when it is not (non-UTF-8
158/// bytes on Unix, an unpaired UTF-16 unit on Windows).
159pub fn os_text(value: &std::ffi::OsStr) -> Option<&str> {
160    value.to_str()
161}
162
163/// A captured output line, accepting either common ending even when the program
164/// (rather than the host) explicitly chose which ending to emit.
165pub(crate) fn output_line(bytes: &[u8]) -> &[u8] {
166    bytes
167        .strip_suffix(b"\r\n")
168        .or_else(|| bytes.strip_suffix(b"\n"))
169        .unwrap_or(bytes)
170}
171
172/// Decode one native tool path line. Unix paths may end in a literal carriage return;
173/// only Windows accepts CRLF as the line terminator rather than part of the path.
174pub(crate) fn path_from_line(bytes: &[u8]) -> std::path::PathBuf {
175    let path = if CRLF_LINE_ENDINGS {
176        bytes
177            .strip_suffix(b"\r\n")
178            .or_else(|| bytes.strip_suffix(b"\n"))
179            .unwrap_or(bytes)
180    } else {
181        bytes.strip_suffix(b"\n").unwrap_or(bytes)
182    };
183    path_from_bytes(path)
184}
185
186/// This system's directory for temporary files.
187pub(crate) fn temporary_directory() -> std::path::PathBuf {
188    std::env::temp_dir()
189}
190
191const STATE_HOME_OVERRIDE: &str = "ARTIFACTIZE_STATE_HOME";
192
193/// The environment variables consulted for state storage, in precedence order.
194pub(crate) fn state_home_variables() -> impl Iterator<Item = &'static str> {
195    std::iter::once(STATE_HOME_OVERRIDE)
196        .chain(os::STATE_VARIABLES.iter().copied())
197        .chain(os::HOME_VARIABLES.iter().copied())
198}
199
200/// Default state directory policy belongs with the platform's environment names.
201pub(crate) fn state_directory() -> Option<std::path::PathBuf> {
202    resolve_state_directory(
203        environment::var(STATE_HOME_OVERRIDE).map(Into::into),
204        os::STATE_VARIABLES
205            .iter()
206            .find_map(|name| environment::var(name).filter(|v| !v.is_empty()))
207            .map(Into::into),
208        home_directory(),
209    )
210}
211
212fn resolve_state_directory(
213    artifactize: Option<std::path::PathBuf>,
214    state: Option<std::path::PathBuf>,
215    home: Option<std::path::PathBuf>,
216) -> Option<std::path::PathBuf> {
217    artifactize
218        .filter(|p| !p.as_os_str().is_empty())
219        .or_else(|| {
220            state
221                .filter(|p| !p.as_os_str().is_empty())
222                .map(|p| p.join("artifactize"))
223        })
224        .or_else(|| {
225            home.filter(|p| !p.as_os_str().is_empty())
226                .map(|p| p.join(".local/state/artifactize"))
227        })
228}
229
230/// Printable user metadata, not an authenticated principal.
231pub(crate) fn user_name() -> Option<String> {
232    USER_VARIABLES
233        .iter()
234        .find_map(|name| environment::var_text(name).filter(|value| !value.is_empty()))
235}
236
237/// Strip one platform-supported script line ending and name the accepted endings.
238pub(crate) fn fingerprint_line_ending(stdout: &[u8]) -> (&[u8], &'static str) {
239    if CRLF_LINE_ENDINGS {
240        (
241            stdout
242                .strip_suffix(b"\r\n")
243                .or_else(|| stdout.strip_suffix(b"\n"))
244                .unwrap_or(stdout),
245            "LF or CRLF",
246        )
247    } else {
248        (stdout.strip_suffix(b"\n").unwrap_or(stdout), "LF")
249    }
250}
251
252/// Classify the final component without following links or Windows reparse points.
253pub(crate) fn path_kind(path: &std::path::Path) -> std::io::Result<FileKind> {
254    match (path.parent(), path.file_name()) {
255        (Some(parent), Some(name)) => entry_kind(&open_directory(parent)?, name),
256        _ => open_directory(path).map(|_| FileKind::Directory),
257    }
258}
259
260/// A declared program as text: a path among its spellings is written with `/`.
261pub(crate) fn program_text(command: &str) -> String {
262    path_text(std::path::Path::new(command))
263}
264
265/// Serialize a declared program as [`program_text`].
266pub(crate) fn serialize_program<S: serde::Serializer>(
267    command: &str,
268    serializer: S,
269) -> Result<S::Ok, S::Error> {
270    serializer.serialize_str(&program_text(command))
271}
272
273/// Render serialized path lists with portable separators, just like single saved paths.
274pub(crate) fn serialize_paths<S: serde::Serializer>(
275    paths: &[std::path::PathBuf],
276    serializer: S,
277) -> Result<S::Ok, S::Error> {
278    use serde::Serialize;
279    paths
280        .iter()
281        .map(path_text)
282        .collect::<Vec<_>>()
283        .serialize(serializer)
284}
285
286#[cfg(test)]
287mod process_tests;
288#[cfg(test)]
289pub(crate) use process_tests::pipe_grace_armed;
290
291#[cfg(test)]
292mod program_tests {
293    #[test]
294    fn a_declared_program_is_written_with_forward_slashes() {
295        assert_eq!(super::program_text("pnpm"), "pnpm");
296        assert_eq!(super::program_text("tools/run.sh"), "tools/run.sh");
297        // Windows interprets backslashes as separators; Unix permits them in filenames.
298        #[cfg(windows)]
299        assert_eq!(super::program_text(r"tools\run.cmd"), "tools/run.cmd");
300    }
301}
302
303#[cfg(test)]
304mod private_directory_tests {
305    use super::*;
306
307    #[test]
308    fn kept_temporary_directory_transfers_cleanup_responsibility() {
309        let parent = crate::test_os::tempdir();
310        let directory = private_tempdir_in("kept-", parent.path()).unwrap();
311        let path = directory.keep();
312        assert!(path.is_dir());
313        assert!(is_private_dir(&path).unwrap());
314        remove_tree(&path).unwrap();
315        assert!(!path.exists());
316    }
317}
318
319#[cfg(test)]
320mod state_directory_tests {
321    use super::*;
322    use std::path::PathBuf;
323
324    #[test]
325    fn state_home_precedence_and_empty_values() {
326        let artifactize = PathBuf::from("custom/state");
327        let state = PathBuf::from("state");
328        let home = PathBuf::from("reviewer");
329        assert_eq!(
330            resolve_state_directory(
331                Some(artifactize.clone()),
332                Some(state.clone()),
333                Some(home.clone())
334            ),
335            Some(artifactize)
336        );
337        assert_eq!(
338            resolve_state_directory(None, Some(state.clone()), Some(home.clone())),
339            Some(state.join("artifactize"))
340        );
341        assert_eq!(
342            resolve_state_directory(None, None, Some(home.clone())),
343            Some(home.join(".local/state/artifactize"))
344        );
345        let empty = Some(PathBuf::new());
346        assert_eq!(
347            resolve_state_directory(empty.clone(), empty.clone(), Some(home.clone())),
348            Some(home.join(".local/state/artifactize"))
349        );
350        assert_eq!(
351            resolve_state_directory(empty.clone(), empty.clone(), empty),
352            None
353        );
354        assert_eq!(resolve_state_directory(None, None, None), None);
355    }
356}
357
358mod console;
359pub use console::pause_after_help;
360
361mod interaction;
362pub use interaction::paths_equal;
363pub(crate) use interaction::{is_within, label, private_anonymous_file};
364
365/// Whether an entry exists without following links (including dangling links).
366pub(crate) fn entry_exists(path: &std::path::Path) -> std::io::Result<bool> {
367    let Some(parent) = path.parent() else {
368        return Ok(false);
369    };
370    let directory = match open_directory(parent) {
371        Ok(directory) => directory,
372        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
373        Err(error) => return Err(error),
374    };
375    let Some(name) = path.file_name() else {
376        return Ok(false);
377    };
378    match entry_kind(&directory, name) {
379        Ok(_) => Ok(true),
380        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
381        Err(error) => Err(error),
382    }
383}
384
385/// A no-follow stat of `path`. Unlike [`entry_exists`], this never opens `path`'s parent, so
386/// it still works on a search-only ancestor (executable but unreadable): opening a directory
387/// needs read permission on it, while naming one of its entries by an exact path needs only
388/// search (execute) permission on every ancestor up to it.
389pub(crate) fn marker_metadata(path: &std::path::Path) -> std::io::Result<std::fs::Metadata> {
390    path.symlink_metadata()
391}
392
393#[cfg(test)]
394pub(crate) fn successful_outcome() -> ProcessOutcome {
395    ProcessOutcome::from_native(std::process::ExitStatus::default())
396}