Skip to content

Commit

Permalink
Assert validity on the raw socket in SockRef::from
Browse files Browse the repository at this point in the history
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
  • Loading branch information
Thomasdezeeuw committed Jul 28, 2021
1 parent e00edab commit 086dcd9
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/sockref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,10 @@ where
{
/// The caller must ensure `S` is actually a socket.
fn from(socket: &'s S) -> Self {
let fd = socket.as_raw_fd();
assert!(fd >= 0);
SockRef {
socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(socket.as_raw_fd()) }),
socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(fd) }),
_lifetime: PhantomData,
}
}
Expand All @@ -125,8 +127,10 @@ where
{
/// See the `From<&impl AsRawFd>` implementation.
fn from(socket: &'s S) -> Self {
let socket = socket.as_raw_socket();
assert!(socket != winapi::um::winsock2::INVALID_SOCKET);
SockRef {
socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket.as_raw_socket()) }),
socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket) }),
_lifetime: PhantomData,
}
}
Expand All @@ -141,3 +145,12 @@ impl fmt::Debug for SockRef<'_> {
.finish()
}
}

#[test]
#[should_panic]
fn sockref_from_invalid_fd() {
#[cfg(unix)]
let _ = SockRef::from(&-1);
#[cfg(windows)]
let _ = SockRef::from(&winapi::um::winsock2::INVALID_SOCKET);
}

0 comments on commit 086dcd9

Please sign in to comment.