From 56e3d56c25287ff1afebbb88cf7c1c70cbf5b3ce Mon Sep 17 00:00:00 2001 From: Johnathan Corgan Date: Mon, 13 Jul 2026 09:20:04 +0000 Subject: [PATCH] peer/connected_udp: own the connected-socket fd with OwnedFd Replace the hand-rolled RawFd field and the unsafe Drop on ConnectedPeerSocket with an OwnedFd, whose own drop glue closes the fd. from_fd now stores the OwnedFd it already receives instead of stripping ownership through into_raw_fd, and the manual libc::close is gone, shrinking the unsafe surface. Behavior-neutral: the fd still closes exactly once at last-Arc-drop and as_raw_fd returns the same underlying fd while the socket is alive. --- src/peer/connected_udp/socket.rs | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/src/peer/connected_udp/socket.rs b/src/peer/connected_udp/socket.rs index 85b709a..8b54e54 100644 --- a/src/peer/connected_udp/socket.rs +++ b/src/peer/connected_udp/socket.rs @@ -6,7 +6,7 @@ #![allow(dead_code)] use std::net::SocketAddr; -use std::os::unix::io::{AsRawFd, IntoRawFd, OwnedFd, RawFd}; +use std::os::unix::io::{AsRawFd, OwnedFd, RawFd}; /// A `connect()`-ed UDP socket for one established peer. /// @@ -26,7 +26,7 @@ use std::os::unix::io::{AsRawFd, IntoRawFd, OwnedFd, RawFd}; /// needs to be redone on the data path. #[derive(Debug)] pub(crate) struct ConnectedPeerSocket { - fd: RawFd, + fd: OwnedFd, peer_addr: SocketAddr, local_addr: SocketAddr, } @@ -34,10 +34,10 @@ pub(crate) struct ConnectedPeerSocket { impl ConnectedPeerSocket { /// Adopt an already-opened, bound, and `connect()`-ed fd (from /// `crate::transport::udp::open_connected_fd`) into an owning - /// handle. Takes ownership of the fd; it is closed on drop. + /// handle. Takes ownership of the fd; the `OwnedFd` closes it on drop. pub(crate) fn from_fd(fd: OwnedFd, peer_addr: SocketAddr, local_addr: SocketAddr) -> Self { Self { - fd: fd.into_raw_fd(), + fd, peer_addr, local_addr, } @@ -55,18 +55,7 @@ impl ConnectedPeerSocket { impl AsRawFd for ConnectedPeerSocket { fn as_raw_fd(&self) -> RawFd { - self.fd - } -} - -impl Drop for ConnectedPeerSocket { - fn drop(&mut self) { - // Best-effort close. Ignore the result — if close fails the - // kernel has already done what it can; we don't want to panic - // in Drop. - unsafe { - libc::close(self.fd); - } + self.fd.as_raw_fd() } }