From 5613cde84eb406471603489ad401886b8f8cd7e4 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:46:38 -0500 Subject: [PATCH] fix(steam): confine engine file operations below their folder, and hold shared depots during an install - New safe_fs: every step below the install folder is opened relative to its parent's descriptor with O_NOFOLLOW (openat, mkdirat, renameat, unlinkat, symlinkat). The depot writer, resume verification, adoption of a client's staged files and shared-depot removal use it, so a symlink already there or swapped in mid-operation makes the step fail instead of reaching outside. A symlink inside the folder is no longer followed either. - An install holds the shared depots it relies on from planning until it returns, past the manifest write that lists them; an uninstall meanwhile keeps a held depot instead of removing it. Only unit-tested; not yet validated on a device. --- app/src/main/rust/stores/src/steam/NOTICE.md | 3 + .../rust/stores/src/steam/depot_writer.rs | 145 ++------- app/src/main/rust/stores/src/steam/install.rs | 3 + app/src/main/rust/stores/src/steam/mod.rs | 1 + .../main/rust/stores/src/steam/register.rs | 120 ++++--- app/src/main/rust/stores/src/steam/safe_fs.rs | 303 ++++++++++++++++++ 6 files changed, 416 insertions(+), 159 deletions(-) create mode 100644 app/src/main/rust/stores/src/steam/safe_fs.rs diff --git a/app/src/main/rust/stores/src/steam/NOTICE.md b/app/src/main/rust/stores/src/steam/NOTICE.md index 49256ab3e1..d23c321a54 100644 --- a/app/src/main/rust/stores/src/steam/NOTICE.md +++ b/app/src/main/rust/stores/src/steam/NOTICE.md @@ -44,6 +44,9 @@ Date of modification: 2026-11-07. KeyValues writer), `install` (download orchestration) and a new JNI layer (`jni`). - `library` records the depots the account's packages grant, and `plan` installs only those (the client skips the rest, e.g. edition-only depots); `plan` flags apps with a Linux build. +- New `safe_fs`: the depot writer, adoption of a client's staged files and shared-depot removal + open every path below their folder relative to its descriptor without following symlinks. + Installs hold the shared depots they rely on, so an uninstall in the meantime keeps them. - Not ported: QR and password sign-in, auth sessions, friends, chat and chat images, persona, lobbies, cloud, user stats, achievements, inventory, published files and workshop, app and ownership tickets, playing-session control, the Wine bridge, the other stores' downloaders, diff --git a/app/src/main/rust/stores/src/steam/depot_writer.rs b/app/src/main/rust/stores/src/steam/depot_writer.rs index f43a3a63c5..74c2e665de 100644 --- a/app/src/main/rust/stores/src/steam/depot_writer.rs +++ b/app/src/main/rust/stores/src/steam/depot_writer.rs @@ -13,9 +13,10 @@ use crate::steam::cdn; use crate::steam::content_manifest::{ChunkData, ContentManifest}; use crate::steam::depot_chunk::{process_depot_chunk, steam_adler_hash}; use crate::steam::pb::ccontentserverdirectory::CContentServerDirectoryServerInfo; +use crate::steam::safe_fs::Root; use sha1::{Digest, Sha1}; use std::collections::HashMap; -use std::fs::{self, File, OpenOptions}; +use std::fs::{self, File}; use std::path::{Component, Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; @@ -109,14 +110,16 @@ struct FileSlot { remaining: AtomicUsize, size: u64, path: PathBuf, + /// `path` below the install folder, as the manifest names it. + rel: PathBuf, mode: u32, } struct DepotFiles { slots: Vec, open_count: AtomicUsize, - /// The canonical target folder; every write must resolve beneath it. - root: PathBuf, + /// The install folder; every file is opened below it without following symlinks. + root: Root, } impl DepotFiles { @@ -126,14 +129,9 @@ impl DepotFiles { if let Some(file) = handle.as_ref() { return Ok(Arc::clone(file)); } - make_parent_dirs(&self.root, &slot.path)?; - check_file_target(&self.root, &slot.path)?; - let file = OpenOptions::new() - .create(true) - .write(true) - .read(true) - .truncate(false) - .open(&slot.path) + let file = self + .root + .open_rw(&slot.rel, slot.mode) .map_err(|err| format!("open '{}': {err}", slot.path.display()))?; set_file_mode(&file, &slot.path, slot.mode)?; let file = Arc::new(file); @@ -178,13 +176,9 @@ impl DepotFiles { /// Files with nothing left to fetch (zero chunks, or every chunk already correct on disk). fn finalize_untouched(&self, idx: usize) -> Result<(), String> { let slot = &self.slots[idx]; - make_parent_dirs(&self.root, &slot.path)?; - check_file_target(&self.root, &slot.path)?; - let file = OpenOptions::new() - .create(true) - .write(true) - .truncate(false) - .open(&slot.path) + let file = self + .root + .open_rw(&slot.rel, slot.mode) .map_err(|err| format!("open '{}': {err}", slot.path.display()))?; set_file_mode(&file, &slot.path, slot.mode)?; let current = file.metadata().map(|m| m.len()).unwrap_or(u64::MAX); @@ -260,17 +254,11 @@ fn prepare( bad.filename ))); } - if let Err(err) = fs::create_dir_all(request.target_dir) { - return Err(DepotWriteOutcome::fail(format!( - "mkdir '{}': {err}", - request.target_dir.display() - ))); - } - let root = match fs::canonicalize(request.target_dir) { + let root = match Root::open(request.target_dir, true) { Ok(root) => root, Err(err) => { return Err(DepotWriteOutcome::fail(format!( - "resolve '{}': {err}", + "open '{}': {err}", request.target_dir.display() ))) } @@ -280,9 +268,13 @@ fn prepare( let mut existing = Vec::with_capacity(manifest.files.len()); for file in &manifest.files { let path = request.target_dir.join(&file.filename); + let rel = PathBuf::from(&file.filename); let regular = is_regular(file.flags, &file.linktarget); let len = if regular { - fs::metadata(&path).map(|m| m.len()).unwrap_or(0) + root.open_read(&rel) + .and_then(|f| f.metadata()) + .map(|m| m.len()) + .unwrap_or(0) } else { 0 }; @@ -292,6 +284,7 @@ fn prepare( remaining: AtomicUsize::new(0), size: file.size, path, + rel, mode: if (file.flags & DEPOT_FILE_FLAG_EXECUTABLE) != 0 { 0o755 } else { @@ -319,11 +312,13 @@ fn prepare( } for file in &manifest.files { - let path = request.target_dir.join(&file.filename); + let rel = Path::new(&file.filename); let result = if !file.linktarget.is_empty() { - create_symlink(&root, &path, &file.linktarget) + root.symlink(rel, &file.linktarget) + .map_err(|err| format!("symlink '{}': {err}", file.filename)) } else if (file.flags & DEPOT_FILE_FLAG_DIRECTORY) != 0 { - make_dirs(&root, &path) + root.make_dirs(rel) + .map_err(|err| format!("mkdir '{}': {err}", file.filename)) } else { Ok(()) }; @@ -527,7 +522,7 @@ fn verify_existing( manifest: &ContentManifest, slots: &[FileSlot], existing: &[u64], - root: &Path, + root: &Root, workers: usize, cancel: &AtomicBool, ) -> Vec> { @@ -556,10 +551,7 @@ fn verify_existing( let Some(idx) = next else { return; }; - if check_file_target(root, &slots[idx].path).is_err() { - continue; - } - let Ok(file) = File::open(&slots[idx].path) else { + let Ok(file) = root.open_read(&slots[idx].rel) else { continue; }; let chunks = &manifest.files[idx].chunks; @@ -599,71 +591,6 @@ pub fn existing_chunk_matches(file: &File, file_len: u64, chunk: &ChunkData) -> steam_adler_hash(&buf) == chunk.crc } -/// Fails unless `path` (which must exist) resolves beneath `root`, so a symlink in the game folder -/// cannot carry a write outside it. -fn check_inside(root: &Path, path: &Path) -> Result<(), String> { - match fs::canonicalize(path) { - Ok(real) if real.starts_with(root) => Ok(()), - Ok(real) => Err(format!( - "'{}' resolves outside the install folder ({})", - path.display(), - real.display() - )), - Err(err) => Err(format!("resolve '{}': {err}", path.display())), - } -} - -/// Creates `dir` and its missing parents, refusing when an existing ancestor or the result -/// resolves outside `root`. -fn make_dirs(root: &Path, dir: &Path) -> Result<(), String> { - let mut existing = dir; - while fs::symlink_metadata(existing).is_err() { - match existing.parent() { - Some(parent) if !parent.as_os_str().is_empty() => existing = parent, - _ => break, - } - } - check_inside(root, existing)?; - fs::create_dir_all(dir).map_err(|err| format!("mkdir '{}': {err}", dir.display()))?; - check_inside(root, dir) -} - -fn make_parent_dirs(root: &Path, path: &Path) -> Result<(), String> { - match path.parent() { - Some(parent) if !parent.as_os_str().is_empty() => make_dirs(root, parent), - _ => Ok(()), - } -} - -/// A file about to be opened: its folder must be inside `root`, and if the path itself is a symlink -/// it must resolve inside `root` too (a dangling one would create its target wherever it points). -fn check_file_target(root: &Path, path: &Path) -> Result<(), String> { - if let Some(parent) = path.parent() { - check_inside(root, parent)?; - } - match fs::symlink_metadata(path) { - Ok(meta) if meta.file_type().is_symlink() => check_inside(root, path), - _ => Ok(()), - } -} - -fn create_symlink(root: &Path, path: &Path, target: &str) -> Result<(), String> { - make_parent_dirs(root, path)?; - if fs::symlink_metadata(path).is_ok() { - fs::remove_file(path).map_err(|err| format!("unlink '{}': {err}", path.display()))?; - } - #[cfg(unix)] - { - std::os::unix::fs::symlink(target, path) - .map_err(|err| format!("symlink '{}': {err}", path.display())) - } - #[cfg(not(unix))] - { - let _ = target; - Err(format!("symlink '{}': unsupported", path.display())) - } -} - #[cfg(unix)] fn set_file_mode(file: &File, path: &Path, mode: u32) -> Result<(), String> { use std::os::unix::fs::PermissionsExt; @@ -765,9 +692,10 @@ mod tests { remaining: AtomicUsize::new(0), size: 10, path: path.clone(), + rel: PathBuf::from(path.file_name().unwrap()), mode: 0o644, }]; - let root = fs::canonicalize(&dir).unwrap(); + let root = Root::open(&dir, false).unwrap(); let flags = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(false)); assert_eq!(flags, vec![vec![true, false]]); let cancelled = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(true)); @@ -929,7 +857,6 @@ mod tests { let _ = fs::remove_dir_all(&dir); } - #[cfg(unix)] #[test] fn refuses_writes_through_a_symlink_out_of_the_install_folder() { let base = std::env::temp_dir().join(format!( @@ -944,15 +871,13 @@ mod tests { fs::create_dir_all(&dir).unwrap(); fs::create_dir_all(&outside).unwrap(); std::os::unix::fs::symlink(&outside, dir.join("link")).unwrap(); - std::os::unix::fs::symlink("../game", dir.join("inner")).unwrap(); - let root = fs::canonicalize(&dir).unwrap(); - assert!(make_parent_dirs(&root, &dir.join("link/sub/f.bin")).is_err()); - assert!(!outside.join("sub").exists()); - assert!(check_file_target(&root, &dir.join("link/f.bin")).is_err()); - assert!(make_parent_dirs(&root, &dir.join("inner/sub/f.bin")).is_ok()); - assert!(check_file_target(&root, &dir.join("inner/sub/f.bin")).is_ok()); std::os::unix::fs::symlink(outside.join("x"), dir.join("dangling")).unwrap(); - assert!(check_file_target(&root, &dir.join("dangling")).is_err()); + let root = Root::open(&dir, false).unwrap(); + assert!(root.make_dirs(Path::new("link/sub")).is_err()); + assert!(root.open_rw(Path::new("link/f.bin"), 0o644).is_err()); + assert!(root.open_rw(Path::new("dangling"), 0o644).is_err()); + assert!(!outside.join("sub").exists() && !outside.join("f.bin").exists() && !outside.join("x").exists()); + assert!(root.open_rw(Path::new("sub/f.bin"), 0o644).is_ok()); let _ = fs::remove_dir_all(&base); } } diff --git a/app/src/main/rust/stores/src/steam/install.rs b/app/src/main/rust/stores/src/steam/install.rs index 5088ca591c..0f5cb1938e 100644 --- a/app/src/main/rust/stores/src/steam/install.rs +++ b/app/src/main/rust/stores/src/steam/install.rs @@ -179,6 +179,9 @@ pub fn run( if cancelled() { return fail("cancelled"); } + // Held until this run returns, past the final manifest write that records them as used. + let _shared_hold = + register::hold_shared(&plan.shared.iter().map(|d| d.depot_id).collect::>()); // Checked before takeover, which removes a half-finished client download's staging. if !register::library_registered(&req.steam_root, &req.game_library.guest) { return fail("library_not_in_libraryfolders"); diff --git a/app/src/main/rust/stores/src/steam/mod.rs b/app/src/main/rust/stores/src/steam/mod.rs index d2701e078a..00dfcc7fb7 100644 --- a/app/src/main/rust/stores/src/steam/mod.rs +++ b/app/src/main/rust/stores/src/steam/mod.rs @@ -31,6 +31,7 @@ pub mod plan; pub mod proto_envelope; pub mod proto_wire; pub mod register; +pub mod safe_fs; pub mod session; pub mod signin; pub mod steam_directory; diff --git a/app/src/main/rust/stores/src/steam/register.rs b/app/src/main/rust/stores/src/steam/register.rs index ca5d58938c..389cae846c 100644 --- a/app/src/main/rust/stores/src/steam/register.rs +++ b/app/src/main/rust/stores/src/steam/register.rs @@ -16,6 +16,7 @@ use crate::steam::content_manifest::ContentManifest; use crate::steam::kv; use crate::steam::plan::AppPlan; +use crate::steam::safe_fs::Root; use crate::steam::vdf::KVNode; use std::collections::HashSet; use std::fs; @@ -151,41 +152,16 @@ pub fn adopt_staged(library: &LibraryRoot, app_id: u32, install_dir: &str) -> us return 0; } let staging = library.steamapps().join("downloading").join(app_id.to_string()); - let target = library.common_dir(install_dir); - let mut moved = 0; - let mut pending = vec![staging.clone()]; - while let Some(dir) = pending.pop() { - let Ok(entries) = fs::read_dir(&dir) else { - continue; - }; - for entry in entries.flatten() { - let path = entry.path(); - let Ok(meta) = fs::symlink_metadata(&path) else { - continue; - }; - if meta.is_dir() { - pending.push(path); - continue; - } - if !meta.is_file() { - continue; - } - let Ok(rel) = path.strip_prefix(&staging) else { - continue; - }; - let dest = target.join(rel); - if fs::symlink_metadata(&dest).is_ok() { - continue; - } - let Some(parent) = dest.parent() else { - continue; - }; - if fs::create_dir_all(parent).is_ok() && fs::rename(&path, &dest).is_ok() { - moved += 1; - } - } - } - moved + let Ok(from) = Root::open(&staging, false) else { + return 0; + }; + let Ok(to) = Root::open(&library.common_dir(install_dir), true) else { + return 0; + }; + from.files() + .iter() + .filter(|rel| from.move_new(rel, &to, rel).unwrap_or(false)) + .count() } #[derive(Clone, Debug, Eq, PartialEq)] @@ -413,6 +389,46 @@ fn set_default(node: &mut KVNode, key: &str, value: &str) { /// Records a shared depot in its app's manifest (creating the manifest when the app has none /// yet), as the client does: `InstalledDepots`, `InstallScripts`, `SizeOnDisk`. +/// Shared depots an install in progress relies on, with how many installs hold each. An +/// uninstall leaves a held depot in place, from the moment an install sees it until its manifest, +/// which lists the depot under `SharedDepots`, is written. +static SHARED_HELD: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +pub struct SharedHold(Vec); + +pub fn hold_shared(depots: &[u32]) -> SharedHold { + let mut held = SHARED_HELD.lock().unwrap_or_else(|p| p.into_inner()); + for depot in depots { + match held.iter_mut().find(|(id, _)| id == depot) { + Some((_, count)) => *count += 1, + None => held.push((*depot, 1)), + } + } + SharedHold(depots.to_vec()) +} + +impl Drop for SharedHold { + fn drop(&mut self) { + let mut held = SHARED_HELD.lock().unwrap_or_else(|p| p.into_inner()); + for depot in &self.0 { + if let Some(pos) = held.iter().position(|(id, _)| id == depot) { + held[pos].1 -= 1; + if held[pos].1 == 0 { + held.remove(pos); + } + } + } + } +} + +pub fn shared_held(depot: u32) -> bool { + SHARED_HELD + .lock() + .unwrap_or_else(|p| p.into_inner()) + .iter() + .any(|(id, _)| *id == depot) +} + /// Serializes read-modify-write of a shared app's manifest between installs and uninstalls. static SHARED_ACF_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -748,6 +764,9 @@ fn remove_shared_depot( let _guard = SHARED_ACF_LOCK .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); + if shared_held(depot_id) { + return Ok(false); + } let Some(lib) = libraries.iter().find(|l| l.acf_path(from_app).exists()) else { return Ok(false); }; @@ -765,8 +784,7 @@ fn remove_shared_depot( let Some(files) = shared_files(from_app, depot_id, manifest_id) else { return Ok(false); }; - let base = lib.common_dir(&install_dir); - let Ok(real_base) = fs::canonicalize(&base) else { + let Ok(base) = Root::open(&lib.common_dir(&install_dir), false) else { return Ok(false); }; let mut removed_any = false; @@ -774,18 +792,11 @@ fn remove_shared_depot( if !crate::steam::depot_writer::path_is_safe(&rel) { continue; } - let target = base.join(&rel); - // The final component is unlinked without following it; its folder must resolve inside - // the shared app's folder, so a linked ancestor cannot send the removal elsewhere. - let inside = target - .parent() - .and_then(|parent| fs::canonicalize(parent).ok()) - .is_some_and(|parent| parent.starts_with(&real_base)); - if !inside { - continue; - } - if fs::symlink_metadata(&target).is_ok_and(|m| !m.is_dir()) { - match fs::remove_file(&target) { + let rel = Path::new(&rel); + // Walked below the shared app's folder without following links; a linked folder on the + // way leaves the file alone. The file itself is unlinked, never followed. + if base.kind(rel).ok().flatten().is_some_and(|kind| kind != libc::S_IFDIR) { + match base.remove_file(rel) { Ok(()) => removed_any = true, Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} // Untouched, the depot stays recorded so a later uninstall can retry. Once files @@ -1250,4 +1261,15 @@ mod tests { assert_eq!(adopt_staged(&library, 42, "Game"), 0); let _ = fs::remove_dir_all(&dir); } + + #[test] + fn a_held_shared_depot_counts_holds() { + assert!(!shared_held(999_001)); + let a = hold_shared(&[999_001]); + let b = hold_shared(&[999_001]); + drop(a); + assert!(shared_held(999_001)); + drop(b); + assert!(!shared_held(999_001)); + } } diff --git a/app/src/main/rust/stores/src/steam/safe_fs.rs b/app/src/main/rust/stores/src/steam/safe_fs.rs new file mode 100644 index 0000000000..d14db1a7f2 --- /dev/null +++ b/app/src/main/rust/stores/src/steam/safe_fs.rs @@ -0,0 +1,303 @@ +//! File operations confined to one folder. Every step below the folder is opened relative to its +//! parent's descriptor with `O_NOFOLLOW`, so a symlink anywhere on the way (one that was there +//! before, or one swapped in while we work) makes the operation fail instead of reaching outside. +//! A path check followed by a separate open would leave that window open. + +use std::ffi::CString; +use std::fs::File; +use std::io; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::ffi::OsStrExt; +use std::path::{Component, Path, PathBuf}; + +pub struct Root { + fd: OwnedFd, + path: PathBuf, +} + +fn cstr(name: &std::ffi::OsStr) -> io::Result { + CString::new(name.as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput)) +} + +fn check(ret: libc::c_int) -> io::Result { + if ret < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(ret) + } +} + +fn open_dir_at(dir: RawFd, name: &CString) -> io::Result { + let fd = check(unsafe { + libc::openat( + dir, + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + })?; + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) +} + +/// The plain names of `rel`; anything else (`..`, a root, a prefix) is refused. +fn names(rel: &Path) -> io::Result> { + rel.components() + .filter(|c| !matches!(c, Component::CurDir)) + .map(|c| match c { + Component::Normal(name) => cstr(name), + _ => Err(io::Error::from(io::ErrorKind::InvalidInput)), + }) + .collect() +} + +impl Root { + /// Opens (creating it if needed) the folder `path`. The folder itself may be reached through + /// symlinks (library aliases); only what is below it is confined. + pub fn open(path: &Path, create: bool) -> io::Result { + if create { + std::fs::create_dir_all(path)?; + } + let name = cstr(path.as_os_str())?; + let fd = check(unsafe { + libc::open( + name.as_ptr(), + libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, + ) + })?; + Ok(Root { + fd: unsafe { OwnedFd::from_raw_fd(fd) }, + path: path.to_path_buf(), + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// The folder holding `rel` (its last name returned beside it), each step opened without + /// following symlinks; missing folders are created when `create`. + fn parent(&self, rel: &Path, create: bool) -> io::Result<(OwnedFd, CString)> { + let mut parts = names(rel)?; + let last = parts + .pop() + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + let mut dir = self.fd.try_clone()?; + for part in parts { + dir = match open_dir_at(dir.as_raw_fd(), &part) { + Ok(next) => next, + Err(err) if create && err.raw_os_error() == Some(libc::ENOENT) => { + let made = unsafe { libc::mkdirat(dir.as_raw_fd(), part.as_ptr(), 0o755) }; + if made < 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() != Some(libc::EEXIST) { + return Err(err); + } + } + open_dir_at(dir.as_raw_fd(), &part)? + } + Err(err) => return Err(err), + }; + } + Ok((dir, last)) + } + + /// Creates the folder `rel` and its missing parents. + pub fn make_dirs(&self, rel: &Path) -> io::Result<()> { + let (dir, last) = self.parent(rel, true)?; + let made = unsafe { libc::mkdirat(dir.as_raw_fd(), last.as_ptr(), 0o755) }; + if made < 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() != Some(libc::EEXIST) { + return Err(err); + } + } + open_dir_at(dir.as_raw_fd(), &last).map(drop) + } + + /// Opens the file `rel` for reading and writing, creating it (and its folders) when missing. + pub fn open_rw(&self, rel: &Path, mode: u32) -> io::Result { + let (dir, last) = self.parent(rel, true)?; + let fd = check(unsafe { + libc::openat( + dir.as_raw_fd(), + last.as_ptr(), + libc::O_RDWR | libc::O_CREAT | libc::O_NOFOLLOW | libc::O_CLOEXEC, + mode as libc::c_uint, + ) + })?; + Ok(unsafe { File::from_raw_fd(fd) }) + } + + /// Opens the existing file `rel` for reading. + pub fn open_read(&self, rel: &Path) -> io::Result { + let (dir, last) = self.parent(rel, false)?; + let fd = check(unsafe { + libc::openat( + dir.as_raw_fd(), + last.as_ptr(), + libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + ) + })?; + Ok(unsafe { File::from_raw_fd(fd) }) + } + + /// The type of `rel` without following a final symlink; `None` when it does not exist. + pub fn kind(&self, rel: &Path) -> io::Result> { + let (dir, last) = match self.parent(rel, false) { + Ok(found) => found, + Err(err) if err.raw_os_error() == Some(libc::ENOENT) => return Ok(None), + Err(err) => return Err(err), + }; + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + let ret = unsafe { + libc::fstatat( + dir.as_raw_fd(), + last.as_ptr(), + &mut st, + libc::AT_SYMLINK_NOFOLLOW, + ) + }; + if ret < 0 { + let err = io::Error::last_os_error(); + return if err.raw_os_error() == Some(libc::ENOENT) { + Ok(None) + } else { + Err(err) + }; + } + Ok(Some(st.st_mode & libc::S_IFMT)) + } + + /// Replaces whatever is at `rel` (never following it) with a symlink to `target`. + pub fn symlink(&self, rel: &Path, target: &str) -> io::Result<()> { + let (dir, last) = self.parent(rel, true)?; + let unlinked = unsafe { libc::unlinkat(dir.as_raw_fd(), last.as_ptr(), 0) }; + if unlinked < 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() != Some(libc::ENOENT) { + return Err(err); + } + } + let target = CString::new(target).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + check(unsafe { libc::symlinkat(target.as_ptr(), dir.as_raw_fd(), last.as_ptr()) }).map(drop) + } + + /// Unlinks the file or symlink `rel` without following it. + pub fn remove_file(&self, rel: &Path) -> io::Result<()> { + let (dir, last) = self.parent(rel, false)?; + check(unsafe { libc::unlinkat(dir.as_raw_fd(), last.as_ptr(), 0) }).map(drop) + } + + /// Moves the regular file `rel` of this folder to `dest_rel` in `dest` when nothing is there yet. + /// Returns false when the destination exists or the source is not a regular file. + pub fn move_new(&self, rel: &Path, dest: &Root, dest_rel: &Path) -> io::Result { + if self.kind(rel)? != Some(libc::S_IFREG) || dest.kind(dest_rel)?.is_some() { + return Ok(false); + } + let (from, from_name) = self.parent(rel, false)?; + let (to, to_name) = dest.parent(dest_rel, true)?; + check(unsafe { + libc::renameat( + from.as_raw_fd(), + from_name.as_ptr(), + to.as_raw_fd(), + to_name.as_ptr(), + ) + })?; + Ok(true) + } + + /// Every regular file below this folder, as relative paths; symlinks are neither followed + /// nor listed. + pub fn files(&self) -> Vec { + let mut out = Vec::new(); + let mut pending = vec![PathBuf::new()]; + while let Some(rel) = pending.pop() { + let dir = if rel.as_os_str().is_empty() { + self.fd.try_clone().ok() + } else { + self.parent(&rel, false) + .and_then(|(parent, last)| open_dir_at(parent.as_raw_fd(), &last)) + .ok() + }; + let Some(dir) = dir else { + continue; + }; + let Ok(entries) = std::fs::read_dir(format!("/proc/self/fd/{}", dir.as_raw_fd())) else { + continue; + }; + for entry in entries.flatten() { + let child = rel.join(entry.file_name()); + match self.kind(&child) { + Ok(Some(libc::S_IFDIR)) => pending.push(child), + Ok(Some(libc::S_IFREG)) => out.push(child), + _ => {} + } + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn base(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("dd-safefs-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn creates_and_opens_below_the_folder() { + let dir = base("open"); + let root = Root::open(&dir.join("game"), true).unwrap(); + let mut f = root.open_rw(Path::new("a/b/c.bin"), 0o644).unwrap(); + std::io::Write::write_all(&mut f, b"x").unwrap(); + assert_eq!(fs::read(dir.join("game/a/b/c.bin")).unwrap(), b"x"); + assert!(root.open_read(Path::new("a/b/c.bin")).is_ok()); + assert_eq!(root.kind(Path::new("a/b")).unwrap(), Some(libc::S_IFDIR)); + assert_eq!(root.kind(Path::new("a/missing")).unwrap(), None); + assert!(root.open_rw(Path::new("../escape"), 0o644).is_err()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn never_follows_a_symlink_below_the_folder() { + let dir = base("links"); + let outside = dir.join("outside"); + fs::create_dir_all(&outside).unwrap(); + let root = Root::open(&dir.join("game"), true).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("game/link")).unwrap(); + std::os::unix::fs::symlink(outside.join("x"), dir.join("game/dangling")).unwrap(); + assert!(root.open_rw(Path::new("link/f.bin"), 0o644).is_err()); + assert!(root.make_dirs(Path::new("link/sub")).is_err()); + assert!(root.open_rw(Path::new("dangling"), 0o644).is_err()); + assert!(root.open_read(Path::new("link/f.bin")).is_err()); + assert!(!outside.join("f.bin").exists() && !outside.join("sub").exists() && !outside.join("x").exists()); + root.remove_file(Path::new("link")).unwrap(); + assert!(outside.is_dir()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn moves_files_between_folders_without_replacing() { + let dir = base("move"); + let from = Root::open(&dir.join("staging"), true).unwrap(); + let to = Root::open(&dir.join("game"), true).unwrap(); + from.open_rw(Path::new("sub/a.bin"), 0o644).unwrap(); + from.open_rw(Path::new("b.bin"), 0o644).unwrap(); + to.open_rw(Path::new("b.bin"), 0o644).unwrap(); + std::os::unix::fs::symlink("/etc", dir.join("staging/link")).unwrap(); + let mut files = from.files(); + files.sort(); + assert_eq!(files, vec![PathBuf::from("b.bin"), PathBuf::from("sub/a.bin")]); + assert!(from.move_new(Path::new("sub/a.bin"), &to, Path::new("sub/a.bin")).unwrap()); + assert!(!from.move_new(Path::new("b.bin"), &to, Path::new("b.bin")).unwrap()); + assert!(!from.move_new(Path::new("link"), &to, Path::new("link")).unwrap()); + assert!(dir.join("game/sub/a.bin").is_file()); + let _ = fs::remove_dir_all(&dir); + } +}