obliterate 1.2.0

Force-remove Files and Directories on Linux Including Paths with 000 Permissions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Mount-point detection and lazy unmounting for Linux.
//!
//! Before obliterating a directory tree, every mount-point nested inside it
//! must be unmounted — otherwise `unlinkat` on a mount-point itself succeeds
//! (it removes the directory from the parent namespace) but the filesystem
//! underneath stays alive, which is almost always a disaster in a rootfs
//! scenario.
//!
//! # Unmount strategy (tried in order)
//!
//! 1. **`umount2(MNT_DETACH)` syscall** — succeeds when the process runs as
//!    root (`CAP_SYS_ADMIN`).
//!
//! 2. **User + mount namespace via `unshare(2)`** — forks a child process that
//!    creates an unprivileged user namespace (`CLONE_NEWUSER`) mapped as root,
//!    then a mount namespace (`CLONE_NEWNS`) inside it, and calls
//!    `umount2(MNT_DETACH)` from there. Works without privileges for mounts
//!    owned by the current user. The `unshare` is done in a forked child to
//!    avoid corrupting the parent process namespace and to be safe with
//!    multithreaded runtimes (the kernel rejects `CLONE_NEWUSER` on processes
//!    with more than one thread). If `unshare` itself fails (user namespaces
//!    disabled on this kernel), the child exits with code 1 and the parent
//!    falls through to fusermount. If the namespace was created but the mount
//!    does not belong to the current user, the child exits with code 2 and the
//!    parent stops immediately — fusermount would also reject it.
//!
//! 3. **`fusermount3 -u -z` / `fusermount -u -z`** — fallback for FUSE mounts
//!    on systems where user namespaces are disabled by the kernel
//!    (`/proc/sys/kernel/unprivileged_userns_clone = 0`, common on some Debian
//!    derivatives). Both binaries are setuid-root and resolved by name without
//!    PATH scanning. `fusermount3` is tried first; `fusermount` is the fallback
//!    for older distributions.
//!
//! 4. **[`Error::UnmountFailed`]** — none of the above worked. The caller must
//!    arrange unmounting externally before retrying. The removal is **not**
//!    attempted when a mount-point cannot be detached, to avoid leaving orphaned
//!    filesystems behind.

use crate::error::{Error, Result};
use std::collections::HashMap;
use std::ffi::CString;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::FromRawFd;
use std::path::{Path, PathBuf};
use std::process::Command;

/// `MNT_DETACH` flag for `umount2(2)` — immediately detaches from the
/// namespace but keeps open handles functional until they are closed.
const MNT_DETACH: libc::c_int = 2;

/// `CLONE_NEWUSER` flag for `unshare(2)` — creates a new user namespace in
/// which the calling process's UID is mapped as root (uid 0).
const CLONE_NEWUSER: libc::c_int = 0x10000000;

/// `CLONE_NEWNS` flag for `unshare(2)` — creates a new mount namespace,
/// inheriting a copy of the parent's mount tree that can be modified
/// independently.
const CLONE_NEWNS: libc::c_int = 0x00020000;

/// A single entry from `/proc/self/mountinfo` whose mountpoint is at or under
/// the path being obliterated.
#[derive(Debug, Clone)]
pub struct MountPoint {
    /// Unique mount ID from /proc/self/mountinfo
    pub id: u32,
    /// Parent mount ID
    pub parent_id: u32,
    /// Absolute path where this filesystem is mounted.
    pub path: PathBuf,
}

/// Returns all mount-points at or under `root`, sorted **the deepest first** so
/// that nested mounts are unmounted before their parents.
///
/// Uses a [`BufReader`] to parse `/proc/self/mountinfo` line-by-line, which is
/// memory-efficient for systems with many mounts.
///
/// # Arguments
///
/// * `root` - The base path to scan for nested mount-points.
///
/// # Returns
///
/// Returns a [`Result`] containing a vector of [`MountPoint`] entries, ordered
/// deepest first. Returns an empty vector if `root` does not exist or if
/// `/proc/self/mountinfo` is unavailable.
pub fn mounts_under(root: &Path) -> Result<Vec<MountPoint>> {
    let root_canon = match root.canonicalize() {
        Ok(p) => p,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(Error::Io(e)),
    };

    let file = match File::open("/proc/self/mountinfo") {
        Ok(f) => f,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(Error::Io(e)),
    };

    let reader = BufReader::new(file);
    let mut mounts = Vec::new();

    for line_result in reader.lines() {
        let line = line_result.map_err(Error::Io)?;

        if let Some(mp) = parse_mountinfo_line(&line) {
            if mp.path == root_canon || mp.path.starts_with(&root_canon) {
                mounts.push(mp);
            }
        }
    }

    let depths = compute_depths(&mounts);
    mounts.sort_by_key(|mp| depths.get(&mp.id).copied().unwrap_or(0));
    mounts.reverse();
    Ok(mounts)
}

