diff --git a/Cargo.lock b/Cargo.lock index e7963f3f..b2a79b5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1760,6 +1760,7 @@ name = "uu_mountpoint" version = "0.0.1" dependencies = [ "clap", + "libc", "uucore 0.2.2", ] diff --git a/src/uu/mountpoint/Cargo.toml b/src/uu/mountpoint/Cargo.toml index 111bcbfc..5a1d43ec 100644 --- a/src/uu/mountpoint/Cargo.toml +++ b/src/uu/mountpoint/Cargo.toml @@ -9,6 +9,9 @@ edition = "2021" uucore = { workspace = true } clap = { workspace = true } +[target.'cfg(unix)'.dependencies] +libc = { workspace = true } + [lib] path = "src/mountpoint.rs" diff --git a/src/uu/mountpoint/src/mountpoint.rs b/src/uu/mountpoint/src/mountpoint.rs index a6b5368a..4fac873d 100644 --- a/src/uu/mountpoint/src/mountpoint.rs +++ b/src/uu/mountpoint/src/mountpoint.rs @@ -3,8 +3,8 @@ // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. -use clap::Arg; use clap::{crate_version, Command}; +use clap::{Arg, ArgAction}; use std::env; #[cfg(not(windows))] use std::fs; @@ -23,6 +23,20 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { let path = matches.get_one::("path"); if let Some(path) = path { + if matches.get_flag("devno") { + return print_block_devno(path); + } + if matches.get_flag("fs-devno") { + match fs_devno(path) { + Ok(Some(devno)) => println!("{devno}"), + Ok(None) => { + println!("{path} is not a mountpoint"); + set_exit_code(32); + } + Err(e) => return Err(USimpleError::new(1, format!("{path}: {}", strip_errno(&e)))), + } + return Ok(()); + } match is_mountpoint(path) { Ok(true) => println!("{path} is a mountpoint"), Ok(false) => { @@ -56,6 +70,77 @@ fn is_mountpoint(path: &str) -> std::io::Result { .any(|mount_point| unescape_mountinfo(mount_point) == target.as_os_str().as_bytes())) } +/// The `major:minor` of the filesystem mounted on `path`, or `None` when it is +/// not a mount point. Like util-linux, this is the device number of the +/// topmost (last) mountinfo entry for the path, which can differ from the +/// path's `st_dev`, for example for a bind-mounted file. +#[cfg(target_os = "linux")] +fn fs_devno(path: &str) -> std::io::Result> { + use std::os::unix::ffi::OsStrExt; + + let target = fs::canonicalize(path)?; + let Ok(mountinfo) = fs::read("/proc/self/mountinfo") else { + return fs_devno_by_device(path); + }; + // the last entry for a mount point is the topmost mount + Ok(mountinfo.rsplit(|&b| b == b'\n').find_map(|line| { + let mut fields = line.split(|&b| b == b' '); + let devno = fields.nth(2)?; + let mount_point = fields.nth(1)?; + (unescape_mountinfo(mount_point) == target.as_os_str().as_bytes()) + .then(|| String::from_utf8_lossy(devno).into_owned()) + })) +} + +#[cfg(all(not(windows), not(target_os = "linux")))] +fn fs_devno(path: &str) -> std::io::Result> { + fs_devno_by_device(path) +} + +#[cfg(not(windows))] +fn fs_devno_by_device(path: &str) -> std::io::Result> { + if !is_mountpoint_by_device(path)? { + return Ok(None); + } + Ok(Some(format_devno(fs::metadata(path)?.dev()))) +} + +#[cfg(windows)] +fn fs_devno(_path: &str) -> std::io::Result> { + Ok(None) +} + +#[cfg(not(windows))] +fn format_devno(dev: u64) -> String { + // dev_t is narrower than u64 on some platforms, such as macOS + #[allow(clippy::unnecessary_cast)] + let dev = dev as libc::dev_t; + format!("{}:{}", libc::major(dev), libc::minor(dev)) +} + +/// Prints the `major:minor` of the block device `path`. +#[cfg(not(windows))] +fn print_block_devno(path: &str) -> UResult<()> { + use std::os::unix::fs::FileTypeExt; + + let metadata = fs::metadata(path) + .map_err(|e| USimpleError::new(1, format!("{path}: {}", strip_errno(&e))))?; + if metadata.file_type().is_block_device() { + println!("{}", format_devno(metadata.rdev())); + } else { + uucore::show_error!("{path}: not a block device"); + set_exit_code(32); + } + Ok(()) +} + +#[cfg(windows)] +fn print_block_devno(path: &str) -> UResult<()> { + uucore::show_error!("{path}: not a block device"); + set_exit_code(32); + Ok(()) +} + /// mountinfo writes space, tab, newline and backslash as `\ooo` octal escapes. #[cfg(target_os = "linux")] fn unescape_mountinfo(field: &[u8]) -> Vec { @@ -108,6 +193,20 @@ pub fn uu_app() -> Command { .about(ABOUT) .override_usage(format_usage(USAGE)) .infer_long_args(true) + .arg( + Arg::new("fs-devno") + .short('d') + .long("fs-devno") + .action(ArgAction::SetTrue) + .help("Print the major/minor device number of the filesystem mounted on PATH"), + ) + .arg( + Arg::new("devno") + .short('x') + .long("devno") + .action(ArgAction::SetTrue) + .help("Print the major/minor device number of the block device PATH"), + ) .arg( Arg::new("path") .value_name("PATH") diff --git a/tests/by-util/test_mountpoint.rs b/tests/by-util/test_mountpoint.rs index 7042c8c8..5fe303af 100644 --- a/tests/by-util/test_mountpoint.rs +++ b/tests/by-util/test_mountpoint.rs @@ -66,3 +66,57 @@ fn test_proc_is_a_mountpoint() { .succeeds() .stdout_is("/proc/ is a mountpoint\n"); } + +#[test] +#[cfg(target_os = "linux")] +fn test_fs_devno_of_root() { + // the device number of the topmost mount on `/`, as in mountinfo + let mountinfo = std::fs::read_to_string("/proc/self/mountinfo").unwrap(); + let devno = mountinfo + .lines() + .rev() + .find_map(|line| { + let fields: Vec<&str> = line.split(' ').collect(); + (fields[4] == "/").then(|| fields[2].to_string()) + }) + .unwrap(); + for flag in ["-d", "--fs-devno"] { + new_ucmd!() + .args(&[flag, "/"]) + .succeeds() + .stdout_is(format!("{devno}\n")); + } +} + +#[test] +#[cfg(unix)] +fn test_fs_devno_not_a_mountpoint() { + let (at, mut ucmd) = at_and_ucmd!(); + at.mkdir("dir"); + ucmd.args(&["-d", &at.plus_as_string("dir")]) + .current_dir("/") + .fails() + .code_is(32) + .stdout_is(format!( + "{} is not a mountpoint\n", + at.plus_as_string("dir") + )); +} + +#[test] +#[cfg(unix)] +fn test_devno_not_a_block_device() { + for flag in ["-x", "--devno"] { + new_ucmd!() + .args(&[flag, "/dev/null"]) + .fails() + .code_is(32) + .no_stdout() + .stderr_is("mountpoint: /dev/null: not a block device\n"); + } + new_ucmd!() + .args(&["-x", "does-not-exist"]) + .fails() + .code_is(1) + .stderr_contains("does-not-exist: No such file or directory"); +}