Skip to main content

dope_sys/io/socket/addr/
mod.rs

1//! Native socket addresses.
2
3use std::{
4    marker, mem, net, num,
5    os::fd::{AsRawFd as _, BorrowedFd},
6    ptr,
7};
8
9use crate::{Errno, io, kernel};
10use io::socket::{self, Domain};
11
12mod internet;
13pub use internet::Internet;
14
15/// Exact byte capacity of one native socket-address buffer.
16pub const CAPACITY: usize = mem::size_of::<libc::sockaddr_storage>();
17
18/// Exact byte length of the namespace prefix every address carries.
19pub const FAMILY_BYTES: usize =
20    mem::offset_of!(libc::sockaddr_storage, ss_family) + mem::size_of::<libc::sa_family_t>();
21
22/// A validated nonzero native socket-address length.
23#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
24#[repr(transparent)]
25pub struct Socklen(num::NonZero<libc::socklen_t>);
26
27impl Socklen {
28    /// Exact length of one admitted address payload.
29    const fn of<T>() -> Self {
30        const {
31            assert!(
32                mem::size_of::<T>() > 0 && mem::size_of::<T>() <= CAPACITY,
33                "address payload does not fit sockaddr_storage",
34            );
35        }
36        Self(
37            num::NonZero::<libc::socklen_t>::MIN
38                .saturating_add(mem::size_of::<T>() as libc::socklen_t - 1),
39        )
40    }
41
42    /// Validates one observed length against the exact storage capacity.
43    fn try_from_len(len: usize) -> Option<Self> {
44        if len > CAPACITY {
45            return None;
46        }
47        num::NonZero::new(len as libc::socklen_t).map(Self)
48    }
49
50    pub const fn get(self) -> usize {
51        self.0.get() as usize
52    }
53
54    pub(crate) const fn raw(self) -> libc::socklen_t {
55        self.0.get()
56    }
57}
58
59/// Native encoding of the two-byte address header selected by its backend.
60pub trait Source {
61    /// Whether every pathname must retain a trailing NUL inside the path field.
62    const UNIX_TERMINATED: bool;
63    /// Whether a leading NUL selects the native abstract namespace.
64    const UNIX_ABSTRACT: bool;
65
66    fn header(domain: Domain, len: Socklen) -> [u8; 2];
67}
68
69/// One native Unix-domain socket address with its exact path length.
70#[derive(Clone, Copy)]
71pub struct Unix {
72    raw: libc::sockaddr_un,
73    len: Socklen,
74}
75
76enum Name {
77    Path,
78    Abstract,
79}
80
81impl Unix {
82    /// Encodes one pathname, proving it fits the platform's path field.
83    pub fn from_path<S: Source>(bytes: &[u8]) -> Result<Self, PathError> {
84        Self::encode::<S>(bytes, Name::Path)
85    }
86
87    /// Encodes an abstract name without adding a trailing NUL to its identity.
88    pub fn from_name<S: Source>(bytes: &[u8]) -> Result<Self, PathError> {
89        Self::encode::<S>(bytes, Name::Abstract)
90    }
91
92    fn encode<S: Source>(bytes: &[u8], name: Name) -> Result<Self, PathError> {
93        // SAFETY: zero initializes every native address field and path byte.
94        let mut raw: libc::sockaddr_un = unsafe { mem::zeroed() };
95        let capacity = raw.sun_path.len();
96        let (prefix, suffix) = match name {
97            Name::Path => {
98                PathError::check(bytes, capacity - usize::from(S::UNIX_TERMINATED))?;
99                (0, usize::from(bytes.len() < capacity))
100            }
101            Name::Abstract => {
102                if !S::UNIX_ABSTRACT {
103                    return Err(PathError::Unsupported);
104                }
105                PathError::length(bytes.len(), capacity - 1)?;
106                (1, 0)
107            }
108        };
109        for (dst, byte) in raw.sun_path.iter_mut().skip(prefix).zip(bytes) {
110            *dst = *byte as libc::c_char;
111        }
112        let len = num::NonZero::<libc::socklen_t>::MIN.saturating_add(
113            (mem::offset_of!(libc::sockaddr_un, sun_path) + prefix + bytes.len() + suffix - 1)
114                as libc::socklen_t,
115        );
116        let len = Socklen(len);
117        // SAFETY: the native header occupies the first two initialized bytes.
118        unsafe {
119            ptr::from_mut(&mut raw)
120                .cast::<[u8; 2]>()
121                .write(S::header(Domain::Unix, len))
122        };
123        Ok(Self { raw, len })
124    }
125
126    /// Typed view of this address for one syscall.
127    #[must_use]
128    pub fn as_addr(&self) -> Addr<'_> {
129        Addr::new(&self.raw, self.len)
130    }
131}
132
133/// An address length the kernel may overwrite in place.
134#[derive(Clone, Copy, Debug)]
135#[repr(transparent)]
136pub struct Length(libc::socklen_t);
137
138#[derive(Clone, Copy)]
139#[repr(transparent)]
140pub struct Buffer(libc::sockaddr_storage);
141
142/// One native address buffer with its exact length.
143#[derive(Clone, Copy)]
144#[repr(C)]
145pub struct Storage<L = Length> {
146    storage: Buffer,
147    len: L,
148}
149
150impl Storage<Length> {
151    #[must_use]
152    pub fn empty() -> Self {
153        Self {
154            storage: unsafe { mem::zeroed() },
155            len: Length(CAPACITY as libc::socklen_t),
156        }
157    }
158
159    /// Exclusive view of the buffer and the length the kernel overwrites.
160    pub fn output_mut(&mut self) -> (&mut Buffer, &mut u32) {
161        (&mut self.storage, &mut self.len.0)
162    }
163
164    pub fn prepare(&mut self) -> (&mut Buffer, &mut u32) {
165        self.len = Length(CAPACITY as libc::socklen_t);
166        self.output_mut()
167    }
168}
169
170impl Storage<Socklen> {
171    #[must_use]
172    pub fn as_addr(&self) -> Addr<'_> {
173        Addr::new(&self.storage, self.len)
174    }
175
176    /// Copies one exact native address view into a fresh buffer.
177    #[must_use]
178    pub fn from_addr(source: Addr<'_>) -> Self {
179        let (addr, len) = source.parts();
180        let mut out = Self {
181            storage: unsafe { mem::zeroed() },
182            len,
183        };
184        // SAFETY: the borrowed view retains its complete native payload; the
185        // admitted length fits this distinct destination without losing padding.
186        unsafe {
187            ptr::copy_nonoverlapping(
188                addr.cast::<u8>(),
189                ptr::from_mut(&mut out.storage).cast(),
190                len.get(),
191            )
192        };
193        out
194    }
195}
196
197const _: () = {
198    assert!(CAPACITY <= libc::socklen_t::MAX as usize);
199    let fields = CAPACITY + mem::size_of::<libc::socklen_t>();
200    let align = mem::align_of::<Storage<Socklen>>();
201    assert!(mem::size_of::<Storage<Socklen>>() == fields.div_ceil(align) * align);
202};
203
204/// Exact native address decoding failure.
205#[derive(Clone, Copy, Debug, Eq, PartialEq)]
206pub enum Error {
207    Storage {
208        actual: usize,
209        capacity: usize,
210    },
211    Header {
212        actual: usize,
213        required: usize,
214    },
215    Address {
216        family: i32,
217        actual: usize,
218        required: usize,
219    },
220    Unsupported {
221        family: i32,
222        actual: usize,
223    },
224}
225
226impl Storage<Socklen> {
227    pub fn to_std(&self) -> Result<net::SocketAddr, Error> {
228        self.as_addr().into_std()
229    }
230}
231
232impl Storage<Length> {
233    pub fn to_std(&self) -> Result<net::SocketAddr, Error> {
234        let actual = self.len.0 as usize;
235        if actual > CAPACITY {
236            return Err(Error::Storage {
237                actual,
238                capacity: CAPACITY,
239            });
240        }
241        // SAFETY: length admission covers these immutable native fields;
242        // native ABI padding need not be initialized.
243        unsafe { Internet::decode(ptr::from_ref(&self.storage.0).cast(), actual) }
244    }
245}
246
247/// Exact Unix-domain name validation failure.
248#[derive(Clone, Copy, Debug, Eq, PartialEq)]
249pub enum PathError {
250    Unsupported,
251    Empty,
252    Length { actual: usize, maximum: usize },
253    Nul { offset: usize },
254}
255
256impl PathError {
257    fn check(bytes: &[u8], maximum: usize) -> Result<(), Self> {
258        if bytes.is_empty() {
259            return Err(Self::Empty);
260        }
261        Self::length(bytes.len(), maximum)?;
262        if let Some(offset) = bytes.iter().position(|byte| *byte == 0) {
263            return Err(Self::Nul { offset });
264        }
265        Ok(())
266    }
267
268    fn length(actual: usize, maximum: usize) -> Result<(), Self> {
269        if actual > maximum {
270            return Err(Self::Length { actual, maximum });
271        }
272        Ok(())
273    }
274}
275
276/// Exact native address extent borrowed from its immutable owner.
277#[derive(Clone, Copy)]
278#[repr(C)]
279pub struct Addr<'a> {
280    addr: ptr::NonNull<libc::sockaddr>,
281    len: Socklen,
282    owner: marker::PhantomData<&'a libc::sockaddr>,
283}
284
285/// Exact failure while observing one descriptor's local address.
286#[derive(Clone, Copy, Debug, Eq, PartialEq)]
287pub enum Local<E> {
288    Syscall(E),
289    Length { actual: usize, capacity: usize },
290}
291
292impl<'a> Addr<'a> {
293    fn new<T>(storage: &'a T, len: Socklen) -> Self {
294        Self {
295            addr: ptr::NonNull::from(storage).cast(),
296            len,
297            owner: marker::PhantomData,
298        }
299    }
300
301    pub const fn parts(self) -> (*const (), Socklen) {
302        (self.addr.as_ptr().cast_const().cast(), self.len)
303    }
304
305    pub fn into_std(self) -> Result<net::SocketAddr, Error> {
306        // SAFETY: this borrow retains its admitted native extent and initialized
307        // fields; the shared decoder accepts unaligned fields and ABI padding.
308        unsafe { Internet::decode(self.addr.as_ptr().cast(), self.len.get()) }
309    }
310
311    pub fn local<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
312        file: BorrowedFd<'_>,
313        storage: &'a mut Storage<Length>,
314    ) -> Result<Self, Local<E>> {
315        socket::raw::name::<S, E, false>(file, storage).map_err(Local::Syscall)?;
316        let actual = storage.len.0 as usize;
317        let len = Socklen::try_from_len(actual).ok_or(Local::Length {
318            actual,
319            capacity: CAPACITY,
320        })?;
321        Ok(Self::new(&storage.storage, len))
322    }
323
324    pub fn try_bind<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
325        self,
326        file: BorrowedFd<'_>,
327    ) -> Result<(), E> {
328        // SAFETY: bind borrows this admitted extent and returns zero or -1 with errno.
329        unsafe {
330            let status = libc::bind(file.as_raw_fd(), self.addr.as_ptr(), self.len.raw());
331            io::raw::status::<S, E>(status)
332        }
333    }
334
335    pub fn try_connect<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
336        self,
337        file: BorrowedFd<'_>,
338    ) -> Result<(), E> {
339        // SAFETY: connect borrows this admitted extent and returns zero or -1 with errno.
340        unsafe {
341            let status = libc::connect(file.as_raw_fd(), self.addr.as_ptr(), self.len.raw());
342            io::raw::status::<S, E>(status)
343        }
344    }
345}