Skip to content

Commit

Permalink
fix(context): use custom open function
Browse files Browse the repository at this point in the history
  • Loading branch information
saidsay-so committed Sep 16, 2024
1 parent 418e777 commit 4d412d9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
18 changes: 9 additions & 9 deletions rust/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use nix::{
fcntl::{open, OFlag},
fcntl::OFlag,
sys::{
socket::{bind, socket, SockFlag, UnixAddr},
stat::{lstat, mknod, mode_t, umask, Mode, SFlag},
Expand All @@ -25,7 +25,7 @@ use strum_macros::EnumIter;

use crate::{
config::{Config, DummyAuthEntry, FeaturesConfig},
utils::{chmod, lchmod, symlink},
utils::{chmod, lchmod, open, symlink},
};

/// File type, mainly used with [TestContext::create].
Expand Down Expand Up @@ -375,7 +375,9 @@ impl FileBuilder {
let path = self.final_path();

match self.file_type {
FileType::Regular => open(&path, OFlag::O_CREAT, mode).and_then(close),
FileType::Regular => {
open(&path, OFlag::O_CREAT, mode).and_then(|fd| close(fd.as_raw_fd()))
}
FileType::Dir => mkdir(&path, mode),
FileType::Fifo => mkfifo(&path, mode),
FileType::Block => mknod(&path, SFlag::S_IFBLK, mode, 0),
Expand Down Expand Up @@ -423,13 +425,11 @@ impl FileBuilder {
OFlag::O_CREAT | oflags,
self.mode.unwrap_or_else(|| Mode::from_bits_truncate(0o644)),
)
// SAFETY: The file descriptor was initialized only by open and isn't used anywhere else, leaving the ownership
.map(|fd| (path, unsafe { OwnedFd::from_raw_fd(fd) }))
.map(|fd| (path, fd))
}
_ => self.create().and_then(|p| {
// SAFETY: The file descriptor was initialized only by open and isn't used anywhere else, leaving the ownership
open(&p, oflags, Mode::empty()).map(|fd| (p, unsafe { OwnedFd::from_raw_fd(fd) }))
}),
_ => self
.create()
.and_then(|p| open(&p, oflags, Mode::empty()).map(|fd| (p, fd))),
}
}

Expand Down
2 changes: 2 additions & 0 deletions rust/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,7 @@ pub fn lchflags<P: ?Sized + nix::NixPath>(

/// Wrapper for open which returns [`Ownedfd`] instead of [`RawFd`].
pub fn open<P: ?Sized + nix::NixPath>(path: &P, oflag: OFlag, mode: Mode) -> nix::Result<OwnedFd> {
// SAFETY: The file descriptor was initialized only by open and isn't used anywhere else,
// leaving the ownership to the caller.
nix::fcntl::open(path, oflag, mode).map(|fd| unsafe { OwnedFd::from_raw_fd(fd) })
}

0 comments on commit 4d412d9

Please sign in to comment.