Skip to main content

dope_sys/io/socket/addr/
mod.rs

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