Skip to content

Commit f32461a

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 f32461a

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/sockref.rs

+14-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 as _);
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,11 @@ impl fmt::Debug for SockRef<'_> {
141145
.finish()
142146
}
143147
}
148+
149+
#[test]
150+
#[should_panic]
151+
#[cfg(unix)]
152+
fn sockref_from_invalid_fd() {
153+
let raw: std::os::unix::io::RawFd = -1;
154+
let _ = SockRef::from(&raw);
155+
}

0 commit comments

Comments
 (0)