Skip to content

fs: Add mntent.h wrapper #257

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 25 additions & 39 deletions fs/df.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,20 @@
// SPDX-License-Identifier: MIT
//

#[cfg(target_os = "linux")]
mod mntent;

#[cfg(target_os = "linux")]
use crate::mntent::MountTable;

use clap::Parser;
use gettextrs::{bind_textdomain_codeset, gettext, setlocale, textdomain, LocaleCategory};
use plib::PROJECT_NAME;
use std::ffi::{CStr, CString};
#[cfg(target_os = "macos")]
use std::ffi::CStr;
use std::ffi::CString;
use std::io;

#[cfg(target_os = "linux")]
const _PATH_MOUNTED: &'static str = "/etc/mtab";

#[derive(Parser)]
#[command(version, about = gettext("df - report free storage space"))]
struct Args {
Expand Down Expand Up @@ -54,9 +59,7 @@ fn to_cstr(array: &[libc::c_char]) -> &CStr {
}
}

fn stat(filename_str: &str) -> io::Result<libc::stat> {
let filename = CString::new(filename_str).unwrap();

fn stat(filename: &CString) -> io::Result<libc::stat> {
unsafe {
let mut st: libc::stat = std::mem::zeroed();
let rc = libc::stat(filename.as_ptr(), &mut st);
Expand Down Expand Up @@ -102,11 +105,11 @@ impl MountList {
}
}

fn push(&mut self, fsstat: &libc::statfs, devname: &CStr, dirname: &CStr) {
fn push(&mut self, fsstat: &libc::statfs, devname: &CString, dirname: &CString) {
let dev = {
if let Ok(st) = stat(devname.to_str().unwrap()) {
if let Ok(st) = stat(devname) {
st.st_rdev as i64
} else if let Ok(st) = stat(dirname.to_str().unwrap()) {
} else if let Ok(st) = stat(dirname) {
st.st_dev as i64
} else {
-1
Expand Down Expand Up @@ -136,9 +139,9 @@ fn read_mount_info() -> io::Result<MountList> {

let mounts: &[libc::statfs] = std::slice::from_raw_parts(mounts as _, n_mnt as _);
for mount in mounts {
let devname = to_cstr(&mount.f_mntfromname);
let dirname = to_cstr(&mount.f_mntonname);
info.push(mount, devname, dirname);
let devname = to_cstr(&mount.f_mntfromname).into();
let dirname = to_cstr(&mount.f_mntonname).into();
info.push(mount, &devname, &dirname);
}
}

Expand All @@ -149,47 +152,30 @@ fn read_mount_info() -> io::Result<MountList> {
fn read_mount_info() -> io::Result<MountList> {
let mut info = MountList::new();

unsafe {
let path_mnt = CString::new(_PATH_MOUNTED).unwrap();
let mnt_mode = CString::new("r").unwrap();
let f = libc::setmntent(path_mnt.as_ptr(), mnt_mode.as_ptr());
if f.is_null() {
return Err(io::Error::last_os_error());
}

loop {
let me = libc::getmntent(f);
if me.is_null() {
break;
}

let me_devname = (*me).mnt_fsname;
let me_dirname = (*me).mnt_dir;
let devname = CStr::from_ptr(me_devname);
let dirname = CStr::from_ptr(me_dirname);

let mut mount: libc::statfs = std::mem::zeroed();
let rc = libc::statfs(dirname.as_ptr(), &mut mount);
let mounts = MountTable::try_new()?;
for mount in mounts {
unsafe {
let mut buf: libc::statfs = std::mem::zeroed();
let rc = libc::statfs(mount.dir.as_ptr(), &mut buf);
if rc < 0 {
eprintln!(
"{}: {}",
dirname.to_str().unwrap(),
mount.dir.to_str().unwrap(),
io::Error::last_os_error()
);
continue;
}

info.push(&mount, devname, dirname);
info.push(&buf, &mount.fsname, &mount.dir);
}

libc::endmntent(f);
}

Ok(info)
}

fn mask_fs_by_file(info: &mut MountList, filename: &str) -> io::Result<()> {
let stat_res = stat(filename);
let c_filename = CString::new(filename).expect("`filename` contains an internal 0 byte");
let stat_res = stat(&c_filename);
if let Err(e) = stat_res {
eprintln!("{}: {}", filename, e);
return Err(e);
Expand Down
141 changes: 141 additions & 0 deletions fs/mntent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
//
// Copyright (c) 2024 fox0
//
// This file is part of the posixutils-rs project covered under
// the MIT License. For the full license text, please see the LICENSE
// file in the root directory of this project.
// SPDX-License-Identifier: MIT
//

//! The mtab file
//! https://www.gnu.org/software/libc/manual/html_node/mtab.html

use libc::{endmntent, getmntent, setmntent, FILE};
use std::ffi::{CStr, CString};
use std::io;
use std::sync::Mutex;

const _PATH_MOUNTED: &CStr = c"/etc/mtab";

/// The mtab (contraction of mounted file systems table) file
/// is a system information file, commonly found on Unix-like systems
pub struct MountTable {
inner: *mut FILE,
}

/// Structure describing a mount table entry
#[derive(Debug, PartialEq)]
pub struct MountTableEntity {
/// Device or server for filesystem
pub fsname: CString,
/// Directory mounted on
pub dir: CString,
/// Type of filesystem: ufs, nfs, etc
pub fstype: CString,
/// Comma-separated options for fs
pub opts: CString,
/// Dump frequency (in days)
pub freq: i32,
/// Pass number for `fsck``
pub passno: i32,
}

impl MountTable {
pub fn try_new() -> Result<Self, io::Error> {
Self::open(_PATH_MOUNTED, c"r")
}

/// Open mtab file
fn open(filename: &CStr, mode: &CStr) -> Result<Self, io::Error> {
// Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem fd lock
// https://www.gnu.org/software/libc/manual/html_node/POSIX-Safety-Concepts.html
let inner = unsafe { setmntent(filename.as_ptr(), mode.as_ptr()) };
if inner.is_null() {
return Err(io::Error::last_os_error());
}
Ok(Self { inner })
}
}

impl Iterator for MountTable {
type Item = MountTableEntity;

fn next(&mut self) -> Option<Self::Item> {
static THREAD_UNSAFE_FUNCTION_MUTEX: Mutex<()> = Mutex::new(());
let _lock = THREAD_UNSAFE_FUNCTION_MUTEX.lock().unwrap();

// Preliminary: | MT-Unsafe race:mntentbuf locale | AS-Unsafe corrupt heap init | AC-Unsafe init corrupt lock mem
// https://www.gnu.org/software/libc/manual/html_node/POSIX-Safety-Concepts.html
let me = unsafe { getmntent(self.inner) };
if me.is_null() {
return None;
}

unsafe {
Some(MountTableEntity {
fsname: CStr::from_ptr((*me).mnt_fsname).into(),
dir: CStr::from_ptr((*me).mnt_dir).into(),
fstype: CStr::from_ptr((*me).mnt_type).into(),
opts: CStr::from_ptr((*me).mnt_opts).into(),
freq: (*me).mnt_freq,
passno: (*me).mnt_passno,
})
}
}
}

impl Drop for MountTable {
/// Close mtab file
fn drop(&mut self) {
// Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe lock mem fd
// https://www.gnu.org/software/libc/manual/html_node/POSIX-Safety-Concepts.html
let _rc = unsafe { endmntent(self.inner) };
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_open() {
let mtab = MountTable::open(c"tests/mtab.txt", c"r");
assert!(mtab.is_ok());
}

#[test]
fn test_open_not_found() {
let mtab = MountTable::open(c"/tmp/not_found", c"r");
let mtab = mtab.err().unwrap();
assert_eq!(mtab.kind(), std::io::ErrorKind::NotFound);
}

#[test]
fn test_iterable() {
let mtab = MountTable::open(c"tests/mtab.txt", c"r").unwrap();
let vec = Vec::from_iter(mtab);
assert_eq!(vec.len(), 2);
assert_eq!(
vec[0],
MountTableEntity {
fsname: CString::new("/dev/sdb1").unwrap(),
dir: CString::new("/").unwrap(),
fstype: CString::new("ext3").unwrap(),
opts: CString::new("rw,relatime,errors=remount-ro").unwrap(),
freq: 0,
passno: 0,
}
);
assert_eq!(
vec[1],
MountTableEntity {
fsname: CString::new("proc").unwrap(),
dir: CString::new("/proc").unwrap(),
fstype: CString::new("proc").unwrap(),
opts: CString::new("rw,noexec,nosuid,nodev").unwrap(),
freq: 0,
passno: 0,
}
);
}
}
2 changes: 2 additions & 0 deletions fs/tests/mtab.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/dev/sdb1 / ext3 rw,relatime,errors=remount-ro 0 0
proc /proc proc rw,noexec,nosuid,nodev 0 0