Skip to main content

thunderstore_engine/
steam.rs

1//! Host facts about the Steam client: where its executable lives, and whether it
2//! can resolve a path a caller hands it.
3//!
4//! # Locating the executable
5//!
6//! [`crate::steam::steam_exe`] answers "what program starts Steam on this
7//! machine". Steam is on `PATH` on Linux, so a bare `steam` is correct there,
8//! but its Windows installer adds nothing to `PATH`: `CreateProcess` appends
9//! `.exe` to a bare program name yet still has nowhere to look, so the spawn
10//! fails outright and the ordinary Steam configuration cannot launch at all.
11//!
12//! # Namespace visibility
13//!
14//! Steam's launch options are a string the caller never opens itself: it names
15//! a wrapper script and a target directory, and *Steam* is what has to resolve
16//! them. On a sandboxed Steam those are resolved in a different mount
17//! namespace, so a path that exists perfectly well for the caller can be
18//! absent for Steam. When that happens nothing on the caller's side fails,
19//! since `steam -applaunch` returns 0 either way, and the only record is a
20//! line in Steam's own console log. The launch simply appears to do nothing.
21//!
22//! This module makes that failure loud *before* a launch, by asking the running
23//! Steam client's own mount namespace whether it can see the path.
24//!
25//! This is host inspection, shared here in the engine rather than kept private
26//! to one client, because every client on Linux hits sandboxed Steam (Flatpak,
27//! Snap, containerized), and the failure mode is a launch that appears to do
28//! nothing, with the only record in Steam's own console log. Sharing the probe
29//! is worth the impurity of reading the host machine.
30
31#![deny(missing_docs)]
32
33use std::path::Path;
34#[cfg(feature = "io")]
35use std::path::{Component, PathBuf};
36
37/// Path prefixes a sandboxed Steam is known to replace with a private mount, used
38/// only when no running Steam client is available to ask directly.
39///
40/// These are per-namespace or per-boot scratch locations that no persistent game
41/// data belongs in regardless of Steam, so flagging them is honest even against an
42/// unsandboxed Steam that could in fact read them.
43const SUSPECT_PREFIXES: [&str; 4] = ["/tmp", "/var/tmp", "/dev/shm", "/run/user"];
44
45/// What was determined about Steam's ability to resolve a path.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Visibility {
48  /// Present in the running Steam client's mount namespace.
49  Reachable,
50  /// Proven absent from the running Steam client's mount namespace. A launch using
51  /// this path would fail inside Steam and report nowhere the caller can see.
52  Unreachable {
53    /// PID of the running Steam client whose mount namespace was inspected.
54    steam_pid: u32,
55  },
56  /// No running Steam client could be inspected, so nothing was proven. `suspect`
57  /// marks a path under a `SUSPECT_PREFIXES` entry, which is the shape of path
58  /// that fails once Steam *is* sandboxed.
59  Unknown {
60    /// Whether the path sits under a prefix a sandboxed Steam is known to
61    /// replace with a private mount.
62    suspect: bool,
63  },
64}
65
66/// How a caller should treat a [`Visibility`] verdict.
67///
68/// The mapping lives here so every client agrees on refuse-versus-warn; the
69/// wording of each refusal or warning is each client's own.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Severity {
72  /// Nothing to report.
73  Ok,
74  /// Report a warning but proceed: the suspicion is unconfirmed.
75  Warn,
76  /// Refuse: a live Steam client was inspected and genuinely lacks the path.
77  Refuse,
78}
79
80impl Visibility {
81  /// How a caller should treat this verdict.
82  ///
83  /// Only a proven absence refuses. An unproven suspicion warns, because
84  /// reporting it as a failure would be a claim the evidence does not support.
85  pub fn severity(&self) -> Severity {
86    match self {
87      Self::Reachable | Self::Unknown { suspect: false } => Severity::Ok,
88      Self::Unknown { suspect: true } => Severity::Warn,
89      Self::Unreachable { .. } => Severity::Refuse,
90    }
91  }
92}
93
94/// Whether `path` starts with a `SUSPECT_PREFIXES` entry.
95///
96/// Compared component-wise rather than as a string prefix, so `/tmpfoo` is not
97/// mistaken for something under `/tmp`.
98pub fn suspect_prefix(path: &Path) -> bool {
99  SUSPECT_PREFIXES
100    .iter()
101    .any(|prefix| starts_with_components(path, Path::new(prefix)))
102}
103
104/// Whether every component of `prefix`, in order, opens `path`.
105fn starts_with_components(path: &Path, prefix: &Path) -> bool {
106  let mut components = path.components();
107
108  for expected in prefix.components() {
109    match components.next() {
110      Some(actual) if actual == expected => {}
111      _ => return false,
112    }
113  }
114
115  true
116}
117
118/// Whether `path` resolves inside the filesystem rooted at `namespace_root`.
119///
120/// `namespace_root` is `/proc/<pid>/root` in real use, which the kernel resolves
121/// against that process's root, including absolute symlinks encountered along the
122/// way, so this genuinely answers "can that process open this path", not merely
123/// "does a similarly named file exist here". Taking the root as a parameter is also
124/// what makes the resolution testable against an ordinary directory tree.
125///
126/// `path`'s root, and on Windows its drive prefix, is dropped before joining,
127/// since [`Path::join`] with an absolute path discards the root it is joined onto.
128#[cfg(feature = "io")]
129fn visible_in(namespace_root: &Path, path: &Path) -> bool {
130  let relative: PathBuf = path
131    .components()
132    .filter(|component| !matches!(component, Component::Prefix(_) | Component::RootDir))
133    .collect();
134
135  namespace_root.join(relative).exists()
136}
137
138/// The running Steam client's pid, as Steam itself records it.
139///
140/// Read from `~/.steam/steam.pid`, which the client writes on startup, and
141/// accepted only if that pid currently belongs to a process named `steam`. A pid
142/// file outlives the process that wrote it, and a recycled pid would otherwise
143/// have us inspecting an unrelated namespace and reporting nonsense about it.
144#[cfg(feature = "io")]
145pub fn steam_client_pid() -> Option<u32> {
146  let home = std::env::var_os("HOME")?;
147  let pid_file = PathBuf::from(home).join(".steam").join("steam.pid");
148  let pid: u32 = std::fs::read_to_string(pid_file)
149    .ok()?
150    .trim()
151    .parse()
152    .ok()?;
153
154  let comm = std::fs::read_to_string(format!("/proc/{pid}/comm")).ok()?;
155
156  (comm.trim() == "steam").then_some(pid)
157}
158
159/// Whether the running Steam client can resolve `path`.
160///
161/// Returns [`Visibility::Unknown`] whenever no Steam client can be inspected, be
162/// that Steam not running, a platform without `/proc`, or an unreadable pid file,
163/// because an unproven suspicion must not be reported as a proven failure.
164#[cfg(feature = "io")]
165pub fn visibility(path: &Path) -> Visibility {
166  let Some(steam_pid) = steam_client_pid() else {
167    return Visibility::Unknown {
168      suspect: suspect_prefix(path),
169    };
170  };
171
172  let namespace_root = PathBuf::from(format!("/proc/{steam_pid}/root"));
173
174  // An unreadable namespace root proves nothing either way; only a readable one
175  // that lacks the path is evidence.
176  if !namespace_root.is_dir() {
177    return Visibility::Unknown {
178      suspect: suspect_prefix(path),
179    };
180  }
181
182  if visible_in(&namespace_root, path) {
183    return Visibility::Reachable;
184  }
185
186  Visibility::Unreachable { steam_pid }
187}
188
189/// The registry key Steam's Windows installer writes its own location into.
190#[cfg(feature = "io")]
191const STEAM_REGISTRY_KEY: &str = r"Software\Valve\Steam";
192
193/// The value under [`STEAM_REGISTRY_KEY`] holding the full path to `steam.exe`.
194#[cfg(feature = "io")]
195const STEAM_REGISTRY_VALUE: &str = "SteamExe";
196
197/// Environment variables naming the roots Steam installs under, in the order its
198/// installer prefers: a 32-bit application on 64-bit Windows lands in
199/// `Program Files (x86)`, and Steam is one.
200#[cfg(feature = "io")]
201const PROGRAM_FILES_VARS: [&str; 2] = ["ProgramFiles(x86)", "ProgramFiles"];
202
203/// The directory Steam creates under a Program Files root.
204#[cfg(feature = "io")]
205const STEAM_INSTALL_DIR: &str = "Steam";
206
207/// The Steam client executable's file name on Windows.
208#[cfg(feature = "io")]
209const STEAM_EXE_NAME: &str = "steam.exe";
210
211/// The program name used when no executable can be located.
212///
213/// Correct on Linux and macOS, where the client is on `PATH`, and no worse than a
214/// bare `steam` on a Windows host that has had Steam put on `PATH` by hand.
215#[cfg(feature = "io")]
216const STEAM_FALLBACK: &str = "steam";
217
218/// `steam.exe` under each root's `Steam` directory, in the order given.
219///
220/// Pure: proposes paths without touching the filesystem, so the preference order
221/// can be asserted on any host.
222#[cfg(feature = "io")]
223fn steam_exe_candidates(roots: &[PathBuf]) -> Vec<PathBuf> {
224  roots
225    .iter()
226    .map(|root| root.join(STEAM_INSTALL_DIR).join(STEAM_EXE_NAME))
227    .collect()
228}
229
230/// The first candidate that is a file, or `None` when none is.
231///
232/// Split out from where the candidates come from so the "which one wins"
233/// decision is testable against an ordinary directory tree, with no Windows and
234/// no Steam.
235#[cfg(feature = "io")]
236fn first_existing(candidates: &[PathBuf]) -> Option<PathBuf> {
237  candidates
238    .iter()
239    .find(|candidate| candidate.is_file())
240    .cloned()
241}
242
243/// The Program Files roots to search, read from the environment.
244///
245/// Guarded at run time rather than with `#[cfg(windows)]` so the resolution path
246/// stays compiled and unit-tested on a Linux CI, which is the only place this can
247/// be tested at all. The guard is load-bearing beyond that: Wine and some CI
248/// images export `ProgramFiles`, and honouring it off Windows would divert a
249/// working launch to a path that cannot be executed.
250#[cfg(feature = "io")]
251fn install_roots() -> Vec<PathBuf> {
252  if !cfg!(windows) {
253    return Vec::new();
254  }
255
256  PROGRAM_FILES_VARS
257    .iter()
258    .filter_map(std::env::var_os)
259    .map(PathBuf::from)
260    .collect()
261}
262
263/// The executable path Steam's installer recorded in the registry.
264///
265/// Preferred over the standard roots because it is the only source that survives
266/// a Steam installed to another drive. Steam writes this value with forward
267/// slashes, which Windows accepts.
268#[cfg(all(windows, feature = "io"))]
269fn registry_steam_exe() -> Option<PathBuf> {
270  let key = windows_registry::CURRENT_USER
271    .open(STEAM_REGISTRY_KEY)
272    .ok()?;
273  let recorded = key.get_string(STEAM_REGISTRY_VALUE).ok()?;
274
275  (!recorded.trim().is_empty()).then(|| PathBuf::from(recorded))
276}
277
278/// No registry to read. See the Windows implementation above.
279#[cfg(all(not(windows), feature = "io"))]
280fn registry_steam_exe() -> Option<PathBuf> {
281  // Referenced so the names stay live off Windows and cannot rot unnoticed.
282  let _ = (STEAM_REGISTRY_KEY, STEAM_REGISTRY_VALUE);
283
284  None
285}
286
287/// Chooses the Steam program from host facts already gathered.
288///
289/// The entire precedence rule, taking the registry value and the install roots as
290/// parameters rather than reading them, so every branch — registry hit, stale
291/// registry, roots order, nothing found at all — is exercised on a Linux CI. That
292/// matters more here than usual: the bug this resolution exists to fix only
293/// reproduces on Windows, which cannot be tested directly.
294///
295/// The registry path is re-checked against the filesystem rather than trusted, so
296/// a stale entry left behind by a moved or uninstalled Steam falls through to the
297/// standard roots instead of yielding a path that cannot be spawned.
298#[cfg(feature = "io")]
299fn resolve_steam_exe(registry: Option<PathBuf>, roots: &[PathBuf]) -> PathBuf {
300  registry
301    .filter(|path| path.is_file())
302    .or_else(|| first_existing(&steam_exe_candidates(roots)))
303    .unwrap_or_else(|| PathBuf::from(STEAM_FALLBACK))
304}
305
306/// The program that starts the Steam client on this machine.
307///
308/// Tries the registry, then the standard install roots, then falls back to a bare
309/// `STEAM_FALLBACK`. Resolution never fails: that fallback is exactly what this
310/// crate passed unconditionally before, so a machine this cannot resolve is left
311/// no worse off than it was.
312///
313/// [`crate::profile::launch::LaunchPlan::to_command`] calls this for
314/// [`crate::profile::launch::LaunchProgram::Steam`], so a caller spawning a
315/// computed plan gets it without asking. It is public for callers assembling a
316/// command themselves.
317#[cfg(feature = "io")]
318pub fn steam_exe() -> PathBuf {
319  resolve_steam_exe(registry_steam_exe(), &install_roots())
320}
321
322#[cfg(all(test, feature = "io"))]
323mod tests {
324  use super::*;
325  use tempfile::tempdir;
326
327  #[test]
328  fn suspect_prefix_matches_whole_components_only() {
329    assert!(suspect_prefix(Path::new(
330      "/tmp/t/d/valheim/steam-wrapper.sh"
331    )));
332    assert!(suspect_prefix(Path::new("/var/tmp/x")));
333    assert!(suspect_prefix(Path::new("/dev/shm/x")));
334    assert!(suspect_prefix(Path::new("/run/user/1000/x")));
335
336    assert!(!suspect_prefix(Path::new("/home/u/.local/share/vmm")));
337    assert!(!suspect_prefix(Path::new("/mnt/games/vmm")));
338
339    // A string-prefix check would wrongly flag these: neither is under /tmp.
340    assert!(!suspect_prefix(Path::new("/tmpfoo/x")));
341    assert!(!suspect_prefix(Path::new("/var/tmpfoo/x")));
342
343    // `/tmp` itself, and a relative path, are handled without panicking.
344    assert!(suspect_prefix(Path::new("/tmp")));
345    assert!(!suspect_prefix(Path::new("relative/path")));
346  }
347
348  #[test]
349  fn visible_in_resolves_an_absolute_path_under_the_namespace_root() {
350    let namespace = tempdir().unwrap();
351    let root = namespace.path();
352
353    std::fs::create_dir_all(root.join("home/u/.local/share/vmm/valheim")).unwrap();
354    std::fs::write(
355      root.join("home/u/.local/share/vmm/valheim/steam-wrapper.sh"),
356      b"#!/bin/sh\n",
357    )
358    .unwrap();
359
360    assert!(visible_in(
361      root,
362      Path::new("/home/u/.local/share/vmm/valheim/steam-wrapper.sh")
363    ));
364
365    // The namespace has no `/tmp` at all, exactly like a sandboxed Steam's.
366    assert!(!visible_in(
367      root,
368      Path::new("/tmp/t/d/valheim/steam-wrapper.sh")
369    ));
370
371    // A directory counts as visible: the wrapper's own check on the target is
372    // `[ -d ]`, not `[ -f ]`.
373    assert!(visible_in(root, Path::new("/home/u/.local/share/vmm")));
374  }
375
376  /// The root, and on Windows the drive prefix, has to be dropped: `Path::join`
377  /// with an absolute path discards the root it is joined onto, which would
378  /// silently check the *host* filesystem and call every path reachable.
379  #[test]
380  fn visible_in_does_not_fall_through_to_the_host_filesystem() {
381    let namespace = tempdir().unwrap();
382    let real = tempdir().unwrap();
383    let outside = real.path().join("wrapper.sh");
384
385    std::fs::write(&outside, b"#!/bin/sh\n").unwrap();
386
387    assert!(outside.exists(), "the file must exist on the host");
388    assert!(
389      !visible_in(namespace.path(), &outside),
390      "a host path must not be reported visible in a namespace that lacks it"
391    );
392  }
393
394  /// Whatever this machine's Steam state, a verdict is always produced and never
395  /// panics, and a home-directory path is never reported as proven unreachable.
396  #[test]
397  fn visibility_returns_a_verdict_without_panicking() {
398    let home = std::env::var("HOME").unwrap_or_else(|_| "/home".to_string());
399    let verdict = visibility(Path::new(&home));
400
401    assert!(
402      !matches!(verdict, Visibility::Unreachable { .. }),
403      "a home path should never be proven unreachable, got: {verdict:?}"
404    );
405  }
406
407  #[test]
408  fn steam_exe_candidates_names_steam_exe_under_each_root_in_order() {
409    let roots = vec![
410      PathBuf::from(r"C:\Program Files (x86)"),
411      PathBuf::from(r"C:\Program Files"),
412    ];
413
414    assert_eq!(
415      steam_exe_candidates(&roots),
416      vec![
417        PathBuf::from(r"C:\Program Files (x86)")
418          .join("Steam")
419          .join("steam.exe"),
420        PathBuf::from(r"C:\Program Files")
421          .join("Steam")
422          .join("steam.exe"),
423      ]
424    );
425
426    // No roots to search is not an error; it simply proposes nothing, which is
427    // what the caller sees on every non-Windows host.
428    assert!(steam_exe_candidates(&[]).is_empty());
429  }
430
431  #[test]
432  fn first_existing_returns_the_earliest_candidate_present_on_disk() {
433    let dir = tempdir().unwrap();
434    let root = dir.path();
435    let absent = root.join("absent.exe");
436    let present = root.join("present.exe");
437    let also_present = root.join("also_present.exe");
438
439    std::fs::write(&present, b"MZ").unwrap();
440    std::fs::write(&also_present, b"MZ").unwrap();
441
442    // Preference order decides, not disk order: the first *present* candidate
443    // wins even though an earlier one was looked for and missing.
444    assert_eq!(
445      first_existing(&[absent.clone(), present.clone(), also_present]),
446      Some(present)
447    );
448
449    assert_eq!(first_existing(&[absent]), None);
450
451    // A directory is not an executable, so it must not satisfy a candidate.
452    assert_eq!(first_existing(&[root.to_path_buf()]), None);
453  }
454
455  /// The precedence the Windows fix turns on, asserted end to end on a host that
456  /// has neither a registry nor a Steam. Each branch is reached by varying only
457  /// the two inputs.
458  #[test]
459  fn resolve_steam_exe_prefers_the_registry_then_the_roots_then_the_fallback() {
460    let dir = tempdir().unwrap();
461    let root = dir.path();
462
463    // A Steam relocated to another drive: only the registry knows about it, and
464    // it must win even when a standard root would also have resolved.
465    let relocated = root.join("D_drive").join("Steam").join("steam.exe");
466    let standard = root.join("ProgramFilesX86");
467    let secondary = root.join("ProgramFiles");
468
469    std::fs::create_dir_all(relocated.parent().unwrap()).unwrap();
470    std::fs::create_dir_all(standard.join("Steam")).unwrap();
471    std::fs::create_dir_all(secondary.join("Steam")).unwrap();
472    std::fs::write(&relocated, b"MZ").unwrap();
473    std::fs::write(standard.join("Steam").join("steam.exe"), b"MZ").unwrap();
474    std::fs::write(secondary.join("Steam").join("steam.exe"), b"MZ").unwrap();
475
476    let roots = vec![standard.clone(), secondary.clone()];
477
478    assert_eq!(
479      resolve_steam_exe(Some(relocated.clone()), &roots),
480      relocated,
481      "a registry-recorded Steam must win over a standard root"
482    );
483
484    assert_eq!(
485      resolve_steam_exe(None, &roots),
486      standard.join("Steam").join("steam.exe"),
487      "with no registry value the first root wins"
488    );
489
490    // A registry entry left behind by a moved or uninstalled Steam must not be
491    // handed back: spawning it would fail where the standard root would work.
492    assert_eq!(
493      resolve_steam_exe(Some(root.join("gone").join("steam.exe")), &roots),
494      standard.join("Steam").join("steam.exe"),
495      "a stale registry entry must fall through to the roots"
496    );
497
498    assert_eq!(
499      resolve_steam_exe(None, std::slice::from_ref(&secondary)),
500      secondary.join("Steam").join("steam.exe"),
501      "the second root resolves when it is the only one offered"
502    );
503
504    // Nothing resolvable is not an error. The bare name is what this crate always
505    // passed, and it still works wherever Steam is on PATH.
506    assert_eq!(
507      resolve_steam_exe(None, &[root.join("empty")]),
508      PathBuf::from("steam")
509    );
510    assert_eq!(resolve_steam_exe(None, &[]), PathBuf::from("steam"));
511  }
512
513  /// The whole resolution path stays compiled and exercised off Windows, so the
514  /// runtime guard is what keeps it inert there. `install_roots` is the only
515  /// route the environment takes into resolution, so a host that happens to
516  /// export `ProgramFiles` — Wine and some CI images do — cannot divert a launch
517  /// as long as this stays empty.
518  ///
519  /// Asserted by calling the shim rather than by setting the variable, because
520  /// the crate is `#![forbid(unsafe_code)]` and `std::env::set_var` is `unsafe`.
521  #[test]
522  fn resolution_is_inert_off_windows() {
523    if cfg!(windows) {
524      return;
525    }
526
527    assert!(
528      install_roots().is_empty(),
529      "no install roots may be proposed off Windows"
530    );
531    assert_eq!(
532      registry_steam_exe(),
533      None,
534      "there is no registry to read off Windows"
535    );
536    assert_eq!(
537      steam_exe(),
538      PathBuf::from("steam"),
539      "off Windows the bare program name is correct and must be preserved"
540    );
541  }
542
543  /// The Windows half of `resolution_is_inert_off_windows`: the registry read
544  /// and the Program Files roots run for real, and whatever the host holds, the
545  /// result is a file that exists or the bare fallback.
546  #[test]
547  #[cfg(windows)]
548  fn resolution_reads_the_host_on_windows() {
549    assert!(
550      !install_roots().is_empty(),
551      "Windows always exports a Program Files root"
552    );
553
554    let recorded = registry_steam_exe();
555    let resolved = steam_exe();
556
557    if let Some(recorded) = recorded.filter(|path| path.is_file()) {
558      assert_eq!(resolved, recorded, "a live registry entry must win");
559    }
560
561    assert!(
562      resolved.is_file() || resolved == Path::new("steam"),
563      "got {}",
564      resolved.display()
565    );
566  }
567
568  #[test]
569  fn only_a_proven_absence_refuses() {
570    assert_eq!(Visibility::Reachable.severity(), Severity::Ok);
571    assert_eq!(
572      Visibility::Unknown { suspect: false }.severity(),
573      Severity::Ok
574    );
575    assert_eq!(
576      Visibility::Unknown { suspect: true }.severity(),
577      Severity::Warn
578    );
579    assert_eq!(
580      Visibility::Unreachable { steam_pid: 1234 }.severity(),
581      Severity::Refuse
582    );
583  }
584}