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 artifactize_foundation::platform::private::{
43    FileIdentity, PRIVATE_DIRECTORY, PRIVATE_FILE, PrivateTempDir, create_private_dir,
44    create_private_dir_all, file_identity, is_owner_only, is_private_dir, is_private_file,
45    private_named_dir, private_options, private_tempdir_in, remove_tree, restrict_file, sync_dir,
46};
47pub(crate) use detached::{DetachedChild, spawn_detached, spawn_run, spawn_watched};
48pub use hidden_input::{SecretInput, secret_input, stdin_is_terminal};
49pub use os::HiddenInput;
50pub use os::stop_requested;
51pub(crate) use os::{
52    CRLF_LINE_ENDINGS, Child, ENV_NAMES_IGNORE_CASE, TEMP_VARIABLES, USER_VARIABLES,
53    hide_console_window, home_directory, host_name, ipc, kill_saved_group, kill_saved_session,
54    path_from_bytes, release_free_memory, resolve_system_aliases, spawn_gated,
55    transient_file_access,
56};
57
58/// A share in a large read's memory, such as an opened Run's: everyone who keeps part of the
59/// read keeps a share, declared after what it keeps so that it is dropped last. When the last
60/// share goes, the read's memory has been freed, and it is given back to the system then, once
61/// (see [`release_free_memory`]), rather than staying with a long-lived process.
62#[derive(Debug, Clone)]
63pub struct Footprint {
64    _release: std::sync::Arc<Release>,
65}
66
67impl Footprint {
68    pub(crate) fn new() -> Self {
69        Self {
70            _release: std::sync::Arc::new(Release),
71        }
72    }
73}
74
75#[derive(Debug)]
76struct Release;
77
78impl Drop for Release {
79    fn drop(&mut self) {
80        release_free_memory();
81    }
82}
83
84pub use artifactize_tools::launch::{ProcessEnd, ProcessOutcome};
85
86/// Poll contended process-shared file locks without blocking the async runtime;
87/// 25 ms keeps session sends and credential refreshes responsive without busy-waiting.
88pub(crate) const FILE_LOCK_RETRY_INTERVAL: std::time::Duration =
89    std::time::Duration::from_millis(25);
90
91pub(crate) use artifactize_tools::files::{
92    EntryName, FileKind, canonicalize, entry_kind, link_target, open_directory, open_entry,
93    open_no_follow, read_dir,
94};
95pub use artifactize_tools::files::{current_directory, open_nonblocking, path_text};
96
97/// The absolute local folder a `file:` URI names, by this OS's path rules (a drive letter
98/// or UNC host on Windows); `None` for another scheme, a remote host or a relative path.
99pub fn file_uri_path(uri: &str) -> Option<std::path::PathBuf> {
100    url::Url::parse(uri)
101        .ok()?
102        .to_file_path()
103        .ok()
104        .filter(|path| path.is_absolute())
105}
106
107/// The absolute folder a caller names; a relative one would resolve against this
108/// process's working directory, which the caller cannot see.
109pub fn absolute_folder(text: &str) -> Option<std::path::PathBuf> {
110    artifactize_tools::files::path_from_text(text)
111        .ok()
112        .filter(|path| path.is_absolute())
113}
114
115/// Whether lookup resolves to a directory, following native links and aliases.
116pub fn is_directory(path: &std::path::Path) -> bool {
117    path.is_dir()
118}
119
120/// Whether lookup resolves to an existing target. Other I/O errors leave it unknown.
121pub fn target_exists(path: &std::path::Path) -> std::io::Result<bool> {
122    paths::target_exists(path)
123}
124
125/// Whether native lookup reaches a regular file, following links and honoring the volume's
126/// name matching. Missing or inaccessible entries do not count.
127pub fn is_regular_file(path: &std::path::Path) -> bool {
128    path.is_file()
129}
130
131/// Open a caller-selected file, following links but never blocking on a special file.
132/// Returns `None` when the opened handle is not a regular file.
133pub fn open_regular_input(path: &std::path::Path) -> std::io::Result<Option<std::fs::File>> {
134    let file = open_nonblocking(path)?;
135    Ok(file.metadata()?.is_file().then_some(file))
136}
137
138pub use artifactize_foundation::platform::files::open_regular;
139
140/// The civil day on this machine at `instant`, using its offset at that instant (including
141/// daylight-saving changes). If the system cannot describe it, use the UTC date.
142pub(crate) fn local_day(instant: time::OffsetDateTime) -> time::Date {
143    let offset = chrono::DateTime::from_timestamp(instant.unix_timestamp(), instant.nanosecond())
144        .map(|utc| utc.with_timezone(&chrono::Local).offset().local_minus_utc())
145        .and_then(|seconds| time::UtcOffset::from_whole_seconds(seconds).ok())
146        .unwrap_or(time::UtcOffset::UTC);
147    instant.to_offset(offset).date()
148}
149
150/// Captured program text with terminal control codes removed.
151pub(crate) fn clean_program_text(bytes: &[u8]) -> String {
152    String::from_utf8(crate::runtime::clean_output(bytes)).expect("clean output is UTF-8")
153}
154
155/// A program's textual output, lossy only where its bytes are not UTF-8.
156pub fn output_text(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
157    String::from_utf8_lossy(bytes)
158}
159
160/// A program's textual output as lines ending in `\n`, whichever ending the program wrote.
161pub fn output_lines(bytes: &[u8]) -> String {
162    output_text(bytes).replace("\r\n", "\n")
163}
164
165/// An OS string (an argument, a file name) as Unicode text: `None` when it is not (non-UTF-8
166/// bytes on Unix, an unpaired UTF-16 unit on Windows).
167pub fn os_text(value: &std::ffi::OsStr) -> Option<&str> {
168    value.to_str()
169}
170
171/// A filesystem name for display when a lossless path key is not needed.
172pub(crate) fn display_name(value: &std::ffi::OsStr) -> String {
173    value.to_string_lossy().into_owned()
174}
175
176/// A captured output line, accepting either common ending even when the program
177/// (rather than the host) explicitly chose which ending to emit.
178pub(crate) fn output_line(bytes: &[u8]) -> &[u8] {
179    bytes
180        .strip_suffix(b"\r\n")
181        .or_else(|| bytes.strip_suffix(b"\n"))
182        .unwrap_or(bytes)
183}
184
185/// Decode one native tool path line. Unix paths may end in a literal carriage return;
186/// only Windows accepts CRLF as the line terminator rather than part of the path.
187pub(crate) fn path_from_line(bytes: &[u8]) -> std::path::PathBuf {
188    let path = if CRLF_LINE_ENDINGS {
189        bytes
190            .strip_suffix(b"\r\n")
191            .or_else(|| bytes.strip_suffix(b"\n"))
192            .unwrap_or(bytes)
193    } else {
194        bytes.strip_suffix(b"\n").unwrap_or(bytes)
195    };
196    path_from_bytes(path)
197}
198
199/// This system's directory for temporary files.
200pub(crate) fn temporary_directory() -> std::path::PathBuf {
201    std::env::temp_dir()
202}
203
204const STATE_HOME_OVERRIDE: &str = "ARTIFACTIZE_STATE_HOME";
205
206/// The environment variables consulted for state storage, in precedence order.
207pub(crate) fn state_home_variables() -> impl Iterator<Item = &'static str> {
208    std::iter::once(STATE_HOME_OVERRIDE)
209        .chain(os::STATE_VARIABLES.iter().copied())
210        .chain(os::HOME_VARIABLES.iter().copied())
211}
212
213/// Default state directory policy belongs with the platform's environment names.
214pub(crate) fn state_directory() -> Option<std::path::PathBuf> {
215    resolve_state_directory(
216        environment::var(STATE_HOME_OVERRIDE).map(Into::into),
217        os::STATE_VARIABLES
218            .iter()
219            .find_map(|name| environment::var(name).filter(|v| !v.is_empty()))
220            .map(Into::into),
221        home_directory(),
222    )
223}
224
225fn resolve_state_directory(
226    artifactize: Option<std::path::PathBuf>,
227    state: Option<std::path::PathBuf>,
228    home: Option<std::path::PathBuf>,
229) -> Option<std::path::PathBuf> {
230    artifactize
231        .filter(|p| !p.as_os_str().is_empty())
232        .or_else(|| {
233            state
234                .filter(|p| !p.as_os_str().is_empty())
235                .map(|p| p.join("artifactize"))
236        })
237        .or_else(|| {
238            home.filter(|p| !p.as_os_str().is_empty())
239                .map(|p| p.join(".local/state/artifactize"))
240        })
241}
242
243/// Printable user metadata, not an authenticated principal.
244pub(crate) fn user_name() -> Option<String> {
245    USER_VARIABLES
246        .iter()
247        .find_map(|name| environment::var_text(name).filter(|value| !value.is_empty()))
248}
249
250/// Strip one platform-supported script line ending and name the accepted endings.
251pub(crate) fn fingerprint_line_ending(stdout: &[u8]) -> (&[u8], &'static str) {
252    if CRLF_LINE_ENDINGS {
253        (
254            stdout
255                .strip_suffix(b"\r\n")
256                .or_else(|| stdout.strip_suffix(b"\n"))
257                .unwrap_or(stdout),
258            "LF or CRLF",
259        )
260    } else {
261        (stdout.strip_suffix(b"\n").unwrap_or(stdout), "LF")
262    }
263}
264
265/// Classify the final component without following links or Windows reparse points.
266pub(crate) fn path_kind(path: &std::path::Path) -> std::io::Result<FileKind> {
267    match (path.parent(), path.file_name()) {
268        (Some(parent), Some(name)) => entry_kind(&open_directory(parent)?, name),
269        _ => open_directory(path).map(|_| FileKind::Directory),
270    }
271}
272
273/// Decode an authored program before path inspection or native lookup. Legacy declarations
274/// can use a native Windows verbatim spelling, whose literal slashes must not be translated.
275pub(crate) fn program_path(command: &str) -> std::io::Result<std::path::PathBuf> {
276    #[cfg(windows)]
277    if command.starts_with(r"\\?\") {
278        return Ok(command.into());
279    }
280    artifactize_tools::files::path_from_text(command)
281}
282
283/// A declared program as reversible path text, using `/` in its readable spelling.
284pub(crate) fn program_text(command: &str) -> String {
285    program_path(command).map_or_else(|_| command.to_owned(), |path| path_text(&path))
286}
287
288/// Serialize a declared program as [`program_text`].
289pub(crate) fn serialize_program<S: serde::Serializer>(
290    command: &str,
291    serializer: S,
292) -> Result<S::Ok, S::Error> {
293    serializer.serialize_str(&program_text(command))
294}
295
296/// Render serialized path lists with portable separators, just like single saved paths.
297pub(crate) fn serialize_paths<S: serde::Serializer>(
298    paths: &[std::path::PathBuf],
299    serializer: S,
300) -> Result<S::Ok, S::Error> {
301    use serde::Serialize;
302    paths
303        .iter()
304        .map(path_text)
305        .collect::<Vec<_>>()
306        .serialize(serializer)
307}
308
309#[cfg(test)]
310#[path = "platform/tests/process.rs"]
311mod process_tests;
312#[cfg(test)]
313pub(crate) use process_tests::pipe_grace_armed;
314
315#[cfg(test)]
316#[path = "platform/tests/program.rs"]
317mod program_tests;
318
319#[cfg(test)]
320#[path = "platform/tests/private_directory.rs"]
321mod private_directory_tests;
322
323#[cfg(test)]
324#[path = "platform/tests/state_directory.rs"]
325mod state_directory_tests;
326
327mod console;
328pub use console::pause_after_help;
329
330mod interaction;
331pub use interaction::paths_equal;
332pub(crate) use interaction::{is_within, private_anonymous_file};
333
334/// Whether an entry exists without following links (including dangling links).
335pub(crate) fn entry_exists(path: &std::path::Path) -> std::io::Result<bool> {
336    let Some(parent) = path.parent() else {
337        return Ok(false);
338    };
339    let directory = match open_directory(parent) {
340        Ok(directory) => directory,
341        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
342        Err(error) => return Err(error),
343    };
344    let Some(name) = path.file_name() else {
345        return Ok(false);
346    };
347    match entry_kind(&directory, name) {
348        Ok(_) => Ok(true),
349        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
350        Err(error) => Err(error),
351    }
352}
353
354#[cfg(test)]
355#[path = "platform/tests/stop.rs"]
356mod stop_tests;