1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
|
//! The [`SocketAddrAny`] type and related utilities.
#![allow(unsafe_code)]
use crate::backend::c;
use crate::backend::net::read_sockaddr;
use crate::io::Errno;
use crate::net::addr::{SocketAddrArg, SocketAddrLen, SocketAddrOpaque, SocketAddrStorage};
#[cfg(unix)]
use crate::net::SocketAddrUnix;
use crate::net::{AddressFamily, SocketAddr, SocketAddrV4, SocketAddrV6};
use core::fmt;
use core::mem::{size_of, MaybeUninit};
use core::num::NonZeroU32;
/// Temporary buffer for creating a `SocketAddrAny` from a syscall that writes
/// to a `sockaddr_t` and `socklen_t`
///
/// Unlike `SocketAddrAny`, this does not maintain the invariant that `len`
/// bytes are initialized.
pub(crate) struct SocketAddrBuf {
pub(crate) len: c::socklen_t,
pub(crate) storage: MaybeUninit<SocketAddrStorage>,
}
impl SocketAddrBuf {
#[inline]
pub(crate) const fn new() -> Self {
Self {
len: size_of::<SocketAddrStorage>() as c::socklen_t,
storage: MaybeUninit::<SocketAddrStorage>::uninit(),
}
}
/// Convert the buffer into [`SocketAddrAny`].
///
/// # Safety
///
/// A valid address must have been written into `self.storage` and its
/// length written into `self.len`.
#[inline]
pub(crate) unsafe fn into_any(self) -> SocketAddrAny {
SocketAddrAny::new(self.storage, bitcast!(self.len))
}
/// Convert the buffer into [`Option<SocketAddrAny>`].
///
/// This returns `None` if `len` is zero or other platform-specific
/// conditions define the address as empty.
///
/// # Safety
///
/// Either valid address must have been written into `self.storage` and its
/// length written into `self.len`, or `self.len` must have been set to 0.
#[inline]
pub(crate) unsafe fn into_any_option(self) -> Option<SocketAddrAny> {
let len = bitcast!(self.len);
if read_sockaddr::sockaddr_nonempty(self.storage.as_ptr().cast(), len) {
Some(SocketAddrAny::new(self.storage, len))
} else {
None
}
}
}
/// A type that can hold any kind of socket address, as a safe abstraction for
/// `sockaddr_storage`.
///
/// Socket addresses can be converted to `SocketAddrAny` via the [`From`] and
/// [`Into`] traits. `SocketAddrAny` can be converted back to a specific socket
/// address type with [`TryFrom`] and [`TryInto`]. These implementations return
/// [`Errno::AFNOSUPPORT`] if the address family does not match the requested
/// type.
#[derive(Clone)]
#[doc(alias = "sockaddr_storage")]
pub struct SocketAddrAny {
// Invariants:
// - `len` is at least `size_of::<backend::c::sa_family_t>()`
// - `len` is at most `size_of::<SocketAddrStorage>()`
// - The first `len` bytes of `storage` are initialized.
pub(crate) len: NonZeroU32,
pub(crate) storage: MaybeUninit<SocketAddrStorage>,
}
impl SocketAddrAny {
/// Creates a socket address from `storage`, which is initialized for `len`
/// bytes.
///
/// # Panics
///
/// if `len` is smaller than the sockaddr header or larger than
/// `SocketAddrStorage`.
///
/// # Safety
///
/// - `storage` must contain a valid socket address.
/// - `len` bytes must be initialized.
#[inline]
pub const unsafe fn new(storage: MaybeUninit<SocketAddrStorage>, len: SocketAddrLen) -> Self {
assert!(len as usize >= size_of::<read_sockaddr::sockaddr_header>());
assert!(len as usize <= size_of::<SocketAddrStorage>());
let len = NonZeroU32::new_unchecked(len);
Self { storage, len }
}
/// Creates a socket address from reading from `ptr`, which points at `len`
/// initialized bytes.
///
/// # Panics
///
/// if `len` is smaller than the sockaddr header or larger than
/// `SocketAddrStorage`.
///
/// # Safety
///
/// - `ptr` must be a pointer to memory containing a valid socket address.
/// - `len` bytes must be initialized.
pub unsafe fn read(ptr: *const SocketAddrStorage, len: SocketAddrLen) -> Self {
assert!(len as usize >= size_of::<read_sockaddr::sockaddr_header>());
assert!(len as usize <= size_of::<SocketAddrStorage>());
let mut storage = MaybeUninit::<SocketAddrStorage>::uninit();
core::ptr::copy_nonoverlapping(
ptr.cast::<u8>(),
storage.as_mut_ptr().cast::<u8>(),
len as usize,
);
let len = NonZeroU32::new_unchecked(len);
Self { storage, len }
}
/// Gets the initialized part of the storage as bytes.
#[inline]
fn bytes(&self) -> &[u8] {
let len = self.len.get() as usize;
unsafe { core::slice::from_raw_parts(self.storage.as_ptr().cast(), len) }
}
/// Gets the address family of this socket address.
#[inline]
pub fn address_family(&self) -> AddressFamily {
// SAFETY: Our invariants maintain that the `sa_family` field is
// initialized.
unsafe {
AddressFamily::from_raw(crate::backend::net::read_sockaddr::read_sa_family(
self.storage.as_ptr().cast(),
))
}
}
/// Returns a raw pointer to the sockaddr.
#[inline]
pub fn as_ptr(&self) -> *const SocketAddrStorage {
self.storage.as_ptr()
}
/// Returns a raw mutable pointer to the sockaddr.
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut SocketAddrStorage {
self.storage.as_mut_ptr()
}
/// Returns the length of the encoded sockaddr.
#[inline]
pub fn addr_len(&self) -> SocketAddrLen {
self.len.get()
}
}
impl PartialEq<Self> for SocketAddrAny {
fn eq(&self, other: &Self) -> bool {
self.bytes() == other.bytes()
}
}
impl Eq for SocketAddrAny {}
// This just forwards to another `partial_cmp`.
#[allow(clippy::non_canonical_partial_ord_impl)]
impl PartialOrd<Self> for SocketAddrAny {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
self.bytes().partial_cmp(other.bytes())
}
}
impl Ord for SocketAddrAny {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.bytes().cmp(other.bytes())
}
}
impl core::hash::Hash for SocketAddrAny {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bytes().hash(state)
}
}
impl fmt::Debug for SocketAddrAny {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.address_family() {
AddressFamily::INET => {
if let Ok(addr) = SocketAddrV4::try_from(self.clone()) {
return addr.fmt(f);
}
}
AddressFamily::INET6 => {
if let Ok(addr) = SocketAddrV6::try_from(self.clone()) {
return addr.fmt(f);
}
}
#[cfg(unix)]
AddressFamily::UNIX => {
if let Ok(addr) = SocketAddrUnix::try_from(self.clone()) {
return addr.fmt(f);
}
}
#[cfg(target_os = "linux")]
AddressFamily::XDP => {
if let Ok(addr) = crate::net::xdp::SocketAddrXdp::try_from(self.clone()) {
return addr.fmt(f);
}
}
#[cfg(linux_kernel)]
AddressFamily::NETLINK => {
if let Ok(addr) = crate::net::netlink::SocketAddrNetlink::try_from(self.clone()) {
return addr.fmt(f);
}
}
_ => {}
}
f.debug_struct("SocketAddrAny")
.field("address_family", &self.address_family())
.field("namelen", &self.addr_len())
.finish()
}
}
// SAFETY: `with_sockaddr` calls `f` with a pointer to its own storage.
unsafe impl SocketAddrArg for SocketAddrAny {
unsafe fn with_sockaddr<R>(
&self,
f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R,
) -> R {
f(self.as_ptr().cast(), self.addr_len())
}
}
impl From<SocketAddr> for SocketAddrAny {
#[inline]
fn from(from: SocketAddr) -> Self {
from.as_any()
}
}
impl TryFrom<SocketAddrAny> for SocketAddr {
type Error = Errno;
/// Convert if the address is an IPv4 or IPv6 address.
///
/// Returns `Err(Errno::AFNOSUPPORT)` if the address family is not IPv4 or
/// IPv6.
#[inline]
fn try_from(value: SocketAddrAny) -> Result<Self, Self::Error> {
match value.address_family() {
AddressFamily::INET => read_sockaddr::read_sockaddr_v4(&value).map(SocketAddr::V4),
AddressFamily::INET6 => read_sockaddr::read_sockaddr_v6(&value).map(SocketAddr::V6),
_ => Err(Errno::AFNOSUPPORT),
}
}
}
impl From<SocketAddrV4> for SocketAddrAny {
#[inline]
fn from(from: SocketAddrV4) -> Self {
from.as_any()
}
}
impl TryFrom<SocketAddrAny> for SocketAddrV4 {
type Error = Errno;
/// Convert if the address is an IPv4 address.
///
/// Returns `Err(Errno::AFNOSUPPORT)` if the address family is not IPv4.
#[inline]
fn try_from(value: SocketAddrAny) -> Result<Self, Self::Error> {
read_sockaddr::read_sockaddr_v4(&value)
}
}
impl From<SocketAddrV6> for SocketAddrAny {
#[inline]
fn from(from: SocketAddrV6) -> Self {
from.as_any()
}
}
impl TryFrom<SocketAddrAny> for SocketAddrV6 {
type Error = Errno;
/// Convert if the address is an IPv6 address.
///
/// Returns `Err(Errno::AFNOSUPPORT)` if the address family is not IPv6.
#[inline]
fn try_from(value: SocketAddrAny) -> Result<Self, Self::Error> {
read_sockaddr::read_sockaddr_v6(&value)
}
}
#[cfg(unix)]
impl From<SocketAddrUnix> for SocketAddrAny {
#[inline]
fn from(from: SocketAddrUnix) -> Self {
from.as_any()
}
}
#[cfg(unix)]
impl TryFrom<SocketAddrAny> for SocketAddrUnix {
type Error = Errno;
/// Convert if the address is a Unix socket address.
///
/// Returns `Err(Errno::AFNOSUPPORT)` if the address family is not Unix.
#[inline]
fn try_from(value: SocketAddrAny) -> Result<Self, Self::Error> {
read_sockaddr::read_sockaddr_unix(&value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn any_read() {
let localhost = std::net::Ipv6Addr::LOCALHOST;
let addr = SocketAddrAny::from(SocketAddrV6::new(localhost, 7, 8, 9));
unsafe {
let same = SocketAddrAny::read(addr.as_ptr(), addr.addr_len());
assert_eq!(addr, same);
}
}
}
|