Skip to content

Commit

Permalink
sys/stat: add a safe wrapper for mknodat(2)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucab committed Jul 22, 2021
1 parent 7033d47 commit c0230a9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -8,6 +8,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).

- Added `IPV6_V6ONLY` sockopt.
(#[1470](https://github.com/nix-rust/nix/pull/1470))
- Added `mknodat`.
(#[1473](https://github.com/nix-rust/nix/pull/1473))

### Changed

Expand Down
25 changes: 21 additions & 4 deletions src/sys/stat.rs
Expand Up @@ -9,6 +9,7 @@ use std::os::unix::io::RawFd;
use crate::sys::time::{TimeSpec, TimeVal};

libc_bitflags!(
/// "File type" flags for `mknod` and related functions.
pub struct SFlag: mode_t {
S_IFIFO;
S_IFCHR;
Expand All @@ -22,6 +23,7 @@ libc_bitflags!(
);

libc_bitflags! {
/// "File mode / permissions" flags.
pub struct Mode: mode_t {
S_IRWXU;
S_IRUSR;
Expand All @@ -41,11 +43,26 @@ libc_bitflags! {
}
}

/// Create a special or ordinary file, by pathname.
pub fn mknod<P: ?Sized + NixPath>(path: &P, kind: SFlag, perm: Mode, dev: dev_t) -> Result<()> {
let res = path.with_nix_path(|cstr| {
unsafe {
libc::mknod(cstr.as_ptr(), kind.bits | perm.bits() as mode_t, dev)
}
let res = path.with_nix_path(|cstr| unsafe {
libc::mknod(cstr.as_ptr(), kind.bits | perm.bits() as mode_t, dev)
})?;

Errno::result(res).map(drop)
}

/// Create a special or ordinary file, relative to a given directory.
#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))]
pub fn mknodat<P: ?Sized + NixPath>(
dirfd: RawFd,
path: &P,
kind: SFlag,
perm: Mode,
dev: dev_t,
) -> Result<()> {
let res = path.with_nix_path(|cstr| unsafe {
libc::mknodat(dirfd, cstr.as_ptr(), kind.bits | perm.bits() as mode_t, dev)
})?;

Errno::result(res).map(drop)
Expand Down

0 comments on commit c0230a9

Please sign in to comment.