Skip to main content

subspace_core/path/
resolve.rs

1//! Resolving the `PATH` once at startup and applying it to this process.
2
3use std::ffi::OsString;
4use std::path::PathBuf;
5use std::sync::OnceLock;
6use std::time::Duration;
7
8use chrono::{DateTime, Utc};
9
10use super::cache::{CachedPath, PathCache, read_cache};
11use super::capture::{Capture, joined};
12use super::entries::{distinct, merge, missing_variables};
13use super::fallback::{self, Probe, env_var};
14use super::{DISABLE_ENV, DISABLE_ENV_ALIAS, save, shell_timeout};
15
16/// Where the effective `PATH` came from, for display and diagnostics.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum Source {
19    /// The login shell at this path printed its `PATH`.
20    LoginShell(PathBuf),
21    /// The machine and user `Path` registry values (Windows).
22    Registry,
23    /// The inherited `PATH` was kept, with the reason.
24    Inherited(String),
25}
26
27impl Source {
28    pub fn describe(&self) -> String {
29        match self {
30            Source::LoginShell(shell) => format!("login shell {}", shell.display()),
31            Source::Registry => "Windows registry".to_string(),
32            Source::Inherited(reason) => format!("inherited ({reason})"),
33        }
34    }
35}
36
37/// A failed capture: what happened, and the reason text for
38/// [`Source::Inherited`].
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub(super) struct CaptureError {
41    pub(super) capture: Capture,
42    pub(super) message: String,
43}
44
45/// What the login shell or the registry reported.
46pub(super) struct Found {
47    pub(super) path: OsString,
48    pub(super) source: Source,
49    pub(super) capture: Capture,
50    pub(super) network: Vec<(String, String)>,
51}
52
53/// The outcome of [`apply`]: the merged `PATH` and how it was made.
54#[derive(Debug, Clone)]
55pub struct Resolved {
56    pub path: OsString,
57    pub source: Source,
58    /// Whether the login shell or the registry was asked, and the result.
59    pub capture: Capture,
60    /// Entries the capture, the saved `PATH` and the fallback folders added
61    /// to the inherited `PATH`.
62    pub added: usize,
63    /// The usual install folders ([`super::FALLBACK_DIRECTORIES`]) appended to
64    /// `path`, in order.
65    pub fallback: Vec<PathBuf>,
66    /// The saved `PATH`, when the shell failed and it was used.
67    pub cached: Option<CachedPath>,
68    /// Whether `path` differs from the inherited `PATH`, by new entries or
69    /// by order.
70    pub changed: bool,
71    /// Network variables the login shell sets and this process lacks.
72    pub network: Vec<(String, String)>,
73}
74
75impl Resolved {
76    fn inherited_path(path: OsString, reason: &str, capture: Capture) -> Self {
77        Self {
78            path,
79            source: Source::Inherited(reason.to_string()),
80            capture,
81            added: 0,
82            fallback: Vec::new(),
83            cached: None,
84            changed: false,
85            network: Vec::new(),
86        }
87    }
88
89    fn merged(path: OsString, found: Found, current: &OsString) -> Self {
90        Self {
91            added: distinct(&path).len() - distinct(current).len(),
92            changed: path != *current,
93            path,
94            source: found.source,
95            capture: found.capture,
96            fallback: Vec::new(),
97            cached: None,
98            network: missing_variables(found.network, |name| std::env::var_os(name).is_some()),
99        }
100    }
101
102    /// Append `directories` to `path`, and measure `added` and `changed`
103    /// against the inherited `current` again.
104    fn append(&mut self, directories: &[PathBuf], current: &OsString) {
105        if directories.is_empty() {
106            return;
107        }
108        let mut entries = distinct(&self.path);
109        entries.extend(directories.iter().cloned());
110        if let Ok(path) = std::env::join_paths(&entries) {
111            self.path = path;
112            self.added = distinct(&self.path)
113                .len()
114                .saturating_sub(distinct(current).len());
115            self.changed = self.path != *current;
116        }
117    }
118
119    /// Append the saved folders of `cache` that still exist.
120    fn use_cache(&mut self, cache: &PathCache, probe: &Probe<'_>, current: &OsString) {
121        let directories =
122            fallback::missing_directories(&distinct(&self.path), cache.path.clone(), probe);
123        self.append(&directories, current);
124        self.cached = Some(CachedPath {
125            saved_at: cache.saved_at,
126            source: cache.source.clone(),
127            version: cache.version.clone(),
128            added: directories.len(),
129        });
130    }
131
132    /// Whether the login shell or the registry was asked and failed.
133    pub fn capture_failed(&self) -> bool {
134        self.capture.failed()
135    }
136
137    /// What supplied the `PATH`: `login_shell`, `registry`, `terminal`,
138    /// `disabled`, or after a failed capture `cache` when saved folders were
139    /// added, else `fallback`.
140    pub fn path_from(&self) -> &'static str {
141        match &self.capture {
142            Capture::Captured { .. } => "login_shell",
143            Capture::Registry => "registry",
144            Capture::Terminal => "terminal",
145            Capture::Disabled => "disabled",
146            _ if self.cached.as_ref().is_some_and(|cached| cached.added > 0) => "cache",
147            _ => "fallback",
148        }
149    }
150
151    /// The fields of the `startup path` log record at `now`. `cache_age` is
152    /// whole seconds since the saved `PATH` was written, or `-`. The fields
153    /// name sources and appended folders and count entries and variables;
154    /// they never hold the `PATH` value or an environment variable, because
155    /// proxy variables can hold credentials.
156    pub fn log_fields(&self, now: DateTime<Utc>) -> Vec<(&'static str, String)> {
157        let cache_age = self.cached.as_ref().map_or_else(
158            || "-".to_string(),
159            |cached| (now - cached.saved_at).num_seconds().max(0).to_string(),
160        );
161        vec![
162            ("source", self.source.describe()),
163            ("capture", self.capture.label().to_string()),
164            (
165                "capture_seconds",
166                self.capture.seconds().unwrap_or_else(|| "-".to_string()),
167            ),
168            ("path_from", self.path_from().to_string()),
169            ("cache_age", cache_age),
170            ("added", self.added.to_string()),
171            ("fallback", joined(&self.fallback)),
172            ("changed", self.changed.to_string()),
173            ("network_variables", self.network.len().to_string()),
174        ]
175    }
176}
177
178/// What the host passes to [`apply`].
179#[derive(Debug, Clone)]
180pub struct Startup {
181    /// `<state dir>/path-cache.json` of the running product, or `None` to
182    /// neither read nor save a cache.
183    pub cache_file: Option<PathBuf>,
184    /// Ask the login shell even when started from a terminal.
185    pub force: bool,
186}
187
188static APPLIED: OnceLock<Resolved> = OnceLock::new();
189
190/// What [`apply`] set, if it ran.
191pub fn applied() -> Option<&'static Resolved> {
192    APPLIED.get()
193}
194
195static SEARCH_FOLDERS: OnceLock<Vec<PathBuf>> = OnceLock::new();
196
197/// The fallback folders `find_tool` searches, or `None` before [`apply`]
198/// ran. Tests that never apply the startup `PATH` therefore never search
199/// this computer's install folders.
200pub(super) fn search_folders() -> Option<&'static [PathBuf]> {
201    SEARCH_FOLDERS.get().map(Vec::as_slice)
202}
203
204/// Resolve the full `PATH`, set it and the missing network variables for
205/// this process, and save the `PATH` when it is known good.
206///
207/// # Safety
208///
209/// Call this before the process starts any other thread: it changes the
210/// process environment with `std::env::set_var`. The login-shell capture
211/// starts one reader thread. It joins that thread before it returns, also
212/// after a timeout, once the killed process group has closed the pipe. When
213/// a descendant left the group and still holds the pipe, the reader can
214/// still run; `apply` then changes no variable at all, so no other thread
215/// can observe a change.
216// qual:allow(complexity, unsafe) reason: "The host calls this before app threads exist; the shell reader is joined first, and when it cannot be joined the environment is left unchanged; Rust 2024 set_var is unsafe and child-only env does not update this process."
217pub unsafe fn apply(startup: Startup) -> &'static Resolved {
218    let cache = startup.cache_file.as_deref().and_then(read_cache);
219    let folders = fallback::startup_folders(&Probe::from_env(&env_var));
220    let resolved = resolve(startup.force, cache.as_ref(), folders.clone());
221    // SAFETY: the caller starts no thread before this; `reader_running`
222    // tells whether the shell reader could not be joined.
223    unsafe { set_environment(&resolved, reader_still_running()) };
224    let _ = SEARCH_FOLDERS.set(folders);
225    save::save(startup.cache_file, &resolved, cache, Utc::now());
226    APPLIED.get_or_init(|| resolved)
227}
228
229/// Set `PATH` and the missing network variables, unless the shell reader
230/// still runs (`reader_running`); then change nothing.
231///
232/// # Safety
233///
234/// No other thread may exist, apart from a reader that `reader_running`
235/// reports, which this function then leaves alone.
236// qual:allow(unsafe) reason: "Only apply calls this, before any thread exists and after the shell reader was joined; with a running reader nothing is changed."
237unsafe fn set_environment(resolved: &Resolved, reader_running: bool) {
238    if reader_running {
239        return;
240    }
241    if resolved.changed {
242        // SAFETY: no other thread exists: the caller starts none, and the
243        // shell reader has been joined.
244        unsafe { std::env::set_var("PATH", &resolved.path) };
245    }
246    for (name, value) in &resolved.network {
247        // SAFETY: as above.
248        unsafe { std::env::set_var(name, value) };
249    }
250}
251
252/// Work out the `PATH` a terminal would have. Without `force`, a process that
253/// runs in a terminal keeps its `PATH`, because it already has the shell's.
254fn resolve(force: bool, cache: Option<&PathCache>, folders: Vec<PathBuf>) -> Resolved {
255    resolve_with(Inputs {
256        current: std::env::var_os("PATH").unwrap_or_default(),
257        disabled: disabled_by(&env_var),
258        terminal: terminal_start(force),
259        capture: platform_path,
260        cache,
261        fallback: folders,
262        probe: Probe::from_env(&env_var),
263        inherited_first: cfg!(windows),
264    })
265}
266
267/// The variable that turns the capture off, when one is `0`.
268pub(super) fn disabled_by(lookup: &dyn Fn(&str) -> Option<String>) -> Option<&'static str> {
269    [DISABLE_ENV, DISABLE_ENV_ALIAS]
270        .into_iter()
271        .find(|name| lookup(name).as_deref() == Some("0"))
272}
273
274/// What [`resolve_with`] reads from the process and the file system.
275pub(super) struct Inputs<'a, C> {
276    pub(super) current: OsString,
277    pub(super) disabled: Option<&'static str>,
278    pub(super) terminal: bool,
279    pub(super) capture: C,
280    pub(super) cache: Option<&'a PathCache>,
281    /// The expanded fallback folders, existing or not.
282    pub(super) fallback: Vec<PathBuf>,
283    pub(super) probe: Probe<'a>,
284    /// Merge order of a successful capture: the inherited `PATH` first
285    /// (Windows registry), or the captured one first (login shell).
286    pub(super) inherited_first: bool,
287}
288
289/// A disabled or terminal resolution keeps `current` unchanged. Otherwise
290/// the capture leads (see [`captured`]). After a failed capture the saved
291/// folders that still exist follow; the fallback folders come last.
292pub(super) fn resolve_with<C>(inputs: Inputs<'_, C>) -> Resolved
293where
294    C: FnOnce(Duration) -> Result<Found, CaptureError>,
295{
296    let current = inputs.current;
297    if let Some(name) = inputs.disabled {
298        return Resolved::inherited_path(current, &format!("{name}=0"), Capture::Disabled);
299    }
300    if inputs.terminal {
301        return Resolved::inherited_path(current, "started from a terminal", Capture::Terminal);
302    }
303    let timeout = shell_timeout(inputs.cache.is_some());
304    let mut resolved = captured(
305        (inputs.capture)(timeout),
306        current.clone(),
307        inputs.inherited_first,
308    );
309    if resolved.capture_failed()
310        && let Some(cache) = inputs.cache
311    {
312        resolved.use_cache(cache, &inputs.probe, &current);
313    }
314    let directories =
315        fallback::missing_directories(&distinct(&resolved.path), inputs.fallback, &inputs.probe);
316    resolved.append(&directories, &current);
317    resolved.fallback = directories;
318    resolved
319}
320
321/// The `PATH` from a capture `outcome`, or `current` with the failure.
322fn captured(
323    outcome: Result<Found, CaptureError>,
324    current: OsString,
325    inherited_first: bool,
326) -> Resolved {
327    match outcome {
328        Ok(found) => {
329            // The login shell defines what a terminal has, so it leads. The
330            // registry only holds machine and user values, so on Windows the
331            // inherited PATH leads and keeps any directories a terminal or a
332            // launcher added for this session; the registry adds what is
333            // missing, such as a tool installed after sign-in.
334            let path = if inherited_first {
335                merge(&current, &found.path)
336            } else {
337                merge(&found.path, &current)
338            };
339            Resolved::merged(path, found, &current)
340        }
341        Err(error) => Resolved::inherited_path(current, &error.message, error.capture),
342    }
343}
344
345#[cfg(unix)]
346use super::shell::{platform_path, reader_still_running, terminal_start};
347
348#[cfg(windows)]
349use super::registry::platform_path;
350
351/// Windows needs no terminal check: the inherited PATH always leads there, so
352/// a terminal launch keeps its order and only gains missing registry entries.
353#[cfg(not(unix))]
354fn terminal_start(_force: bool) -> bool {
355    false
356}
357
358/// Only the Unix login-shell capture starts a reader thread.
359#[cfg(not(unix))]
360fn reader_still_running() -> bool {
361    false
362}
363
364/// Other platforms have no login shell or registry to ask.
365#[cfg(not(any(unix, windows)))]
366fn platform_path(_timeout: Duration) -> Result<Found, CaptureError> {
367    Err(CaptureError {
368        capture: Capture::Other {
369            reason: "unsupported platform".to_string(),
370        },
371        message: "unsupported platform".to_string(),
372    })
373}
374
375#[cfg(test)]
376mod log_tests;
377#[cfg(test)]
378mod tests;