/// Lazily unmounts `mp` using the best available strategy.
///
/// "Lazy" (`MNT_DETACH`) means active file handles continue to work until
/// closed, but the mount-point is immediately detached from the namespace tree,
/// which is what is needed before deleting the directory. Strategies are tried
/// in order and the first success returns immediately. If no strategy succeeds
/// the mount-point is left intact and an error is returned — removal is never
/// attempted against a live filesystem.
///
/// # Arguments
///
/// * `mp` - The mount-point to detach, including its path and filesystem type.
///
/// # Returns
///
/// Returns `Ok(())` if the mount-point was successfully detached.
pub fn unmount_lazy(mp: &MountPoint) -> Result<()> {
    // Strategy 1: direct syscall
    match try_umount2_detach(&mp.path) {
        Ok(()) => return Ok(()),
        Err(e) if matches!(e.raw_os_error(), Some(libc::EPERM) | Some(libc::EACCES)) => {}
        Err(e) => return Err(Error::Io(e)),
    }

    // Strategy 2: user namespace
    match try_umount2_in_user_ns(&mp.path) {
        Ok(()) => return Ok(()),
        Err(e) if e.raw_os_error() == Some(libc::EPERM) => {}
        Err(e) if e.raw_os_error() == Some(libc::EACCES) => {
            return Err(Error::UnmountFailed {
                path: mp.path.clone(),
                reason: format!(
                    "mount at '{}' does not belong to the current user; \
                     unmount it manually before retrying",
                    mp.path.display()
                ),
            });
        }
        Err(e) => return Err(Error::Io(e)),
    }

    // Strategy 3: always try fusermount as fallback
    match try_fusermount(&mp.path) {
        Ok(()) => return Ok(()),
        Err(_) => {}
    }

    // Strategy 4: nothing worked — refuse to proceed
    Err(Error::UnmountFailed {
        path: mp.path.clone(),
        reason: "failed to unmount; may require CAP_SYS_ADMIN or manual intervention".into(),
    })
}

