Skip to content

Commit 086dcd9

Browse files
committed
Assert validity on the raw socket in SockRef::from
Since we now use the niche feature on Unix it's unsound to use SockRef::from(-1), but it can be done without any unsafe. This change adds an assertion to ensure we hit this soundness issue. Still need to wait on the I/O safety RFC: https://github.com/rust-lang/rfcs/blob/master/text/3128-io-safety.md Tracking issue: rust-lang/rust#87074 Implementation pr: rust-lang/rust#87329
1 parent e00edab commit 086dcd9

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/sockref.rs

+15-2
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,10 @@ where
109109
{
110110
/// The caller must ensure `S` is actually a socket.
111111
fn from(socket: &'s S) -> Self {
112+
let fd = socket.as_raw_fd();
113+
assert!(fd >= 0);
112114
SockRef {
113-
socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(socket.as_raw_fd()) }),
115+
socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(fd) }),
114116
_lifetime: PhantomData,
115117
}
116118
}
@@ -125,8 +127,10 @@ where
125127
{
126128
/// See the `From<&impl AsRawFd>` implementation.
127129
fn from(socket: &'s S) -> Self {
130+
let socket = socket.as_raw_socket();
131+
assert!(socket != winapi::um::winsock2::INVALID_SOCKET);
128132
SockRef {
129-
socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket.as_raw_socket()) }),
133+
socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket) }),
130134
_lifetime: PhantomData,
131135
}
132136
}
@@ -141,3 +145,12 @@ impl fmt::Debug for SockRef<'_> {
141145
.finish()
142146
}
143147
}
148+
149+
#[test]
150+
#[should_panic]
151+
fn sockref_from_invalid_fd() {
152+
#[cfg(unix)]
153+
let _ = SockRef::from(&-1);
154+
#[cfg(windows)]
155+
let _ = SockRef::from(&winapi::um::winsock2::INVALID_SOCKET);
156+
}

0 commit comments

Comments
 (0)