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    artifactize_tools::files::path_from_text(text)
118        .ok()
119        .filter(|path| path.is_absolute())
120}
121
122/// Whether lookup resolves to a directory, following native links and aliases.
123pub fn is_directory(path: &std::path::Path) -> bool {
124    path.is_dir()
125}
126
127/// Whether lookup resolves to an existing target. Other I/O errors leave it unknown.
128pub fn target_exists(path: &std::path::Path) -> std::io::Result<bool> {
129    paths::target_exists(path)
130}
131
132/// Whether native lookup reaches a regular file, following links and honoring the volume's
133/// name matching. Missing or inaccessible entries do not count.
134pub fn is_regular_file(path: &std::path::Path) -> bool {
135    path.is_file()
136}
137
138/// Open a caller-selected file, following links but never blocking on a special file.
139/// Returns `None` when the opened handle is not a regular file.
140pub fn open_regular_input(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
141    let file = open_nonblocking(path)?;
142    Ok(file.metadata()?.is_file().then_some(file))
143}
144
145/// Open an existing regular file for reading without following a link in its last
146/// component (on Windows, any reparse point), and check what was opened.
147pub fn open_regular(path: &std::path::Path) -> std::io::Result<std::fs::File> {
148    let file = open_no_follow(std::fs::OpenOptions::new().read(true), path)?;
149    if file.metadata()?.is_file() {
150        Ok(file)
151    } else {
152        Err(std::io::Error::new(
153            std::io::ErrorKind::InvalidInput,
154            "not a regular file",
155        ))
156    }
157}
158
159/// The civil day on this machine at `instant`, using its offset at that instant (including
160/// daylight-saving changes). If the system cannot describe it, use the UTC date.
161pub(crate) fn local_day(instant: time::OffsetDateTime) -> time::Date {
162    let offset = chrono::DateTime::from_timestamp(instant.unix_timestamp(), instant.nanosecond())
163        .map(|utc| utc.with_timezone(&chrono::Local).offset().local_minus_utc())
164        .and_then(|seconds| time::UtcOffset::from_whole_seconds(seconds).ok())
165        .unwrap_or(time::UtcOffset::UTC);
166    instant.to_offset(offset).date()
167}
168
169/// Captured program text with terminal control codes removed.
170pub(crate) fn clean_program_text(bytes: &[u8]) -> String {
171    String::from_utf8(crate::runtime::clean_output(bytes)).expect("clean output is UTF-8")
172}
173
174/// A program's textual output, lossy only where its bytes are not UTF-8.
175pub fn output_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
176    String::from_utf8_lossy(bytes)
177}
178
179/// A program's textual output as lines ending in `\n`, whichever ending the program wrote.
180pub fn output_lines(bytes: &[u8]) -> String {
181    output_text(bytes).replace("\r\n", "\n")
182}
183
184/// An OS string (an argument, a file name) as Unicode text: `None` when it is not (non-UTF-8
185/// bytes on Unix, an unpaired UTF-16 unit on Windows).
186pub fn os_text(value: &std::ffi::OsStr) -> Option<&str> {
187    value.to_str()
188}
189
190/// A filesystem name for display when a lossless path key is not needed.
191pub(crate) fn display_name(value: &std::ffi::OsStr) -> String {
192    value.to_string_lossy().into_owned()
193}
194
195/// A captured output line, accepting either common ending even when the program
196/// (rather than the host) explicitly chose which ending to emit.
197pub(crate) fn output_line(bytes: &[u8]) -> &[u8] {
198    bytes
199        .strip_suffix(b"\r\n")
200        .or_else(|| bytes.strip_suffix(b"\n"))
201        .unwrap_or(bytes)
202}
203
204/// Decode one native tool path line. Unix paths may end in a literal carriage return;
205/// only Windows accepts CRLF as the line terminator rather than part of the path.
206pub(crate) fn path_from_line(bytes: &[u8]) -> std::path::PathBuf {
207    let path = if CRLF_LINE_ENDINGS {
208        bytes
209            .strip_suffix(b"\r\n")
210            .or_else(|| bytes.strip_suffix(b"\n"))
211            .unwrap_or(bytes)
212    } else {
213        bytes.strip_suffix(b"\n").unwrap_or(bytes)
214    };
215    path_from_bytes(path)
216}
217
218/// This system's directory for temporary files.
219pub(crate) fn temporary_directory() -> std::path::PathBuf {
220    std::env::temp_dir()
221}
222
223const STATE_HOME_OVERRIDE: &str = "ARTIFACTIZE_STATE_HOME";
224
225/// The environment variables consulted for state storage, in precedence order.
226pub(crate) fn state_home_variables() -> impl Iterator<Item = &'static str> {
227    std::iter::once(STATE_HOME_OVERRIDE)
228        .chain(os::STATE_VARIABLES.iter().copied())
229        .chain(os::HOME_VARIABLES.iter().copied())
230}
231
232/// Default state directory policy belongs with the platform's environment names.
233pub(crate) fn state_directory() -> Option<std::path::PathBuf> {
234    resolve_state_directory(
235        environment::var(STATE_HOME_OVERRIDE).map(Into::into),
236        os::STATE_VARIABLES
237            .iter()
238            .find_map(|name| environment::var(name).filter(|v| !v.is_empty()))
239            .map(Into::into),
240        home_directory(),
241    )
242}
243
244fn resolve_state_directory(
245    artifactize: Option<std::path::PathBuf>,
246    state: Option<std::path::PathBuf>,
247    home: Option<std::path::PathBuf>,
248) -> Option<std::path::PathBuf> {
249    artifactize
250        .filter(|p| !p.as_os_str().is_empty())
251        .or_else(|| {
252            state
253                .filter(|p| !p.as_os_str().is_empty())
254                .map(|p| p.join("artifactize"))
255        })
256        .or_else(|| {
257            home.filter(|p| !p.as_os_str().is_empty())
258                .map(|p| p.join(".local/state/artifactize"))
259        })
260}
261
262/// Printable user metadata, not an authenticated principal.
263pub(crate) fn user_name() -> Option<String> {
264    USER_VARIABLES
265        .iter()
266        .find_map(|name| environment::var_text(name).filter(|value| !value.is_empty()))
267}
268
269/// Strip one platform-supported script line ending and name the accepted endings.
270pub(crate) fn fingerprint_line_ending(stdout: &[u8]) -> (&[u8], &'static str) {
271    if CRLF_LINE_ENDINGS {
272        (
273            stdout
274                .strip_suffix(b"\r\n")
275                .or_else(|| stdout.strip_suffix(b"\n"))
276                .unwrap_or(stdout),
277            "LF or CRLF",
278        )
279    } else {
280        (stdout.strip_suffix(b"\n").unwrap_or(stdout), "LF")
281    }
282}
283
284/// Classify the final component without following links or Windows reparse points.
285pub(crate) fn path_kind(path: &std::path::Path) -> std::io::Result<FileKind> {
286    match (path.parent(), path.file_name()) {
287        (Some(parent), Some(name)) => entry_kind(&open_directory(parent)?, name),
288        _ => open_directory(path).map(|_| FileKind::Directory),
289    }
290}
291
292/// Decode an authored program before path inspection or native lookup. Legacy declarations
293/// can use a native Windows verbatim spelling, whose literal slashes must not be translated.
294pub(crate) fn program_path(command: &str) -> std::io::Result<std::path::PathBuf> {
295    #[cfg(windows)]
296    if command.starts_with(r"\\?\") {
297        return Ok(command.into());
298    }
299    artifactize_tools::files::path_from_text(command)
300}
301
302/// A declared program as reversible path text, using `/` in its readable spelling.
303pub(crate) fn program_text(command: &str) -> String {
304    program_path(command).map_or_else(|_| command.to_owned(), |path| path_text(&path))
305}
306
307/// Serialize a declared program as [`program_text`].
308pub(crate) fn serialize_program<S: serde::Serializer>(
309    command: &str,
310    serializer: S,
311) -> Result<S::Ok, S::Error> {
312    serializer.serialize_str(&program_text(command))
313}
314
315/// Render serialized path lists with portable separators, just like single saved paths.
316pub(crate) fn serialize_paths<S: serde::Serializer>(
317    paths: &[std::path::PathBuf],
318    serializer: S,
319) -> Result<S::Ok, S::Error> {
320    use serde::Serialize;
321    paths
322        .iter()
323        .map(path_text)
324        .collect::<Vec<_>>()
325        .serialize(serializer)
326}
327
328#[cfg(test)]
329mod process_tests;
330#[cfg(test)]
331pub(crate) use process_tests::pipe_grace_armed;
332
333#[cfg(test)]
334mod program_tests {
335    #[test]
336    fn a_declared_program_is_written_with_forward_slashes() {
337        assert_eq!(super::program_text("pnpm"), "pnpm");
338        assert_eq!(super::program_text("tools/run.sh"), "tools/run.sh");
339        // Windows interprets backslashes as separators; Unix permits them in filenames.
340        #[cfg(windows)]
341        assert_eq!(super::program_text(r"tools\run.cmd"), "tools/run.cmd");
342    }
343}
344
345#[cfg(test)]
346mod private_directory_tests {
347    use super::*;
348
349    #[test]
350    fn kept_temporary_directory_transfers_cleanup_responsibility() {
351        let parent = crate::test_os::tempdir();
352        let directory = private_tempdir_in("kept-", parent.path()).unwrap();
353        let path = directory.keep();
354        assert!(path.is_dir());
355        assert!(is_private_dir(&path).unwrap());
356        remove_tree(&path).unwrap();
357        assert!(!path.exists());
358    }
359}
360
361#[cfg(test)]
362mod state_directory_tests {
363    use super::*;
364    use std::path::PathBuf;
365
366    #[test]
367    fn state_home_precedence_and_empty_values() {
368        let artifactize = PathBuf::from("custom/state");
369        let state = PathBuf::from("state");
370        let home = PathBuf::from("reviewer");
371        assert_eq!(
372            resolve_state_directory(
373                Some(artifactize.clone()),
374                Some(state.clone()),
375                Some(home.clone())
376            ),
377            Some(artifactize)
378        );
379        assert_eq!(
380            resolve_state_directory(None, Some(state.clone()), Some(home.clone())),
381            Some(state.join("artifactize"))
382        );
383        assert_eq!(
384            resolve_state_directory(None, None, Some(home.clone())),
385            Some(home.join(".local/state/artifactize"))
386        );
387        let empty = Some(PathBuf::new());
388        assert_eq!(
389            resolve_state_directory(empty.clone(), empty.clone(), Some(home.clone())),
390            Some(home.join(".local/state/artifactize"))
391        );
392        assert_eq!(
393            resolve_state_directory(empty.clone(), empty.clone(), empty),
394            None
395        );
396        assert_eq!(resolve_state_directory(None, None, None), None);
397    }
398}
399
400mod console;
401pub use console::pause_after_help;
402
403mod interaction;
404pub use interaction::paths_equal;
405pub(crate) use interaction::{is_within, label, private_anonymous_file};
406
407/// Whether an entry exists without following links (including dangling links).
408pub(crate) fn entry_exists(path: &std::path::Path) -> std::io::Result<bool> {
409    let Some(parent) = path.parent() else {
410        return Ok(false);
411    };
412    let directory = match open_directory(parent) {
413        Ok(directory) => directory,
414        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
415        Err(error) => return Err(error),
416    };
417    let Some(name) = path.file_name() else {
418        return Ok(false);
419    };
420    match entry_kind(&directory, name) {
421        Ok(_) => Ok(true),
422        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
423        Err(error) => Err(error),
424    }
425}
426
427/// A no-follow stat of `path`. Unlike [`entry_exists`], this never opens `path`'s parent, so
428/// it still works on a search-only ancestor (executable but unreadable): opening a directory
429/// needs read permission on it, while naming one of its entries by an exact path needs only
430/// search (execute) permission on every ancestor up to it.
431pub(crate) fn marker_metadata(path: &std::path::Path) -> std::io::Result<std::fs::Metadata> {
432    path.symlink_metadata()
433}
434
435#[cfg(test)]
436pub(crate) fn successful_outcome() -> ProcessOutcome {
437    ProcessOutcome::from_native(std::process::ExitStatus::default())
438}
439
440#[cfg(test)]
441mod stop_tests {
442    use super::*;
443    use std::{path::PathBuf, time::Duration};
444
445    const READY: &str = "ARTIFACTIZE_TEST_STOP_PROBE_READY";
446    const WATCHDOG: Duration = Duration::from_secs(15);
447
448    #[tokio::test]
449    async fn a_terminal_interrupt_completes_stop_requested() {
450        let root = crate::test_os::tempdir();
451        let ready = root.path().join("ready");
452        let mut child = crate::test_os::test_command(
453            "platform::stop_tests::terminal_interrupt_probe",
454            &[(READY, ready.clone().into_os_string())],
455        );
456        crate::test_os::new_group(&mut child);
457        let mut child = crate::test_os::spawn_test(&mut tokio::process::Command::from(child));
458        crate::test_os::wait_until(WATCHDOG, || ready.is_file());
459        crate::test_os::interrupt(child.id());
460        assert!(child.wait().await.success());
461    }
462
463    #[tokio::test]
464    async fn terminal_interrupt_probe() {
465        let Some(ready) = crate::test_os::environment_variable(READY) else {
466            return;
467        };
468        let stop = stop_requested().unwrap();
469        std::fs::write(PathBuf::from(ready), "subscribed").unwrap();
470        stop.await;
471    }
472}