/// Calls `umount2(path, MNT_DETACH)` directly via libc.
///
/// # Arguments
///
/// * `path` - The mount-point path to detach.
///
/// # Returns
///
/// Returns `Ok(())` on success, or an [`io::Error`] reflecting the errno set
/// by the kernel (e.g. `EPERM` when `CAP_SYS_ADMIN` is absent).
fn try_umount2_detach(path: &Path) -> io::Result<()> {
    let cpath = CString::new(path.as_os_str().as_bytes())
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains null byte"))?;
    let ret = unsafe { libc::umount2(cpath.as_ptr(), MNT_DETACH) };
    if ret == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

/// Unmounts `path` from inside a freshly created user + mount namespace.
///
/// Forks a child process that calls `unshare(CLONE_NEWUSER | CLONE_NEWNS)`,
/// maps the real UID/GID as root inside the new user namespace, then calls
/// `umount2(MNT_DETACH)`. The parent waits for the child and converts its exit
/// status back into an `io::Result`.
///
/// The fork is necessary for two reasons:
/// - `CLONE_NEWUSER` is rejected by the kernel when the calling process has
///   more than one thread, which is common in Rust programs using async runtimes
///   or Rayon. Forking creates a single-threaded child that can safely call it.
/// - The new namespaces are discarded when the child exits, so the parent's
///   mount tree is never affected.
///
/// # Arguments
///
/// * `path` - The mount-point path to detach.
///
/// # Returns
///
/// Returns `Ok(())` if the child successfully unmounted the path.
/// Returns `Err(EPERM)` if `unshare` failed, meaning user namespaces are
/// disabled on this kernel — the caller should try fusermount next.
/// Returns `Err(EACCES)` if the namespace was created but `umount2` was
/// rejected, meaning the mount does not belong to the current user — the caller
/// should stop and report an error rather than trying fusermount, which would
/// also reject it.
fn try_umount2_in_user_ns(path: &Path) -> io::Result<()> {
    let cpath = CString::new(path.as_os_str().as_bytes())
        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains null byte"))?;

    let uid = unsafe { libc::getuid() };
    let gid = unsafe { libc::getgid() };

    let pid = unsafe { libc::fork() };
    match pid {
        -1 => Err(io::Error::last_os_error()),
        0 => {
            if unsafe { libc::unshare(CLONE_NEWUSER | CLONE_NEWNS) } != 0 {
                unsafe { libc::_exit(1) };
            }

            if write_proc_file("/proc/self/setgroups", "deny").is_err() {
                unsafe { libc::_exit(2) };
            }

            let uid_map = format!("0 {uid} 1");
            if write_proc_file("/proc/self/uid_map", &uid_map).is_err() {
                unsafe { libc::_exit(2) };
            }

            let gid_map = format!("0 {gid} 1");
            if write_proc_file("/proc/self/gid_map", &gid_map).is_err() {
                unsafe { libc::_exit(2) };
            }

            let ret = unsafe { libc::umount2(cpath.as_ptr(), MNT_DETACH) };
            unsafe { libc::_exit(if ret == 0 { 0 } else { 2 }) };
        }
        child_pid => {
            let mut status: libc::c_int = 0;
            loop {
                let ret = unsafe { libc::waitpid(child_pid, &mut status, 0) };
                if ret == -1 {
                    let e = io::Error::last_os_error();
                    if e.raw_os_error() == Some(libc::EINTR) {
                        continue;
                    }
                    return Err(e);
                }
                break;
            }

            match (libc::WIFEXITED(status), libc::WEXITSTATUS(status)) {
                (true, 0) => Ok(()),
                (true, 1) => Err(io::Error::from_raw_os_error(libc::EPERM)),
                (true, _) => Err(io::Error::from_raw_os_error(libc::EACCES)),
                _ => Err(io::Error::from_raw_os_error(libc::EINTR)),
            }
        }
    }
}

/// Tries `fusermount3 -u -z <path>`, falling back to `fusermount -u -z`.
///
/// Both binaries are setuid-root system tools installed by the package manager.
/// They are resolved by name only — no PATH scanning — because `execve` finds
/// them the same way the shell would. The binary can be overridden via the
/// `OBLITERATE_FUSERMOUNT` environment variable for testing or exotic setups.
///
/// # Arguments
///
/// * `path` - The FUSE mount-point path to unmount.
///
/// # Returns
///
/// Returns `Ok(())` on success, or `Err(String)` with a human-readable
/// description of what failed, including which binary was tried.
fn try_fusermount(path: &Path) -> std::result::Result<(), String> {
    for bin in &["fusermount3", "fusermount"] {
        match run_fusermount(bin, path) {
            Ok(()) => return Ok(()),
            Err(ref msg) if msg.contains("not found") || msg.contains("ENOENT") => continue,
            Err(msg) => return Err(msg),
        }
    }

    Err("neither fusermount3 nor fusermount is installed; \
         install fuse3 (or fuse2) or run as root"
        .into())
}

/// Executes `<bin> -u -z -- <path>` and maps the outcome to a human-readable
/// error string on failure.
///
/// # Arguments
///
/// * `bin` - The fusermount binary name or path to execute.
/// * `path` - The mount-point path to pass as the unmount target.
///
/// # Returns
///
/// Returns `Ok(())` if the process exits successfully, or `Err(String)`
/// describing the failure, including the binary name and exit status.
fn run_fusermount(bin: &str, path: &Path) -> std::result::Result<(), String> {
    let output = Command::new(bin)
        .args(["-u", "-z", "--"])
        .arg(path)
        .output();

    match output {
        Ok(out) if out.status.success() => Ok(()),
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr);
            let stdout = String::from_utf8_lossy(&out.stdout);
            let msg = if !stderr.trim().is_empty() {
                stderr.trim().to_owned()
            } else {
                stdout.trim().to_owned()
            };
            let exit = out
                .status
                .code()
                .map_or_else(|| "signal".into(), |c| c.to_string());

            Err(format!("{bin}: {msg} (exit {exit})"))
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => Err(format!("{bin}: not found")),
        Err(e) => Err(format!("{bin}: {e}")),
    }
}

