Skip to content

Commit d10f87e

Browse files
committed
Add SockAddrStorage type
1 parent 6828a5b commit d10f87e

File tree

5 files changed

+89
-43
lines changed

5 files changed

+89
-43
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -72,4 +72,5 @@ allowed_external_types = [
7272
"libc::*",
7373
# Referenced via a type alias.
7474
"windows_sys::Win32::Networking::WinSock::socklen_t",
75+
"windows_sys::Win32::Networking::WinSock::ADDRESS_FAMILY",
7576
]

src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ compile_error!("Socket2 doesn't support the compile target");
185185

186186
use sys::c_int;
187187

188-
pub use sockaddr::{socklen_t, SockAddr};
188+
pub use sockaddr::{sa_family_t, socklen_t, SockAddr, SockAddrStorage};
189189
pub use socket::Socket;
190190
pub use sockref::SockRef;
191191

src/sockaddr.rs

+73-26
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,71 @@
11
use std::hash::Hash;
2-
use std::mem::{self, size_of, MaybeUninit};
2+
use std::mem::{self, size_of};
33
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
44
use std::path::Path;
55
use std::{fmt, io, ptr};
66

77
#[cfg(windows)]
88
use windows_sys::Win32::Networking::WinSock::SOCKADDR_IN6_0;
99

10-
use crate::sys::{
11-
c_int, sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, AF_INET, AF_INET6,
12-
AF_UNIX,
13-
};
10+
use crate::sys::{c_int, sockaddr_in, sockaddr_in6, sockaddr_storage, AF_INET, AF_INET6, AF_UNIX};
1411
use crate::Domain;
1512

1613
/// The integer type used with `getsockname` on this platform.
1714
#[allow(non_camel_case_types)]
1815
pub type socklen_t = crate::sys::socklen_t;
1916

