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)]
138#[repr(transparent)]
139pub struct Buffer(libc::sockaddr_storage);
140
141#[derive(Clone, Copy)]
143#[repr(C)]
144pub struct Storage<L = Length> {
145 storage: Buffer,
146 len: L,
147}
148
149impl Storage<Length> {
150 #[must_use]
151 pub fn empty() -> Self {
152 Self {
153 storage: unsafe { mem::zeroed() },
154 len: Length(CAPACITY as libc::socklen_t),
155 }
156 }
157
158 pub fn output_mut(&mut self) -> (&mut Buffer, &mut u32) {
160 (&mut self.storage, &mut self.len.0)
161 }
162
163 pub fn prepare_output(&mut self) -> (&mut Buffer, &mut u32) {
164 self.len = Length(CAPACITY as libc::socklen_t);
165 self.output_mut()
166 }
167}
168
169impl Storage<Socklen> {
170 #[must_use]
171 pub fn as_addr(&self) -> Addr<'_> {
172 Addr::new(&self.storage, self.len)
173 }
174
175 #[must_use]
177 pub fn from_addr(source: Addr<'_>) -> Self {
178 let (addr, len) = source.parts();
179 let mut out = Self {
180 storage: unsafe { mem::zeroed() },
181 len,
182 };
183 unsafe {
186 ptr::copy_nonoverlapping(
187 addr.cast::<u8>(),
188 ptr::from_mut(&mut out.storage).cast(),
189 len.get(),
190 )
191 };
192 out
193 }
194}
195
196impl<L> Storage<L> {
197 fn decode(&self, actual: usize) -> Result<net::SocketAddr, Error> {
198 unsafe { Internet::decode(ptr::from_ref(&self.storage.0).cast(), actual) }
201 }
202}
203
204const _: () = {
205 assert!(CAPACITY <= libc::socklen_t::MAX as usize);
206 let fields = CAPACITY + mem::size_of::<libc::socklen_t>();
207 let align = mem::align_of::<Storage<Socklen>>();
208 assert!(mem::size_of::<Storage<Socklen>>() == fields.div_ceil(align) * align);
209};
210
211#[derive(Clone, Copy, Debug, Eq, PartialEq)]
213pub enum Error {
214 Storage {
215 actual: usize,
216 capacity: usize,
217 },
218 Header {
219 actual: usize,
220 required: usize,
221 },
222 Address {
223 family: i32,
224 actual: usize,
225 required: usize,
226 },
227 Unsupported {
228 family: i32,
229 actual: usize,
230 },
231}
232
233impl Storage<Socklen> {
234 pub fn to_std(&self) -> Result<net::SocketAddr, Error> {
235 self.decode(self.len.get())
236 }
237}
238
239impl Storage<Length> {
240 #[inline]
241 pub fn to_std(&self) -> Result<net::SocketAddr, Error> {
242 let actual = self.len.0 as usize;
243 if actual > CAPACITY {
244 return Err(Error::Storage {
245 actual,
246 capacity: CAPACITY,
247 });
248 }
249 self.decode(actual)
250 }
251}
252
253#[derive(Clone, Copy, Debug, Eq, PartialEq)]
255pub enum PathError {
256 Unsupported,
257 Empty,
258 Length { actual: usize, maximum: usize },
259 Nul { offset: usize },
260}
261
262impl PathError {
263 fn check(bytes: &[u8], maximum: usize) -> Result<(), Self> {
264 if bytes.is_empty() {
265 return Err(Self::Empty);
266 }
267 Self::length(bytes.len(), maximum)?;
268 if let Some(offset) = bytes.iter().position(|byte| *byte == 0) {
269 return Err(Self::Nul { offset });
270 }
271 Ok(())
272 }
273
274 fn length(actual: usize, maximum: usize) -> Result<(), Self> {
275 if actual > maximum {
276 return Err(Self::Length { actual, maximum });
277 }
278 Ok(())
279 }
280}
281
282#[derive(Clone, Copy)]
284#[repr(C)]
285pub struct Addr<'a> {
286 addr: ptr::NonNull<libc::sockaddr>,
287 len: Socklen,
288 owner: marker::PhantomData<&'a libc::sockaddr>,
289}
290
291#[derive(Clone, Copy, Debug, Eq, PartialEq)]
293pub enum Local<E> {
294 Syscall(E),
295 Length { actual: usize, capacity: usize },
296}
297
298impl<'a> Addr<'a> {
299 fn new<T>(storage: &'a T, len: Socklen) -> Self {
300 Self {
301 addr: ptr::NonNull::from(storage).cast(),
302 len,
303 owner: marker::PhantomData,
304 }
305 }
306
307 pub const fn parts(self) -> (*const (), Socklen) {
308 (self.addr.as_ptr().cast_const().cast(), self.len)
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 let (address, length) = storage.prepare_output();
316 let status =
319 unsafe { libc::getsockname(file.as_raw_fd(), ptr::from_mut(address).cast(), length) };
320 unsafe { kernel::raw::Status::new(status).try_zero::<S, E>() }.map_err(Local::Syscall)?;
322 let actual = *length as usize;
323 let len = Socklen::try_from_len(actual).ok_or(Local::Length {
324 actual,
325 capacity: CAPACITY,
326 })?;
327 Ok(Self::new(&storage.storage, len))
328 }
329
330 pub fn try_bind<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
331 self,
332 file: BorrowedFd<'_>,
333 ) -> Result<(), E> {
334 let status = unsafe { libc::bind(file.as_raw_fd(), self.addr.as_ptr(), self.len.raw()) };
336 unsafe { kernel::raw::Status::new(status).try_zero::<S, E>() }
338 }
339
340 pub fn try_connect<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
341 self,
342 file: BorrowedFd<'_>,
343 ) -> Result<(), E> {
344 let status = unsafe { libc::connect(file.as_raw_fd(), self.addr.as_ptr(), self.len.raw()) };
346 unsafe { kernel::raw::Status::new(status).try_zero::<S, E>() }
348 }
349}