/// Writes `content` atomically to a `/proc/self/…` control file.
///
/// Used inside the forked child to configure the new user namespace before
/// calling `umount2`. To write must complete in a single `write(2)` call
/// because the kernel processes these files atomically — partial writes are
/// rejected.
///
/// # Arguments
///
/// * `path` - The `/proc/self/…` file to write (e.g. `"/proc/self/uid_map"`).
/// * `content` - The ASCII string to write into the file.
///
/// # Returns
///
/// Returns `Ok(())` if the entire content was written successfully.
fn write_proc_file(path: &str, content: &str) -> io::Result<()> {
    let cpath = CString::new(path).expect("proc path has no null byte");
    let fd = unsafe { libc::open(cpath.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC) };
    if fd < 0 {
        return Err(io::Error::last_os_error());
    }

    let mut file = unsafe { File::from_raw_fd(fd) };
    file.write_all(content.as_bytes())
}

/// Parses a single line of `/proc/self/mountinfo` into a [`MountPoint`].
///
/// The optional-fields section (between mount-options and the bare `-` token)
/// may contain zero or more fields, so the separator is located by scanning for
/// `"-"` as a standalone token rather than relying on a fixed column index.
///
/// Mountinfo format (kernel docs):
/// ```text
/// 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,...
/// id  parent  maj:min  root  mountpoint  mountopts  [optional...]  -  fstype  source  superopts
/// ```
///
/// # Arguments
///
/// * `line` - A raw line from `/proc/self/mountinfo`.
///
/// # Returns
///
/// Returns `Some(MountPoint)` if the line is valid, or `None` if any required
/// field is missing or the `-` separator cannot be found.
fn parse_mountinfo_line(line: &str) -> Option<MountPoint> {
    let tokens: Vec<&str> = line.split(' ').collect();
    let mount_id = tokens.get(0)?.parse::<u32>().ok()?;
    let parent_id = tokens.get(1)?.parse::<u32>().ok()?;
    let mountpoint_raw = tokens.get(4)?;
    let mountpoint = unescape_mountinfo(mountpoint_raw);

    Some(MountPoint {
        id: mount_id,
        parent_id,
        path: PathBuf::from(mountpoint),
    })
}

/// Unescapes octal sequences in mountinfo paths (`\NNN` → byte).
///
/// The kernel encodes spaces and other special bytes in paths as three-digit
/// octal escape sequences (e.g. `\040` for U+0020 SPACE).
///
/// # Arguments
///
/// * `s` - The raw escaped path string from a mountinfo line.
///
/// # Returns
///
/// Returns the decoded path as a [`String`]. Falls back to lossy UTF-8
/// conversion if the decoded bytes are not valid UTF-8.
fn unescape_mountinfo(s: &str) -> String {
    let mut out: Vec<u8> = Vec::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'\\' && i + 3 < bytes.len() {
            let decode = (|| {
                let a = (bytes[i + 1] as char).to_digit(8)? as u8;
                let b = (bytes[i + 2] as char).to_digit(8)? as u8;
                let c = (bytes[i + 3] as char).to_digit(8)? as u8;
                Some((a << 6) | (b << 3) | c)
            })();

            if let Some(byte) = decode {
                out.push(byte);
                i += 4;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }

    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}

/// Calculates the depth of each mount based on the parent → child relationship.
///
/// The deeper the mount, the higher the value — this ensures children are
/// unmounted before their parents.
///
/// # Arguments
///
/// * `mounts` - List of mount-points.
///
/// # Returns
///
/// A `HashMap` mapping mount ID to its depth (0 = root, higher = deeper).
fn compute_depths(mounts: &[MountPoint]) -> HashMap<u32, usize> {
    let map: HashMap<u32, &MountPoint> = mounts.iter().map(|m| (m.id, m)).collect();

    let mut depths = HashMap::new();

    for mp in mounts {
        let mut depth = 0;
        let mut current = mp;

        while let Some(parent) = map.get(&current.parent_id) {
            depth += 1;
            current = parent;
        }

        depths.insert(mp.id, depth);
    }

    depths
}

#[cfg(test)]
#[path = "unmount_tests.rs"]
mod tests;