17+
/// The integer type for the `ss_family` field on this platform.
18+
#[allow(non_camel_case_types)]
19+
pub type sa_family_t = crate::sys::sa_family_t;
20+
21+
/// Rust version of the [`sockaddr_storage`] type.
22+
///
23+
/// This type is intended to be used with with direct calls to the `getsockname` syscall. See the
24+
/// documentation of [`SockAddr::new`] for examples.
25+
///
26+
/// This crate defines its own `sockaddr_storage` type to avoid semver concerns with upgrading
27+
/// `windows-sys`.
28+
#[repr(transparent)]
29+
pub struct SockAddrStorage {
30+
storage: sockaddr_storage,
31+
}
32+
33+
impl SockAddrStorage {
34+
/// Construct a new storage containing all zeros.
35+
#[inline]
36+
pub fn zeroed() -> Self {
37+
// SAFETY: All zeros is valid for this type.
38+
unsafe { mem::zeroed() }
39+
}
40+
41+
/// Returns the size of this storage.
42+
#[inline]
43+
pub fn size_of(&self) -> socklen_t {
44+
size_of::<Self>() as socklen_t
45+
}
46+
47+
/// View this type as another type.
48+
///
49+
/// # Safety
50+
///
51+
/// The type `T` must be one of the `sockaddr_*` types defined by this platform.
52+
#[inline]
53+
pub unsafe fn view_as<T>(&mut self) -> &mut T {
54+
assert!(size_of::<T>() <= size_of::<Self>());
55+
// SAFETY: This type is repr(transparent) over `sockaddr_storage` and `T` is one of the
56+
// `sockaddr_*` types defined by this platform.
57+
unsafe { &mut *(self as *mut Self as *mut T) }
58+
}
59+
}
60+
61+
impl std::fmt::Debug for SockAddrStorage {
62+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63+
f.debug_struct("sockaddr_storage")
64+
.field("ss_family", &self.storage.ss_family)
65+
.finish_non_exhaustive()
66+
}
67+
}
68+
2069
/// The address of a socket.
2170
///
2271
/// `SockAddr`s may be constructed directly to and from the standard library
@@ -44,23 +93,22 @@ impl SockAddr {
4493
/// # fn main() -> std::io::Result<()> {
4594
/// # #[cfg(unix)] {
4695
/// use std::io;
47-
/// use std::mem;
4896
/// use std::os::unix::io::AsRawFd;
4997
///
50-
/// use socket2::{SockAddr, Socket, Domain, Type};
98+
/// use socket2::{SockAddr, SockAddrStorage, Socket, Domain, Type};
5199
///
52100
/// let socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
53101
///
54102
/// // Initialise a `SocketAddr` byte calling `getsockname(2)`.
55-
/// let mut addr_storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
56-
/// let mut len = mem::size_of_val(&addr_storage) as libc::socklen_t;
103+
/// let mut addr_storage = SockAddrStorage::zeroed();
104+
/// let mut len = addr_storage.size_of();
57105
///
58106
/// // The `getsockname(2)` system call will intiliase `storage` for
59107
/// // us, setting `len` to the correct length.
60108
/// let res = unsafe {
61109
/// libc::getsockname(
62110
/// socket.as_raw_fd(),
63-
/// (&mut addr_storage as *mut libc::sockaddr_storage).cast(),
111+
/// addr_storage.view_as(),
64112
/// &mut len,
65113
/// )
66114
/// };
@@ -74,8 +122,11 @@ impl SockAddr {
74122
/// # Ok(())
75123
/// # }
76124
/// ```
77-
pub const unsafe fn new(storage: sockaddr_storage, len: socklen_t) -> SockAddr {
78-
SockAddr { storage, len }
125+
pub const unsafe fn new(storage: SockAddrStorage, len: socklen_t) -> SockAddr {
126+
SockAddr {
127+
storage: storage.storage,
128+
len: len as socklen_t,
129+
}
79130
}
80131

81132
/// Initialise a `SockAddr` by calling the function `init`.
@@ -125,25 +176,19 @@ impl SockAddr {
125176
/// ```
126177
pub unsafe fn try_init<F, T>(init: F) -> io::Result<(T, SockAddr)>
127178
where
128-
F: FnOnce(*mut sockaddr_storage, *mut socklen_t) -> io::Result<T>,
179+
F: FnOnce(*mut SockAddrStorage, *mut socklen_t) -> io::Result<T>,
129180
{
130181
const STORAGE_SIZE: socklen_t = size_of::<sockaddr_storage>() as socklen_t;
131182
// NOTE: `SockAddr::unix` depends on the storage being zeroed before
132183
// calling `init`.
133184
// NOTE: calling `recvfrom` with an empty buffer also depends on the
134185
// storage being zeroed before calling `init` as the OS might not
135186
// initialise it.
136-
let mut storage = MaybeUninit::<sockaddr_storage>::zeroed();
187+
let mut storage = SockAddrStorage::zeroed();
137188
let mut len = STORAGE_SIZE;
138-
init(storage.as_mut_ptr(), &mut len).map(|res| {
189+
init(&mut storage, &mut len).map(|res| {
139190
debug_assert!(len <= STORAGE_SIZE, "overflown address storage");
140-
let addr = SockAddr {
141-
// Safety: zeroed-out `sockaddr_storage` is valid, caller must
142-
// ensure at least `len` bytes are valid.
143-
storage: storage.assume_init(),
144-
len,
145-
};
146-
(res, addr)
191+
(res, SockAddr::new(storage, len))
147192
})
148193
}
149194

@@ -183,13 +228,15 @@ impl SockAddr {
183228
}
184229

185230
/// Returns a raw pointer to the address.
186-
pub const fn as_ptr(&self) -> *const sockaddr {
187-
ptr::addr_of!(self.storage).cast()
231+
pub const fn as_ptr(&self) -> *const SockAddrStorage {
232+
&self.storage as *const sockaddr_storage as *const SockAddrStorage
188233
}
189234

190235
/// Retuns the address as the storage.
191-
pub const fn as_storage(self) -> sockaddr_storage {
192-
self.storage
236+
pub const fn as_storage(self) -> SockAddrStorage {
237+
SockAddrStorage {
238+
storage: self.storage,
239+
}
193240
}
194241

195242
/// Returns true if this address is in the `AF_INET` (IPv4) family, false otherwise.

src/sys/unix.rs

+10-11
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ use std::{io, slice};
7676
use libc::ssize_t;
7777
use libc::{in6_addr, in_addr};
7878

79-
use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type};
79+
use crate::{Domain, Protocol, SockAddr, SockAddrStorage, TcpKeepalive, Type};
8080
#[cfg(not(target_os = "redox"))]
8181
use crate::{MsgHdr, MsgHdrMut, RecvFlags};
8282

@@ -640,10 +640,10 @@ pub(crate) fn offset_of_path(storage: &libc::sockaddr_un) -> usize {
640640

641641
#[allow(unsafe_op_in_unsafe_fn)]
642642
pub(crate) fn unix_sockaddr(path: &Path) -> io::Result<SockAddr> {
643-
// SAFETY: a `sockaddr_storage` of all zeros is valid.
644-
let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
643+
let mut storage = SockAddrStorage::zeroed();
645644
let len = {
646-
let storage = unsafe { &mut *ptr::addr_of_mut!(storage).cast::<libc::sockaddr_un>() };
645+
// SAFETY: sockaddr_un is one of the sockaddr_* types defined by this platform.
646+
let storage = unsafe { storage.view_as::<libc::sockaddr_un>() };
647647

648648
let bytes = path.as_os_str().as_bytes();
649649
let too_long = match bytes.first() {
@@ -732,11 +732,10 @@ impl SockAddr {
732732
#[allow(unsafe_op_in_unsafe_fn)]
733733
#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
734734
pub fn vsock(cid: u32, port: u32) -> SockAddr {
735-
// SAFETY: a `sockaddr_storage` of all zeros is valid.
736-
let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
735+
let mut storage = SockAddrStorage::zeroed();
737736
{
738-
let storage: &mut libc::sockaddr_vm =
739-
unsafe { &mut *((&mut storage as *mut sockaddr_storage).cast()) };
737+
// SAFETY: sockaddr_vm is one of the sockaddr_* types defined by this platform.
738+
let storage = unsafe { storage.view_as::<libc::sockaddr_vm>() };
740739
storage.svm_family = libc::AF_VSOCK as sa_family_t;
741740
storage.svm_cid = cid;
742741
storage.svm_port = port;
@@ -877,11 +876,11 @@ pub(crate) fn socketpair(family: c_int, ty: c_int, protocol: c_int) -> io::Resul
877876
}
878877

879878
pub(crate) fn bind(fd: Socket, addr: &SockAddr) -> io::Result<()> {
880-
syscall!(bind(fd, addr.as_ptr(), addr.len() as _)).map(|_| ())
879+
syscall!(bind(fd, addr.as_ptr().cast::<sockaddr>(), addr.len() as _)).map(|_| ())
881880
}
882881

883882
pub(crate) fn connect(fd: Socket, addr: &SockAddr) -> io::Result<()> {
884-
syscall!(connect(fd, addr.as_ptr(), addr.len())).map(|_| ())
883+
syscall!(connect(fd, addr.as_ptr().cast::<sockaddr>(), addr.len())).map(|_| ())
885884
}
886885

887886
pub(crate) fn poll_connect(socket: &crate::Socket, timeout: Duration) -> io::Result<()> {
@@ -1098,7 +1097,7 @@ pub(crate) fn send_to(fd: Socket, buf: &[u8], addr: &SockAddr, flags: c_int) ->
10981097
buf.as_ptr().cast(),
10991098
min(buf.len(), MAX_BUF_LEN),
11001099
flags,
1101-
addr.as_ptr(),
1100+
addr.as_ptr().cast::<sockaddr>(),
11021101
addr.len(),
11031102
))
11041103
.map(|n| n as usize)

src/sys/windows.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use windows_sys::Win32::Networking::WinSock::{
3232
};
3333
use windows_sys::Win32::System::Threading::INFINITE;
3434

35-
use crate::{MsgHdr, RecvFlags, SockAddr, TcpKeepalive, Type};
35+
use crate::{MsgHdr, RecvFlags, SockAddr, SockAddrStorage, TcpKeepalive, Type};
3636

3737
#[allow(non_camel_case_types)]
3838
pub(crate) type c_int = std::os::raw::c_int;
@@ -900,11 +900,10 @@ pub(crate) fn original_dst_ipv6(socket: Socket) -> io::Result<SockAddr> {
900900

901901
#[allow(unsafe_op_in_unsafe_fn)]
902902
pub(crate) fn unix_sockaddr(path: &Path) -> io::Result<SockAddr> {
903-
// SAFETY: a `sockaddr_storage` of all zeros is valid.
904-
let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
903+
let mut storage = SockAddrStorage::zeroed();
905904
let len = {
906-
let storage: &mut windows_sys::Win32::Networking::WinSock::SOCKADDR_UN =
907-
unsafe { &mut *(&mut storage as *mut sockaddr_storage).cast() };
905+
let storage =
906+
unsafe { storage.view_as::<windows_sys::Win32::Networking::WinSock::SOCKADDR_UN>() };
908907

909908
// Windows expects a UTF-8 path here even though Windows paths are
910909
// usually UCS-2 encoded. If Rust exposed OsStr's Wtf8 encoded

0 commit comments

Comments
 (0)