Debian Codegraph @

third_party/rust/rustix/src/backend/libc/net/addr.rs

raw
1 //! Socket address utilities.
2
3 use crate::backend::c;
4 #[cfg(unix)]
5 use {
6 crate::ffi::CStr,
7 crate::io,
8 crate::path,
9 core::cmp::Ordering,
10 core::fmt,
11 core::hash::{Hash, Hasher},
12 core::slice,
13 };
14
15 /// `struct sockaddr_un`
16 #[cfg(unix)]
17 #[derive(Clone)]
18 #[doc(alias = "sockaddr_un")]
19 pub struct SocketAddrUnix {
20 pub(crate) unix: c::sockaddr_un,
21 #[cfg(not(any(bsd, target_os = "haiku")))]
22 len: c::socklen_t,
23 }
24
25 #[cfg(unix)]
26 impl SocketAddrUnix {
27 /// Construct a new Unix-domain address from a filesystem path.
28 #[inline]
29 pub fn new<P: path::Arg>(path: P) -> io::Result<Self> {
30 path.into_with_c_str(Self::_new)
31 }
32
33 #[inline]
34 fn _new(path: &CStr) -> io::Result<Self> {
35 let mut unix = Self::init();
36 let bytes = path.to_bytes_with_nul();
37 if bytes.len() > unix.sun_path.len() {
38 return Err(io::Errno::NAMETOOLONG);
39 }
40 for (i, b) in bytes.iter().enumerate() {
41 unix.sun_path[i] = *b as c::c_char;
42 }
43
44 #[cfg(any(bsd, target_os = "haiku"))]
45 {
46 unix.sun_len = (offsetof_sun_path() + bytes.len()).try_into().unwrap();
47 }
48
49 Ok(Self {
50 unix,
51 #[cfg(not(any(bsd, target_os = "haiku")))]
52 len: (offsetof_sun_path() + bytes.len()).try_into().unwrap(),
53 })
54 }
55
56 /// Construct a new abstract Unix-domain address from a byte slice.
57 #[cfg(linux_kernel)]
58 #[inline]
59 pub fn new_abstract_name(name: &[u8]) -> io::Result<Self> {
60 let mut unix = Self::init();
61 if 1 + name.len() > unix.sun_path.len() {
62 return Err(io::Errno::NAMETOOLONG);
63 }
64 unix.sun_path[0] = 0;
65 for (i, b) in name.iter().enumerate() {
66 unix.sun_path[1 + i] = *b as c::c_char;
67 }
68 let len = offsetof_sun_path() + 1 + name.len();
69 let len = len.try_into().unwrap();
70 Ok(Self {
71 unix,
72 #[cfg(not(any(bsd, target_os = "haiku")))]
73 len,
74 })
75 }
76
77 const fn init() -> c::sockaddr_un {
78 c::sockaddr_un {
79 #[cfg(any(
80 bsd,
81 target_os = "aix",
82 target_os = "haiku",
83 target_os = "nto",
84 target_os = "hurd",
85 ))]
86 sun_len: 0,
87 #[cfg(target_os = "vita")]
88 ss_len: 0,
89 sun_family: c::AF_UNIX as _,
90 #[cfg(any(bsd, target_os = "nto"))]
91 sun_path: [0; 104],
92 #[cfg(not(any(bsd, target_os = "aix", target_os = "haiku", target_os = "nto")))]
93 sun_path: [0; 108],
94 #[cfg(target_os = "haiku")]
95 sun_path: [0; 126],
96 #[cfg(target_os = "aix")]
97 sun_path: [0; 1023],
98 }
99 }
100
101 /// For a filesystem path address, return the path.
102 #[inline]
103 pub fn path(&self) -> Option<&CStr> {
104 let len = self.len();
105 if len != 0 && self.unix.sun_path[0] != 0 {
106 let end = len as usize - offsetof_sun_path();
107 let bytes = &self.unix.sun_path[..end];
108 // SAFETY: `from_raw_parts` to convert from `&[c_char]` to `&[u8]`.
109 // And `from_bytes_with_nul_unchecked` since the string is
110 // NUL-terminated.
111 unsafe {
112 Some(CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(
113 bytes.as_ptr().cast(),
114 bytes.len(),
115 )))
116 }
117 } else {
118 None
119 }
120 }
121
122 /// For an abstract address, return the identifier.
123 #[cfg(linux_kernel)]
124 #[inline]
125 pub fn abstract_name(&self) -> Option<&[u8]> {
126 let len = self.len();
127 if len != 0 && self.unix.sun_path[0] == 0 {
128 let end = len as usize - offsetof_sun_path();
129 let bytes = &self.unix.sun_path[1..end];
130 // SAFETY: `from_raw_parts` to convert from `&[c_char]` to `&[u8]`.
131 unsafe { Some(slice::from_raw_parts(bytes.as_ptr().cast(), bytes.len())) }
132 } else {
133 None
134 }
135 }
136
137 #[inline]
138 pub(crate) fn addr_len(&self) -> c::socklen_t {
139 #[cfg(not(any(bsd, target_os = "haiku")))]
140 {
141 self.len
142 }
143 #[cfg(any(bsd, target_os = "haiku"))]
144 {
145 c::socklen_t::from(self.unix.sun_len)
146 }
147 }
148
149 #[inline]
150 pub(crate) fn len(&self) -> usize {
151 self.addr_len() as usize
152 }
153 }
154
155 #[cfg(unix)]
156 impl PartialEq for SocketAddrUnix {
157 #[inline]
158 fn eq(&self, other: &Self) -> bool {
159 let self_len = self.len() - offsetof_sun_path();
160 let other_len = other.len() - offsetof_sun_path();
161 self.unix.sun_path[..self_len].eq(&other.unix.sun_path[..other_len])
162 }
163 }
164
165 #[cfg(unix)]
166 impl Eq for SocketAddrUnix {}
167
168 #[cfg(unix)]
169 impl PartialOrd for SocketAddrUnix {
170 #[inline]
171 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
172 Some(self.cmp(other))
173 }
174 }
175
176 #[cfg(unix)]
177 impl Ord for SocketAddrUnix {
178 #[inline]
179 fn cmp(&self, other: &Self) -> Ordering {
180 let self_len = self.len() - offsetof_sun_path();
181 let other_len = other.len() - offsetof_sun_path();
182 self.unix.sun_path[..self_len].cmp(&other.unix.sun_path[..other_len])
183 }
184 }
185
186 #[cfg(unix)]
187 impl Hash for SocketAddrUnix {
188 #[inline]
189 fn hash<H: Hasher>(&self, state: &mut H) {
190 let self_len = self.len() - offsetof_sun_path();
191 self.unix.sun_path[..self_len].hash(state)
192 }
193 }
194
195 #[cfg(unix)]
196 impl fmt::Debug for SocketAddrUnix {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 if let Some(path) = self.path() {
199 path.fmt(f)
200 } else {
201 #[cfg(linux_kernel)]
202 if let Some(name) = self.abstract_name() {
203 return name.fmt(f);
204 }
205
206 "(unnamed)".fmt(f)
207 }
208 }
209 }
210
211 /// `struct sockaddr_storage` as a raw struct.
212 pub type SocketAddrStorage = c::sockaddr_storage;
213
214 /// Return the offset of the `sun_path` field of `sockaddr_un`.
215 #[cfg(not(windows))]
216 #[inline]
217 pub(crate) fn offsetof_sun_path() -> usize {
218 let z = c::sockaddr_un {
219 #[cfg(any(
220 bsd,
221 target_os = "aix",
222 target_os = "haiku",
223 target_os = "hurd",
224 target_os = "nto",
225 ))]
226 sun_len: 0_u8,
227 #[cfg(target_os = "vita")]
228 ss_len: 0,
229 #[cfg(any(
230 bsd,
231 target_os = "aix",
232 target_os = "espidf",
233 target_os = "haiku",
234 target_os = "hurd",
235 target_os = "nto",
236 target_os = "vita"
237 ))]
238 sun_family: 0_u8,
239 #[cfg(not(any(
240 bsd,
241 target_os = "aix",
242 target_os = "espidf",
243 target_os = "haiku",
244 target_os = "hurd",
245 target_os = "nto",
246 target_os = "vita"
247 )))]
248 sun_family: 0_u16,
249 #[cfg(any(bsd, target_os = "nto"))]
250 sun_path: [0; 104],
251 #[cfg(not(any(bsd, target_os = "aix", target_os = "haiku", target_os = "nto")))]
252 sun_path: [0; 108],
253 #[cfg(target_os = "haiku")]
254 sun_path: [0; 126],
255 #[cfg(target_os = "aix")]
256 sun_path: [0; 1023],
257 };
258 (crate::utils::as_ptr(&z.sun_path) as usize) - (crate::utils::as_ptr(&z) as usize)
259 }