]> git.proxmox.com Git - pve-lxc-syscalld.git/commitdiff
replace custom Fd with std OwnedFd
authorWolfgang Bumiller <w.bumiller@proxmox.com>
Fri, 21 Oct 2022 12:03:30 +0000 (14:03 +0200)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Fri, 21 Oct 2022 12:03:30 +0000 (14:03 +0200)
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
src/fork.rs
src/io/mod.rs
src/io/pipe.rs
src/io/seq_packet.rs
src/lxcseccomp.rs
src/process/pid_fd.rs
src/sys_mknod.rs
src/tools.rs

index f43c460ad49c99a31becf0276ae041583ebafe4c..c5c2b9e02ec068fa47c7496414154be06f5bd9ca 100644 (file)
@@ -57,9 +57,9 @@ impl Fork {
         let pid = c_try!(unsafe { libc::fork() });
         if pid == 0 {
             drop(pipe_r);
-            let mut pipe_w = pipe_w.into_fd();
+            let pipe_w = pipe_w.into_fd();
             let _ = std::panic::catch_unwind(move || {
-                pipe_w.set_nonblocking(false).unwrap();
+                crate::tools::set_fd_nonblocking(&pipe_w, false).unwrap();
                 let mut pipe_w = unsafe { std::fs::File::from_raw_fd(pipe_w.into_raw_fd()) };
                 let out = match func() {
                     Ok(SyscallStatus::Ok(val)) => Data {
index d19aea8826d3a7f80631f0d9daa4ff29bd3465b1..2de26c1e292e30d36f812d97adafcbd7cfac7491 100644 (file)
@@ -1,16 +1,14 @@
 use std::io;
-use std::os::unix::io::{AsRawFd, RawFd};
+use std::os::unix::io::{AsRawFd, OwnedFd, RawFd};
 
 use tokio::io::unix::AsyncFd;
 
-use crate::tools::Fd;
-
 pub mod cmsg;
 pub mod pipe;
 pub mod rw_traits;
 pub mod seq_packet;
 
-pub async fn wrap_read<R, F>(async_fd: &AsyncFd<Fd>, mut call: F) -> io::Result<R>
+pub async fn wrap_read<R, F>(async_fd: &AsyncFd<OwnedFd>, mut call: F) -> io::Result<R>
 where
     F: FnMut(RawFd) -> io::Result<R>,
 {
@@ -28,7 +26,7 @@ where
     }
 }
 
-pub async fn wrap_write<R, F>(async_fd: &AsyncFd<Fd>, mut call: F) -> io::Result<R>
+pub async fn wrap_write<R, F>(async_fd: &AsyncFd<OwnedFd>, mut call: F) -> io::Result<R>
 where
     F: FnMut(RawFd) -> io::Result<R>,
 {
index 47ad102ee640c24edfdab45db393d4176ab608dd..258ba511d2974b0f33b3616ec94cb6ada404e6ed 100644 (file)
@@ -1,7 +1,7 @@
 use std::convert::{TryFrom, TryInto};
 use std::io;
 use std::marker::PhantomData;
-use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
+use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
 use std::pin::Pin;
 use std::task::{Context, Poll};
 
@@ -9,7 +9,6 @@ use tokio::io::unix::AsyncFd;
 use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
 
 use crate::io::rw_traits;
-use crate::tools::Fd;
 
 pub use rw_traits::{Read, Write};
 
@@ -20,15 +19,15 @@ pub use rw_traits::{Read, Write};
 /// from the reactor, which will just break.
 ///
 /// So we start out with this type which can be "upgraded" or "downgraded" into a `Pipe<T>` or
-/// `Fd`.
-pub struct PipeFd<RW>(Fd, PhantomData<RW>);
+/// `OwnedFd`.
+pub struct PipeFd<RW>(OwnedFd, PhantomData<RW>);
 
 impl<RW> PipeFd<RW> {
-    pub fn new(fd: Fd) -> Self {
+    pub fn new(fd: OwnedFd) -> Self {
         Self(fd, PhantomData)
     }
 
-    pub fn into_fd(self) -> Fd {
+    pub fn into_fd(self) -> OwnedFd {
         self.0
     }
 }
@@ -38,7 +37,7 @@ pub fn pipe_fds() -> io::Result<(PipeFd<rw_traits::Read>, PipeFd<rw_traits::Writ
 
     c_try!(unsafe { libc::pipe2(pfd.as_mut_ptr(), libc::O_CLOEXEC) });
 
-    let (fd_in, fd_out) = unsafe { (Fd::from_raw_fd(pfd[0]), Fd::from_raw_fd(pfd[1])) };
+    let (fd_in, fd_out) = unsafe { (OwnedFd::from_raw_fd(pfd[0]), OwnedFd::from_raw_fd(pfd[1])) };
 
     Ok((PipeFd::new(fd_in), PipeFd::new(fd_out)))
 }
@@ -46,7 +45,7 @@ pub fn pipe_fds() -> io::Result<(PipeFd<rw_traits::Read>, PipeFd<rw_traits::Writ
 /// Tokio supported pipe file descriptor. `tokio::fs::File` requires tokio's complete file system
 /// feature gate, so we just use this `AsyncFd` wrapper.
 pub struct Pipe<RW> {
-    fd: AsyncFd<Fd>,
+    fd: AsyncFd<OwnedFd>,
     _phantom: PhantomData<RW>,
 }
 
index b82b1635d18aa5cc47d672e230c4c5aee46bf89f..95f87357bac64ed62ce17de3894273c6cbd81988 100644 (file)
@@ -1,5 +1,5 @@
 use std::io::{self, IoSlice, IoSliceMut};
-use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
+use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd, RawFd};
 use std::ptr;
 
 use anyhow::Error;
@@ -7,20 +7,19 @@ use nix::sys::socket::{self, AddressFamily, SockFlag, SockType, SockaddrLike};
 use tokio::io::unix::AsyncFd;
 
 use crate::tools::AssertSendSync;
-use crate::tools::Fd;
 
-fn seq_packet_socket(flags: SockFlag) -> nix::Result<Fd> {
+fn seq_packet_socket(flags: SockFlag) -> nix::Result<OwnedFd> {
     let fd = socket::socket(
         AddressFamily::Unix,
         SockType::SeqPacket,
         flags | SockFlag::SOCK_CLOEXEC,
         None,
     )?;
-    Ok(unsafe { Fd::from_raw_fd(fd) })
+    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
 }
 
 pub struct SeqPacketListener {
-    fd: AsyncFd<Fd>,
+    fd: AsyncFd<OwnedFd>,
 }
 
 impl AsRawFd for SeqPacketListener {
@@ -54,13 +53,13 @@ impl SeqPacketListener {
         })
         .await?;
 
-        let fd = unsafe { Fd::from_raw_fd(fd as RawFd) };
+        let fd = unsafe { OwnedFd::from_raw_fd(fd as RawFd) };
         SeqPacketSocket::new(fd)
     }
 }
 
 pub struct SeqPacketSocket {
-    fd: AsyncFd<Fd>,
+    fd: AsyncFd<OwnedFd>,
 }
 
 impl AsRawFd for SeqPacketSocket {
@@ -71,7 +70,7 @@ impl AsRawFd for SeqPacketSocket {
 }
 
 impl SeqPacketSocket {
-    pub fn new(fd: Fd) -> io::Result<Self> {
+    pub fn new(fd: OwnedFd) -> io::Result<Self> {
         Ok(Self {
             fd: AsyncFd::new(fd)?,
         })
index 5ee1ce7f3202998593c611b25b662679199f022b..fdaadfeaea36ea4c646f51022f4360a7bff5fe76 100644 (file)
@@ -6,7 +6,7 @@ use std::io::{self, IoSlice, IoSliceMut};
 use std::mem;
 use std::os::raw::{c_int, c_uint};
 use std::os::unix::fs::FileExt;
-use std::os::unix::io::{FromRawFd, RawFd};
+use std::os::unix::io::{FromRawFd, OwnedFd, RawFd};
 
 use anyhow::{bail, format_err, Error};
 use lazy_static::lazy_static;
@@ -17,7 +17,7 @@ use crate::io::cmsg;
 use crate::io::seq_packet::SeqPacketSocket;
 use crate::process::PidFd;
 use crate::seccomp::{SeccompNotif, SeccompNotifResp, SeccompNotifSizes};
-use crate::tools::{Fd, FromFd};
+use crate::tools::FromFd;
 
 /// Seccomp notification proxy message sent by the lxc monitor.
 ///
@@ -153,13 +153,13 @@ impl ProxyMessageBuffer {
             bail!("expected SCM_RIGHTS control message");
         }
 
-        let fds: Vec<Fd> = cmsg
+        let fds: Vec<OwnedFd> = cmsg
             .data
             .chunks_exact(mem::size_of::<RawFd>())
             .map(|chunk| unsafe {
                 // clippy bug
                 #[allow(clippy::cast_ptr_alignment)]
-                Fd::from_raw_fd(std::ptr::read_unaligned(chunk.as_ptr() as _))
+                OwnedFd::from_raw_fd(std::ptr::read_unaligned(chunk.as_ptr() as _))
             })
             .collect();
 
@@ -394,7 +394,7 @@ impl ProxyMessageBuffer {
 
     /// Checked way to get a file descriptor argument.
     #[inline]
-    pub fn arg_fd(&self, arg: u32, flags: c_int) -> Result<Fd, Error> {
+    pub fn arg_fd(&self, arg: u32, flags: c_int) -> Result<OwnedFd, Error> {
         let fd = self.arg(arg)? as RawFd;
         // we pass negative ones 'as-is', others get opened via the pidfd
         Ok(if fd == libc::AT_FDCWD {
@@ -402,7 +402,7 @@ impl ProxyMessageBuffer {
             // might want to reuse this one?
             self.pid_fd().fd_cwd()?
         } else if fd < 0 {
-            Fd(fd)
+            unsafe { OwnedFd::from_raw_fd(fd) }
         } else {
             self.pid_fd().fd_num(fd, flags)?
         })
index 30fd9b5475b7b2316484c57e1e466045fcc82bcf..993407033bff704b6d1a6b1d1fa197db3d98bcf4 100644 (file)
@@ -4,7 +4,7 @@ use std::ffi::{CStr, CString, OsString};
 use std::io::{self, BufRead, BufReader};
 use std::os::raw::c_int;
 use std::os::unix::ffi::OsStringExt;
-use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
+use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
 
 use anyhow::{bail, Error};
 use libc::pid_t;
@@ -12,7 +12,6 @@ use libc::pid_t;
 use crate::capability::Capabilities;
 use crate::error::io_err_other;
 use crate::nsfd::{ns_type, NsFd};
-use crate::tools::Fd;
 
 use super::{CGroups, IdMap, IdMapEntry, ProcStatus, Uids, UserCaps};
 
@@ -38,7 +37,7 @@ impl PidFd {
     ///
     /// The file descriptor must already be a valid pidfd, this is not checked. This function only
     /// fails if reading the pid from the pidfd's proc entry fails.
-    pub unsafe fn try_from_fd(fd: Fd) -> io::Result<Self> {
+    pub unsafe fn try_from_fd(fd: OwnedFd) -> io::Result<Self> {
         #[allow(clippy::unnecessary_cast)] // pid_t is a type alias
         let mut this = Self(fd.into_raw_fd(), -1 as pid_t);
         let pid = this.read_pid()?;
@@ -58,22 +57,22 @@ impl PidFd {
         NsFd::openat(self.0, c_str!("ns/user"))
     }
 
-    fn fd(&self, path: &CStr, flags: c_int, mode: c_int) -> io::Result<Fd> {
-        Ok(Fd(c_try!(unsafe {
-            libc::openat(
+    fn fd(&self, path: &CStr, flags: c_int, mode: c_int) -> io::Result<OwnedFd> {
+        Ok(unsafe {
+            OwnedFd::from_raw_fd(c_try!(libc::openat(
                 self.as_raw_fd(),
                 path.as_ptr() as *const _,
                 flags | libc::O_CLOEXEC,
                 mode,
-            )
-        })))
+            )))
+        })
     }
 
-    pub fn fd_cwd(&self) -> io::Result<Fd> {
+    pub fn fd_cwd(&self) -> io::Result<OwnedFd> {
         self.fd(c_str!("cwd"), libc::O_DIRECTORY, 0)
     }
 
-    pub fn fd_num(&self, num: RawFd, flags: c_int) -> io::Result<Fd> {
+    pub fn fd_num(&self, num: RawFd, flags: c_int) -> io::Result<OwnedFd> {
         let path = format!("fd/{}\0", num);
         self.fd(
             unsafe { CStr::from_bytes_with_nul_unchecked(path.as_bytes()) },
index b8f7fbab19acb9933830fc207f584a8011b7805e..56ec33764a36b8c02d91f8f038ab48268eed4cfd 100644 (file)
@@ -1,5 +1,5 @@
 use std::ffi::CString;
-use std::os::unix::io::AsRawFd;
+use std::os::unix::io::{AsRawFd, OwnedFd};
 
 use anyhow::Error;
 use nix::errno::Errno;
@@ -10,7 +10,6 @@ use crate::lxcseccomp::ProxyMessageBuffer;
 use crate::process::PidFd;
 use crate::sc_libc_try;
 use crate::syscall::SyscallStatus;
-use crate::tools::Fd;
 
 pub async fn mknod(msg: &ProxyMessageBuffer) -> Result<SyscallStatus, Error> {
     let mode = msg.arg_mode_t(1)?;
@@ -61,7 +60,7 @@ fn check_mknod_dev(mode: stat::mode_t, dev: stat::dev_t) -> bool {
 
 async fn do_mknodat(
     pidfd: &PidFd,
-    dirfd: Fd,
+    dirfd: OwnedFd,
     pathname: CString,
     mode: stat::mode_t,
     dev: stat::dev_t,
index 0447027638fe89777a5b83a7fb592b2143e95990..d4be0667852afba886f20c1c172f2e60f9315a8b 100644 (file)
@@ -3,7 +3,7 @@
 //! Note that this should stay small, otherwise we should introduce a dependency on our `proxmox`
 //! crate as that's where we have all this stuff usually...
 
-use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
+use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
 
 pub fn set_fd_nonblocking<T: AsRawFd + ?Sized>(fd: &T, on: bool) -> nix::Result<libc::c_int> {
     use nix::fcntl;
@@ -13,33 +13,6 @@ pub fn set_fd_nonblocking<T: AsRawFd + ?Sized>(fd: &T, on: bool) -> nix::Result<
     fcntl::fcntl(fd, fcntl::FcntlArg::F_SETFL(flags))
 }
 
-/// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned
-/// `RawFd` is required without the corresponding handler object (such as when only the file
-/// descriptor number is required in a closure which may be dropped instead of being executed).
-#[repr(transparent)]
-pub struct Fd(pub RawFd);
-
-file_descriptor_impl!(Fd);
-
-impl FromRawFd for Fd {
-    unsafe fn from_raw_fd(fd: RawFd) -> Self {
-        Self(fd)
-    }
-}
-
-impl Fd {
-    pub fn set_nonblocking(&mut self, nb: bool) -> nix::Result<libc::c_int> {
-        set_fd_nonblocking(self, nb)
-    }
-}
-
-impl AsRef<RawFd> for Fd {
-    #[inline]
-    fn as_ref(&self) -> &RawFd {
-        &self.0
-    }
-}
-
 /// Byte vector utilities.
 pub mod vec {
     /// Create an uninitialized byte vector of a specific size.