1use std::{
4 marker, mem, net, num,
5 os::fd::{AsRawFd as _, BorrowedFd},
6 ptr,
7};
8
9use crate::{Errno, io::socket::Domain, kernel};
10
11mod internet;
12pub use internet::Internet;
13
14pub const CAPACITY: usize = mem::size_of::<libc::sockaddr_storage>();
16
17pub const FAMILY_BYTES: usize =
19 mem::offset_of!(libc::sockaddr_storage, ss_family) + mem::size_of::<libc::sa_family_t>();
20
21#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
23#[repr(transparent)]
24pub struct Socklen(num::NonZero<libc::socklen_t>);
25
26impl Socklen {
27 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 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
58pub trait Source {
60 const UNIX_TERMINATED: bool;
62 const UNIX_ABSTRACT: bool;
64
65 fn header(domain: Domain, len: Socklen) -> [u8; 2];
66}
67
68#[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 pub fn from_path<S: Source>(bytes: &[u8]) -> Result<Self, PathError> {
83 Self::encode::<S>(bytes, Name::Path)
84 }
85
86 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 mut raw: libc::sockaddr_un = unsafe { mem::zeroed() };
94 let capacity = raw.sun_path.len();
95 let (prefix, suffix) = match name {
96 Name::Path => {
97 PathError::check(bytes, capacity - usize::from(S::UNIX_TERMINATED))?;
98 (0, usize::from(bytes.len() < capacity))
99 }
100 Name::Abstract => {
101 if !S::UNIX_ABSTRACT {
102 return Err(PathError::Unsupported);
103 }
104 PathError::length(bytes.len(), capacity - 1)?;
105 (1, 0)
106 }
107 };
108 for (dst, byte) in raw.sun_path.iter_mut().skip(prefix).zip(bytes) {
109 *dst = *byte as libc::c_char;
110 }
111 let len = num::NonZero::<libc::socklen_t>::MIN.saturating_add(
112 (mem::offset_of!(libc::sockaddr_un, sun_path) + prefix + bytes.len() + suffix - 1)
113 as libc::socklen_t,
114 );
115 let len = Socklen(len);
116 unsafe {
118 ptr::from_mut(&mut raw)
119 .cast::<[u8; 2]>()
120 .write(S::header(Domain::Unix, len))
121 };
122 Ok(Self { raw, len })
123 }
124
125 #[must_use]
127 pub fn as_addr(&self) -> Addr<'_> {
128 Addr::new(&self.raw, self.len)
129 }
130}
131
132#[derive(Clone, Copy, Debug)]
134#[repr(transparent)]
135pub struct Length(libc::socklen_t);
136
137#[derive(Clone, Copy)]
139#[repr(C)]
140pub struct Storage<L = Length> {
141 storage: libc::sockaddr_storage,
142 len: L,
143}
144
145impl Storage<Length> {
146 #[must_use]
147 pub fn empty() -> Self {
148 Self {
149 storage: unsafe { mem::zeroed() },
150 len: Length(CAPACITY as libc::socklen_t),
151 }
152 }
153
154 pub fn output_mut(&mut self) -> (&mut libc::sockaddr_storage, &mut libc::socklen_t) {
156 (&mut self.storage, &mut self.len.0)
157 }
158
159 pub fn prepare_output(&mut self) -> (&mut libc::sockaddr_storage, &mut libc::socklen_t) {
160 self.len = Length(CAPACITY as libc::socklen_t);
161 self.output_mut()
162 }
163}
164
165impl Storage<Socklen> {
166 #[must_use]
167 pub fn as_addr(&self) -> Addr<'_> {
168 Addr::new(&self.storage, self.len)
169 }
170
171 #[must_use]
173 pub fn from_addr(source: Addr<'_>) -> Self {
174 let (addr, len) = source.parts();
175 let mut out = Self {
176 storage: unsafe { mem::zeroed() },
177 len,
178 };
179 unsafe {
182 ptr::copy_nonoverlapping(
183 addr.cast::<u8>(),
184 ptr::from_mut(&mut out.storage).cast(),
185 len.get(),
186 )
187 };
188 out
189 }
190}
191
192impl<L> Storage<L> {
193 fn decode(&self, actual: usize) -> Result<net::SocketAddr, Error> {
194 unsafe { Internet::decode(ptr::from_ref(&self.storage).cast(), actual) }
197 }
198}
199
200const _: () = {
201 assert!(CAPACITY <= libc::socklen_t::MAX as usize);
202 let fields = CAPACITY + mem::size_of::<libc::socklen_t>();
203 let align = mem::align_of::<Storage<Socklen>>();
204 assert!(mem::size_of::<Storage<Socklen>>() == fields.div_ceil(align) * align);
205};
206
207#[derive(Clone, Copy, Debug, Eq, PartialEq)]
209pub enum Error {
210 Storage {
211 actual: usize,
212 capacity: usize,
213 },
214 Header {
215 actual: usize,
216 required: usize,
217 },
218 Address {
219 family: i32,
220 actual: usize,
221 required: usize,
222 },
223 Unsupported {
224 family: i32,
225 actual: usize,
226 },
227}
228
229impl Storage<Socklen> {
230 pub fn to_std(&self) -> Result<net::SocketAddr, Error> {
231 self.decode(self.len.get())
232 }
233}
234
235impl Storage<Length> {
236 #[inline]
237 pub fn to_std(&self) -> Result<net::SocketAddr, Error> {
238 let actual = self.len.0 as usize;
239 if actual > CAPACITY {
240 return Err(Error::Storage {
241 actual,
242 capacity: CAPACITY,
243 });
244 }
245 self.decode(actual)
246 }
247}
248
249#[derive(Clone, Copy, Debug, Eq, PartialEq)]
251pub enum PathError {
252 Unsupported,
253 Empty,
254 Length { actual: usize, maximum: usize },
255 Nul { offset: usize },
256}
257
258impl PathError {
259 fn check(bytes: &[u8], maximum: usize) -> Result<(), Self> {
260 if bytes.is_empty() {
261 return Err(Self::Empty);
262 }
263 Self::length(bytes.len(), maximum)?;
264 if let Some(offset) = bytes.iter().position(|byte| *byte == 0) {
265 return Err(Self::Nul { offset });
266 }
267 Ok(())
268 }
269
270 fn length(actual: usize, maximum: usize) -> Result<(), Self> {
271 if actual > maximum {
272 return Err(Self::Length { actual, maximum });
273 }
274 Ok(())
275 }
276}
277
278#[derive(Clone, Copy)]
280#[repr(C)]
281pub struct Addr<'a> {
282 addr: ptr::NonNull<libc::sockaddr>,
283 len: Socklen,
284 owner: marker::PhantomData<&'a libc::sockaddr>,
285}
286
287#[derive(Clone, Copy, Debug, Eq, PartialEq)]
289pub enum Local<E> {
290 Syscall(E),
291 Length { actual: usize, capacity: usize },
292}
293
294impl<'a> Addr<'a> {
295 fn new<T>(storage: &'a T, len: Socklen) -> Self {
296 Self {
297 addr: ptr::NonNull::from(storage).cast(),
298 len,
299 owner: marker::PhantomData,
300 }
301 }
302
303 pub const fn parts(self) -> (*const libc::sockaddr, Socklen) {
304 (self.addr.as_ptr().cast_const(), self.len)
305 }
306
307 pub fn local<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
308 file: BorrowedFd<'_>,
309 storage: &'a mut Storage<Length>,
310 ) -> Result<Self, Local<E>> {
311 let (address, length) = storage.prepare_output();
312 let status =
315 unsafe { libc::getsockname(file.as_raw_fd(), ptr::from_mut(address).cast(), length) };
316 unsafe { kernel::raw::Status::new(status).try_zero::<S, E>() }.map_err(Local::Syscall)?;
318 let actual = *length as usize;
319 let len = Socklen::try_from_len(actual).ok_or(Local::Length {
320 actual,
321 capacity: CAPACITY,
322 })?;
323 Ok(Self::new(&storage.storage, len))
324 }
325
326 pub fn try_bind<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
327 self,
328 file: BorrowedFd<'_>,
329 ) -> Result<(), E> {
330 let status = unsafe { libc::bind(file.as_raw_fd(), self.addr.as_ptr(), self.len.raw()) };
332 unsafe { kernel::raw::Status::new(status).try_zero::<S, E>() }
334 }
335
336 pub fn try_connect<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
337 self,
338 file: BorrowedFd<'_>,
339 ) -> Result<(), E> {
340 let status = unsafe { libc::connect(file.as_raw_fd(), self.addr.as_ptr(), self.len.raw()) };
342 unsafe { kernel::raw::Status::new(status).try_zero::<S, E>() }
344 }
345}