Preserve independent mount data and allow external media cleanup

This commit is contained in:
Tobi Lutke
2026-09-26 21:58:23 -04:00
parent f3f37c27c4
commit 955108c13f
4 changed files with 418 additions and 44 deletions
+258 -24
View File
@@ -113,9 +113,10 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan {
for target in targets {
let path = normalize(&target.path);
let reason =
refuse(&path, &root, home.as_ref(), &mounts).or_else(|| {
linked(&path, &root, real_root.as_deref(), home.as_ref())
});
refuse(&path, &root, home.as_ref(), &mounts.points, &mounts.media)
.or_else(|| {
linked(&path, &root, real_root.as_deref(), home.as_ref())
});
if let Some(reason) = reason {
plan.blocked.push(Blocked {
path: target.path.clone(),
@@ -364,6 +365,7 @@ fn refuse(
root: &Path,
home: Option<&Home>,
mounts: &[PathBuf],
media: &[PathBuf],
) -> Option<String> {
let key = guard_key(path);
let root_key = guard_key(root);
@@ -414,7 +416,11 @@ fn refuse(
if !key.starts_with(&root_key) && !path.starts_with(root) {
return Some("outside the scanned root".into());
}
if let Some(system) = system_tree(&key, home_key) {
if let Some(system) = system_tree(&key, home_key)
&& !(system == "/run"
&& on_media(&key, mounts, media)
&& fs::canonicalize(path).is_ok_and(|real| real == path))
{
return Some(format!(
"part of the system under {system}: {SYSTEM_TOOLS}"
));
@@ -424,7 +430,7 @@ fn refuse(
"it contains {system}, which is part of the system"
));
}
if is_mount_point(path) {
if mounts.contains(&key) || is_mount_point(path) {
return Some(
"a mount point: removing it would cross onto another filesystem"
.into(),
@@ -533,10 +539,78 @@ const fn identity(_path: &Path, _follow: bool) -> Option<(u64, u64)> {
/// mount boundary whatever the table said.
const MOUNTS_FRESH: std::time::Duration = std::time::Duration::from_secs(2);
/// Paths and safe media exceptions must come from the same snapshot.
#[derive(Default)]
struct MountTable {
points: Vec<PathBuf>,
media: Vec<PathBuf>,
}
fn read_mount_table() -> MountTable {
if let Ok(table) = fs::read_to_string("/proc/self/mountinfo") {
let views = crate::space::parse_mountinfo(&table);
return MountTable {
points: views.iter().map(|mount| guard_key(&mount.point)).collect(),
media: media_roots(&views),
};
}
MountTable {
points: read_mount_points(),
media: Vec::new(),
}
}
/// Only real disks mounted by the desktop under /run/media qualify. A
/// directory with that spelling, a bind of a system tree, and virtual
/// filesystems retain the /run guard. Missing information fails closed.
fn media_roots(mounts: &[crate::space::MountView]) -> Vec<PathBuf> {
mounts
.iter()
.filter(|mount| {
mount.point.starts_with("/run/media")
&& mount.point != Path::new("/run/media")
&& mount.fs_root == Path::new("/")
&& mount.source.starts_with("/dev/")
&& matches!(
mount.fstype.as_str(),
"ext2"
| "ext3"
| "ext4"
| "btrfs"
| "xfs"
| "f2fs"
| "vfat"
| "exfat"
| "ntfs"
| "ntfs3"
| "fuseblk"
| "fuse.ntfs-3g"
)
&& !mounts.iter().any(|other| {
!other.point.starts_with("/run/media")
&& (other.point == Path::new("/")
|| system_tree(&other.point, None).is_some())
&& (other.device == mount.device
|| other.source == mount.source)
})
})
.map(|mount| mount.point.clone())
.collect()
}
fn on_media(key: &Path, mounts: &[PathBuf], media: &[PathBuf]) -> bool {
// Nested mounts do not inherit their parent's exception.
mounts
.iter()
.filter(|point| key.starts_with(point))
.max_by_key(|point| point.components().count())
.is_some_and(|point| key != point && media.contains(point))
}
/// The last read of the mount table, and whether a read is under way.
struct MountCache {
read: Option<std::time::Instant>,
mounts: Option<Arc<Vec<PathBuf>>>,
mounts: Option<Arc<MountTable>>,
refreshing: bool,
}
@@ -554,7 +628,7 @@ static MOUNTS: std::sync::Mutex<MountCache> =
/// its own thread and is used meanwhile; before the first read lands it is
/// empty, which is why the app primes it at start with
/// [`prime_mount_points`].
fn mount_points() -> Arc<Vec<PathBuf>> {
fn mount_points() -> Arc<MountTable> {
let mut cache = MOUNTS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -564,7 +638,7 @@ fn mount_points() -> Arc<Vec<PathBuf>> {
let spawned = thread::Builder::new()
.name("disktree-mounts".into())
.spawn(|| {
let mounts = Arc::new(read_mount_points());
let mounts = Arc::new(read_mount_table());
let mut cache = MOUNTS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -919,7 +993,7 @@ fn run(
// The plan was judged against a mount table up to `MOUNTS_FRESH` old,
// or, right after start, not read yet. Judged again against a fresh
// read, here on the worker, before anything is touched.
let mounts = read_mount_points();
let mounts = read_mount_table();
// Links too: one put on the way down since the plan was made would lead
// the trash out of the root. Permanent removal on Unix refuses that by
// itself; see [`open_parent`].
@@ -930,14 +1004,30 @@ fn run(
if cancel.load(Ordering::Relaxed) {
break;
}
let reason = mounted(&target.path, &mounts).or_else(|| {
linked(
&target.path,
&plan.root,
real_root.as_deref(),
home.as_ref(),
)
});
// The /run/media exception must still hold when removal starts;
// a disk may have been unmounted since the review was displayed.
let reason = target
.path
.starts_with("/run/media")
.then(|| {
refuse(
&target.path,
&plan.root,
home.as_ref(),
&mounts.points,
&mounts.media,
)
})
.flatten()
.or_else(|| mounted(&target.path, &mounts.points))
.or_else(|| {
linked(
&target.path,
&plan.root,
real_root.as_deref(),
home.as_ref(),
)
});
let outcome = if let Some(reason) = reason {
Err(io::Error::other(reason))
} else {
@@ -1469,6 +1559,129 @@ mod tests {
temp
}
#[cfg(target_os = "linux")]
#[test]
fn desktop_media_exception_requires_an_independent_disk() {
let views = crate::space::parse_mountinfo(
"1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 0:20 / /run rw - tmpfs tmpfs rw\n\
3 2 8:2 / /run/media/user/Games rw - ext4 /dev/sdb rw\n\
4 2 8:1 / /run/media/user/System rw - ext4 /dev/root rw\n\
5 2 8:2 /folder /run/media/user/Bind rw - ext4 /dev/sdb rw\n\
6 2 0:21 / /run/media/user/Virtual rw - tmpfs tmpfs rw\n\
7 3 8:1 /etc /run/media/user/Games/nested rw - ext4 /dev/root rw\n",
);
let media = media_roots(&views);
assert_eq!(media, [PathBuf::from("/run/media/user/Games")]);
let points: Vec<_> =
views.iter().map(|view| view.point.clone()).collect();
assert!(on_media(
Path::new("/run/media/user/Games/game"),
&points,
&media
));
for path in [
"/run/media/user/Games",
"/run/media/user/Games/nested/file",
"/run/media/user/System/etc",
"/run/media/user/Bind/file",
"/run/media/user/Virtual/file",
"/run/media/user/NotMounted/file",
"/run/user/1000/file",
] {
assert!(!on_media(Path::new(path), &points, &media), "{path}");
}
assert!(media_roots(&[]).is_empty());
}
/// Run in a private mount namespace with the fixture described in
/// scripts/test-linux-mounts.sh. Never changes the host's mount table.
#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires the isolated mount fixture"]
fn mounted_media_and_repeated_views() {
let table =
fs::read_to_string("/proc/self/mountinfo").expect("mountinfo");
assert!(
crate::space::parse_mountinfo(&table)
.iter()
.any(|mount| mount.point == Path::new("/run")
&& mount.source == "disktree-test-run")
);
let root = Path::new("/run/media/disktree-test");
let mounts = read_mount_points();
// User namespaces cannot mount a block device. Supply the media
// classification separately; the table-policy test above covers it.
let media = vec![root.to_path_buf()];
let file = root.join("game");
fs::write(&file, b"game").expect("fixture");
assert_eq!(refuse(&file, root, None, &mounts, &media), None);
assert!(refuse(root, Path::new("/"), None, &mounts, &media).is_some());
assert!(refuse(&file, root, None, &mounts, &[]).is_some());
std::os::unix::fs::symlink("/etc", root.join("link")).expect("link");
assert!(
refuse(
&root.join("link/passwd"),
&root.join("link"),
None,
&mounts,
&media
)
.is_some()
);
fs::write(root.join("nested/keep"), b"keep").expect("nested");
assert!(
refuse(&root.join("nested/keep"), root, None, &mounts, &media)
.is_some()
);
remove_permanently(&file, root).expect("delete marked game");
assert!(!file.exists());
assert!(root.join("nested/keep").exists());
let scan_root = Path::new("/run/disktree-scan");
let options = crate::scan::ScanOptions {
apparent_size: true,
one_filesystem: false,
..crate::scan::ScanOptions::default()
};
let tree = crate::scan::scan(scan_root, options.clone()).expect("scan");
for name in ["one", "two", "original"] {
assert!(
tree.children.iter().any(|child| &*child.name == name),
"{name}"
);
}
assert!(!tree.children.iter().any(|child| &*child.name == "alias"));
assert_eq!(tree.files, 3);
assert_eq!(tree.bytes, 12);
assert!(
std::process::Command::new("mount")
.args([
"-t",
"tmpfs",
"tmpfs",
"/run/disktree-scan/alias/nested"
])
.status()
.expect("nested mount")
.success()
);
fs::write(scan_root.join("alias/nested/unique"), b"unique")
.expect("unique");
let tree = crate::scan::scan(scan_root, options).expect("rescan");
let alias = tree
.children
.iter()
.find(|child| &*child.name == "alias")
.expect("alias retained");
assert!(
alias
.children
.iter()
.any(|child| &*child.name == "nested" && child.files == 1)
);
}
#[test]
fn a_plan_keeps_only_the_outermost_targets() {
let temp = tree();
@@ -1515,13 +1728,19 @@ mod tests {
fn the_directories_above_home_are_refused() {
let home = Home::of(Path::new("/home/disktree-test-user"));
let reason =
refuse(Path::new("/home"), Path::new("/"), Some(&home), &[]);
refuse(Path::new("/home"), Path::new("/"), Some(&home), &[], &[]);
assert!(
reason.is_some_and(|reason| reason.contains("home directory")),
"the home directory is inside it"
);
assert_eq!(
refuse(Path::new("/home/other"), Path::new("/"), Some(&home), &[]),
refuse(
Path::new("/home/other"),
Path::new("/"),
Some(&home),
&[],
&[]
),
None,
"a sibling of home is not above it"
);
@@ -1579,6 +1798,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
)
.expect("refused");
assert!(reason.contains("home directory"), "{reason}");
@@ -1587,6 +1807,7 @@ mod tests {
Path::new("/Users/tobi/src"),
Path::new("/"),
Some(&Home::of(home)),
&[],
&[]
)
.is_none(),
@@ -1605,6 +1826,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
)
.expect("refused");
assert!(reason.contains(inside), "{path}: {reason}");
@@ -1614,6 +1836,7 @@ mod tests {
Path::new("/opt/local"),
Path::new("/"),
Some(&Home::of(home)),
&[],
&[]
)
.is_none(),
@@ -1637,9 +1860,12 @@ mod tests {
"itself"
);
let reason =
refuse(&root.join("a"), root, None, &mounts).expect("refused");
refuse(&root.join("a"), root, None, &mounts, &[]).expect("refused");
assert!(reason.contains("mounted inside"), "{reason}");
assert_eq!(refuse(&root.join("a/one.bin"), root, None, &mounts), None);
assert_eq!(
refuse(&root.join("a/one.bin"), root, None, &mounts, &[]),
None
);
}
#[test]
@@ -1671,13 +1897,17 @@ mod tests {
// The first read lands on its own thread; wait for it, briefly.
let mut mounts = mount_points();
for _ in 0..500 {
if !mounts.is_empty() {
if !mounts.points.is_empty() {
break;
}
thread::sleep(std::time::Duration::from_millis(10));
mounts = mount_points();
}
assert_eq!(*mounts, read_mount_points(), "the same table, cached");
assert_eq!(
mounts.points,
read_mount_table().points,
"the same table, cached"
);
}
#[test]
@@ -1743,6 +1973,7 @@ mod tests {
&data.join("Users/tobi/src"),
data,
Some(&Home::of(home)),
&[],
&[]
)
.is_none(),
@@ -1753,6 +1984,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
)
.expect("refused");
assert!(reason.contains("/Library"), "{reason}");
@@ -2190,6 +2422,7 @@ mod tests {
&drive,
Some(&Home::of(&home)),
&[],
&[],
);
assert!(
reason.is_some_and(|reason| reason
@@ -2220,7 +2453,7 @@ mod tests {
let public = crate::windows::user_profiles_dir()
.expect("profiles folder")
.join("Public");
let reason = refuse(&public, &system_drive(), None, &[]);
let reason = refuse(&public, &system_drive(), None, &[], &[]);
assert!(reason.is_some_and(|reason| reason.contains("profile")));
}
@@ -2299,6 +2532,7 @@ mod tests {
Path::new("/"),
Some(&Home::of(home)),
&[],
&[],
);
assert!(reason.is_some_and(|reason| reason.contains("/etc")));
}
+11 -3
View File
@@ -750,10 +750,18 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
format!("{} is not a directory", root.display()),
));
}
let resolved = root.canonicalize().ok();
let resolved = root.canonicalize().ok();
let canonical = resolved.as_deref().unwrap_or(root);
let mut never = space::never_scanned(root, canonical);
never.extend(space::repeated_mounts_for(root, canonical));
let mut never = crate::space::never_scanned(root, canonical);
// Hidden-entry and depth filters can leave an alias as the only route
// to files. Keep every mount view when either filter is active.
if context.options.include_hidden && context.options.max_depth.is_none() {
never.extend(crate::space::repeated_mounts_for(
root,
canonical,
context.options.one_filesystem,
));
}
let _ = context.never_scanned.set(never.into_iter().collect());
if context.options.one_filesystem {
*lock(&context.root_device) = Some(device_of(&root_meta));
+131 -17
View File
@@ -229,6 +229,8 @@ pub fn foreign_mounts_for(root: &Path) -> Option<Vec<PathBuf>> {
/// mount from the filesystem itself.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MountView {
/// Kernel filesystem identity; source names such as `tmpfs` repeat.
pub device: String,
pub source: String,
pub fstype: String,
pub point: PathBuf,
@@ -246,13 +248,15 @@ pub fn parse_mountinfo(table: &str) -> Vec<MountView> {
// Optional fields run up to a lone `-`; after it come the type
// and the source.
let (left, right) = line.split_once(" - ")?;
let mut left = left.split_whitespace().skip(3);
let mut left = left.split_whitespace().skip(2);
let device = left.next()?.to_string();
let fs_root = PathBuf::from(unescape_octal(left.next()?));
let point = PathBuf::from(unescape_octal(left.next()?));
let mut right = right.split_whitespace();
let fstype = right.next()?.to_string();
let source = unescape_octal(right.next()?);
Some(MountView {
device,
source,
fstype,
point,
@@ -298,10 +302,40 @@ fn unescape_octal(field: &str) -> String {
/// is left out. The scanned root itself is never left out; if it is the
/// narrower view, its copy inside the wider one is.
pub fn repeated_mounts(mounts: &[MountView], root: &Path) -> Vec<PathBuf> {
repeated_mounts_excluding(mounts, root, &[])
}
fn same_filesystem(left: &MountView, right: &MountView) -> bool {
left.fstype == right.fstype
&& (left.device == right.device
// Btrfs assigns device numbers per subvolume. Its block device
// identifies the filesystem shared by those different roots.
|| (left.fstype == "btrfs"
&& left.source.starts_with("/dev/")
&& left.source == right.source))
}
fn covering_mount<'a>(
mounts: &'a [MountView],
path: &Path,
) -> Option<&'a MountView> {
mounts
.iter()
.filter(|mount| path.starts_with(&mount.point))
.max_by_key(|mount| mount.point.components().count())
}
fn repeated_mounts_excluding(
mounts: &[MountView],
root: &Path,
excluded: &[PathBuf],
) -> Vec<PathBuf> {
let own = covering_mount(mounts, root);
let mut visible: Vec<&MountView> = mounts
.iter()
.filter(|mount| {
mount.point.starts_with(root) || root.starts_with(&mount.point)
(mount.point.starts_with(root) || Some(*mount) == own)
&& !excluded.iter().any(|skip| mount.point.starts_with(skip))
})
.collect();
visible.sort_by_key(|mount| {
@@ -312,28 +346,49 @@ pub fn repeated_mounts(mounts: &[MountView], root: &Path) -> Vec<PathBuf> {
)
});
let mut kept: Vec<&MountView> = Vec::new();
let mut repeated = Vec::new();
let mut repeated: Vec<PathBuf> = Vec::new();
for mount in visible {
// Where this view's directory already appears through a kept one.
let elsewhere = kept.iter().find_map(|wider| {
if wider.source != mount.source || wider.fstype != mount.fstype {
if !same_filesystem(wider, mount) {
return None;
}
let inside = mount.fs_root.strip_prefix(&wider.fs_root).ok()?;
let path = wider.point.join(inside);
(path.starts_with(root) && path != mount.point).then_some(path)
});
match elsewhere {
Some(_) if mount.point != root && mount.point.starts_with(root) => {
repeated.push(mount.point.clone());
if !path.starts_with(root)
|| path == mount.point
|| excluded
.iter()
.chain(&repeated)
.any(|skip| path.starts_with(skip))
{
return None;
}
Some(copy) => {
if copy != root {
repeated.push(copy);
}
// Another mount can hide the supposed original directory.
let covering = covering_mount(mounts, &path)?;
let relative = path.strip_prefix(&covering.point).ok()?;
(same_filesystem(covering, mount)
&& covering.fs_root.join(relative) == mount.fs_root)
.then_some(path)
});
let skip = elsewhere.map(|copy| {
if mount.point != root && mount.point.starts_with(root) {
mount.point.clone()
} else {
copy
}
});
if let Some(skip) = skip
&& !root.starts_with(&skip)
// A duplicate view can contain independently mounted data.
// Keep it rather than hiding that data with its parent.
&& !mounts.iter().any(|child| child.point != skip && child.point.starts_with(&skip))
{
if skip != mount.point {
kept.push(mount);
}
None => kept.push(mount),
repeated.push(skip);
} else {
kept.push(mount);
}
}
repeated
@@ -341,11 +396,20 @@ pub fn repeated_mounts(mounts: &[MountView], root: &Path) -> Vec<PathBuf> {
/// [`repeated_mounts`] for this machine, in `root`'s own spelling. Empty
/// where there is no `/proc/self/mountinfo`.
pub fn repeated_mounts_for(root: &Path, canonical: &Path) -> Vec<PathBuf> {
pub fn repeated_mounts_for(
root: &Path,
canonical: &Path,
one_filesystem: bool,
) -> Vec<PathBuf> {
let Ok(table) = std::fs::read_to_string("/proc/self/mountinfo") else {
return Vec::new();
};
repeated_mounts(&parse_mountinfo(&table), canonical)
let excluded = if one_filesystem {
foreign_mounts_for(canonical).unwrap_or_default()
} else {
Vec::new()
};
repeated_mounts_excluding(&parse_mountinfo(&table), canonical, &excluded)
.iter()
.filter_map(|path| path.strip_prefix(canonical).ok())
.map(|below| root.join(below))
@@ -703,6 +767,56 @@ portal /run/user/1000/doc fuse.portal rw 0 0
);
}
#[test]
fn unrelated_tmpfs_mounts_are_not_duplicates() {
let table = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 0:20 / /one rw - tmpfs tmpfs rw\n\
3 1 0:21 / /two rw - tmpfs tmpfs rw\n";
assert!(repeated(table, "/").is_empty());
let alias =
format!("{table}4 1 0:20 / /three rw - tmpfs different-name rw\n");
assert_eq!(repeated(&alias, "/"), [PathBuf::from("/three")]);
}
#[test]
fn hidden_original_and_nested_mounts_are_preserved() {
let hidden = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 0:20 / /data rw - tmpfs tmpfs rw\n\
3 2 8:1 /data/source /data/bind rw - ext4 /dev/root rw\n";
assert!(repeated(hidden, "/").is_empty());
let nested = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 8:1 /original /view rw - ext4 /dev/root rw\n\
3 2 0:20 / /view/unique rw - tmpfs tmpfs rw\n";
assert!(repeated(nested, "/").is_empty());
}
#[test]
fn excluded_views_cannot_replace_visible_files() {
let mounts = parse_mountinfo(
"1 0 8:1 / / rw - ext4 /dev/root rw\n\
2 1 8:1 /original /view rw - ext4 /dev/root rw\n",
);
assert!(
repeated_mounts_excluding(
&mounts,
Path::new("/"),
&[PathBuf::from("/original")]
)
.is_empty()
);
}
#[test]
fn btrfs_subvolume_devices_can_differ() {
let table = "1 0 0:20 /@ / rw - btrfs /dev/root rw\n\
2 1 0:21 /@home /home rw - btrfs /dev/root rw\n\
3 1 0:22 / /top rw - btrfs /dev/root rw\n";
assert_eq!(
repeated(table, "/"),
[PathBuf::from("/home"), PathBuf::from("/top/@")]
);
}
#[test]
fn mountinfo_escapes_are_decoded_once() {
let mounts = parse_mountinfo(
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Pass the compiled disktree-core unit test binary as the first argument.
# All mounts and writes live in an isolated, temporary /run.
set -eu
exec unshare --user --map-root-user --mount sh -eu -c '
mount --make-rprivate /
mount -t tmpfs disktree-test-run /run
mkdir -p /run/media/disktree-test /run/disktree-scan
mount -t tmpfs tmpfs /run/media/disktree-test
mkdir /run/media/disktree-test/nested
mount -t tmpfs tmpfs /run/media/disktree-test/nested
for dir in original alias one two; do mkdir /run/disktree-scan/$dir; done
mkdir /run/disktree-scan/original/nested
mount --bind /run/disktree-scan/original /run/disktree-scan/alias
for dir in one two; do mount -t tmpfs tmpfs /run/disktree-scan/$dir; done
for dir in original one two; do printf data > /run/disktree-scan/$dir/file; done
"$1" --exact removal::tests::mounted_media_and_repeated_views --ignored --nocapture
' sh "$1"