1use 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
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 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 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 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 #[must_use]
117 pub fn as_addr(&self) -> Addr<'_> {
118 Addr::new(&self.raw, self.len)
119 }
120}
121
122#[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#[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 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 #[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#[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 to_std(&self) -> Result<net::SocketAddr, Error> {
212 socket::raw::observed(&self.storage, self.len.0 as usize)
213 }
214}
215
216#[derive(Clone, Copy, Debug, Eq, PartialEq)]
218pub enum PathError {
219 Unsupported,
220 Empty,
221 Length { actual: usize, maximum: usize },
222 Nul { offset: usize },
223}
224
225impl PathError {
226 fn check(bytes: &[u8], maximum: usize) -> Result<(), Self> {
227 if bytes.is_empty() {
228 return Err(Self::Empty);
229 }
230 Self::length(bytes.len(), maximum)?;
231 if let Some(offset) = bytes.iter().position(|byte| *byte == 0) {
232 return Err(Self::Nul { offset });
233 }
234 Ok(())
235 }
236
237 fn length(actual: usize, maximum: usize) -> Result<(), Self> {
238 if actual > maximum {
239 return Err(Self::Length { actual, maximum });
240 }
241 Ok(())
242 }
243}
244
245#[derive(Clone, Copy)]
247#[repr(C)]
248pub struct Addr<'a> {
249 addr: ptr::NonNull<libc::sockaddr>,
250 len: Socklen,
251 owner: marker::PhantomData<&'a libc::sockaddr>,
252}
253
254#[derive(Clone, Copy, Debug, Eq, PartialEq)]
256pub enum Local<E> {
257 Syscall(E),
258 Length { actual: usize, capacity: usize },
259}
260
261impl<'a> Addr<'a> {
262 fn new<T>(storage: &'a T, len: Socklen) -> Self {
263 Self {
264 addr: ptr::NonNull::from(storage).cast(),
265 len,
266 owner: marker::PhantomData,
267 }
268 }
269
270 pub const fn parts(self) -> (*const (), Socklen) {
271 (self.addr.as_ptr().cast_const().cast(), self.len)
272 }
273
274 pub fn into_std(self) -> Result<net::SocketAddr, Error> {
275 socket::raw::decoded(self)
276 }
277
278 pub fn local<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
279 file: BorrowedFd<'_>,
280 storage: &'a mut Storage<Length>,
281 ) -> Result<Self, Local<E>> {
282 socket::raw::name::<S, E, false>(file, storage).map_err(Local::Syscall)?;
283 let actual = storage.len.0 as usize;
284 let len = Socklen::try_from_len(actual).ok_or(Local::Length {
285 actual,
286 capacity: CAPACITY,
287 })?;
288 Ok(Self::new(&storage.storage, len))
289 }
290
291 pub fn try_bind<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
292 self,
293 file: BorrowedFd<'_>,
294 ) -> Result<(), E> {
295 socket::raw::apply::<S, E, false>(file, self)
296 }
297
298 pub fn try_connect<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
299 self,
300 file: BorrowedFd<'_>,
301 ) -> Result<(), E> {
302 socket::raw::apply::<S, E, true>(file, self)
303 }
304}