Debian Codegraph @

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

raw
1 //! The BSD sockets API requires us to read the `ss_family` field before we can
2 //! interpret the rest of a `sockaddr` produced by the kernel.
3
4 #[cfg(unix)]
5 use super::addr::SocketAddrUnix;
6 use super::ext::{in6_addr_s6_addr, in_addr_s_addr, sockaddr_in6_sin6_scope_id};
7 use crate::backend::c;
8 #[cfg(not(windows))]
9 use crate::ffi::CStr;
10 use crate::io;
11 #[cfg(target_os = "linux")]
12 use crate::net::xdp::{SockaddrXdpFlags, SocketAddrXdp};
13 use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddrAny, SocketAddrV4, SocketAddrV6};
14 use core::mem::size_of;
15
16 // This must match the header of `sockaddr`.
17 #[repr(C)]
18 struct sockaddr_header {
19 #[cfg(any(
20 bsd,
21 target_os = "aix",
22 target_os = "espidf",
23 target_os = "haiku",
24 target_os = "nto",
25 target_os = "vita"
26 ))]
27 sa_len: u8,
28 #[cfg(any(
29 bsd,
30 target_os = "aix",
31 target_os = "espidf",
32 target_os = "haiku",
33 target_os = "nto",
34 target_os = "vita"
35 ))]
36 ss_family: u8,
37 #[cfg(not(any(
38 bsd,
39 target_os = "aix",
40 target_os = "espidf",
41 target_os = "haiku",
42 target_os = "nto",
43 target_os = "vita"
44 )))]
45 ss_family: u16,
46 }
47
48 /// Read the `ss_family` field from a socket address returned from the OS.
49 ///
50 /// # Safety
51 ///
52 /// `storage` must point to a valid socket address returned from the OS.
53 #[inline]
54 unsafe fn read_ss_family(storage: *const c::sockaddr_storage) -> u16 {
55 // Assert that we know the layout of `sockaddr`.
56 let _ = c::sockaddr {
57 #[cfg(any(
58 bsd,
59 target_os = "aix",
60 target_os = "espidf",
61 target_os = "haiku",
62 target_os = "hurd",
63 target_os = "nto",
64 target_os = "vita"
65 ))]
66 sa_len: 0_u8,
67 #[cfg(any(
68 bsd,
69 target_os = "aix",
70 target_os = "espidf",
71 target_os = "haiku",
72 target_os = "hurd",
73 target_os = "nto",
74 target_os = "vita"
75 ))]
76 sa_family: 0_u8,
77 #[cfg(not(any(
78 bsd,
79 target_os = "aix",
80 target_os = "espidf",
81 target_os = "haiku",
82 target_os = "hurd",
83 target_os = "nto",
84 target_os = "vita"
85 )))]
86 sa_family: 0_u16,
87 #[cfg(not(target_os = "haiku"))]
88 sa_data: [0; 14],
89 #[cfg(target_os = "haiku")]
90 sa_data: [0; 30],
91 };
92
93 (*storage.cast::<sockaddr_header>()).ss_family.into()
94 }
95
96 /// Set the `ss_family` field of a socket address to `AF_UNSPEC`, so that we
97 /// can test for `AF_UNSPEC` to test whether it was stored to.
98 pub(crate) unsafe fn initialize_family_to_unspec(storage: *mut c::sockaddr_storage) {
99 (*storage.cast::<sockaddr_header>()).ss_family = c::AF_UNSPEC as _;
100 }
101
102 /// Read a socket address encoded in a platform-specific format.
103 ///
104 /// # Safety
105 ///
106 /// `storage` must point to valid socket address storage.
107 pub(crate) unsafe fn read_sockaddr(
108 storage: *const c::sockaddr_storage,
109 len: usize,
110 ) -> io::Result<SocketAddrAny> {
111 #[cfg(unix)]
112 let offsetof_sun_path = super::addr::offsetof_sun_path();
113
114 if len < size_of::<c::sa_family_t>() {
115 return Err(io::Errno::INVAL);
116 }
117 match read_ss_family(storage).into() {
118 c::AF_INET => {
119 if len < size_of::<c::sockaddr_in>() {
120 return Err(io::Errno::INVAL);
121 }
122 let decode = &*storage.cast::<c::sockaddr_in>();
123 Ok(SocketAddrAny::V4(SocketAddrV4::new(
124 Ipv4Addr::from(u32::from_be(in_addr_s_addr(decode.sin_addr))),
125 u16::from_be(decode.sin_port),
126 )))
127 }
128 c::AF_INET6 => {
129 if len < size_of::<c::sockaddr_in6>() {
130 return Err(io::Errno::INVAL);
131 }
132 let decode = &*storage.cast::<c::sockaddr_in6>();
133 #[cfg(not(windows))]
134 let s6_addr = decode.sin6_addr.s6_addr;
135 #[cfg(windows)]
136 let s6_addr = decode.sin6_addr.u.Byte;
137 #[cfg(not(windows))]
138 let sin6_scope_id = decode.sin6_scope_id;
139 #[cfg(windows)]
140 let sin6_scope_id = decode.Anonymous.sin6_scope_id;
141 Ok(SocketAddrAny::V6(SocketAddrV6::new(
142 Ipv6Addr::from(s6_addr),
143 u16::from_be(decode.sin6_port),
144 u32::from_be(decode.sin6_flowinfo),
145 sin6_scope_id,
146 )))
147 }
148 #[cfg(unix)]
149 c::AF_UNIX => {
150 if len < offsetof_sun_path {
151 return Err(io::Errno::INVAL);
152 }
153 if len == offsetof_sun_path {
154 SocketAddrUnix::new(&[][..]).map(SocketAddrAny::Unix)
155 } else {
156 let decode = &*storage.cast::<c::sockaddr_un>();
157
158 // On Linux check for Linux's [abstract namespace].
159 //
160 // [abstract namespace]: https://man7.org/linux/man-pages/man7/unix.7.html
161 #[cfg(linux_kernel)]
162 if decode.sun_path[0] == 0 {
163 return SocketAddrUnix::new_abstract_name(core::mem::transmute::<
164 &[c::c_char],
165 &[u8],
166 >(
167 &decode.sun_path[1..len - offsetof_sun_path],
168 ))
169 .map(SocketAddrAny::Unix);
170 }
171
172 // Otherwise we expect a NUL-terminated filesystem path.
173
174 // Trim off unused bytes from the end of `path_bytes`.
175 let path_bytes = if cfg!(any(solarish, target_os = "freebsd")) {
176 // FreeBSD and illumos sometimes set the length to longer
177 // than the length of the NUL-terminated string. Find the
178 // NUL and truncate the string accordingly.
179 &decode.sun_path[..decode
180 .sun_path
181 .iter()
182 .position(|b| *b == 0)
183 .ok_or(io::Errno::INVAL)?]
184 } else {
185 // Otherwise, use the provided length.
186 let provided_len = len - 1 - offsetof_sun_path;
187 if decode.sun_path[provided_len] != 0 {
188 return Err(io::Errno::INVAL);
189 }
190 debug_assert_eq!(
191 CStr::from_ptr(decode.sun_path.as_ptr().cast())
192 .to_bytes()
193 .len(),
194 provided_len
195 );
196 &decode.sun_path[..provided_len]
197 };
198
199 SocketAddrUnix::new(core::mem::transmute::<&[c::c_char], &[u8]>(path_bytes))
200 .map(SocketAddrAny::Unix)
201 }
202 }
203 #[cfg(target_os = "linux")]
204 c::AF_XDP => {
205 if len < size_of::<c::sockaddr_xdp>() {
206 return Err(io::Errno::INVAL);
207 }
208 let decode = &*storage.cast::<c::sockaddr_xdp>();
209 Ok(SocketAddrAny::Xdp(SocketAddrXdp::new(
210 SockaddrXdpFlags::from_bits_retain(decode.sxdp_flags),
211 u32::from_be(decode.sxdp_ifindex),
212 u32::from_be(decode.sxdp_queue_id),
213 u32::from_be(decode.sxdp_shared_umem_fd),
214 )))
215 }
216 _ => Err(io::Errno::INVAL),
217 }
218 }
219
220 /// Read an optional socket address returned from the OS.
221 ///
222 /// # Safety
223 ///
224 /// `storage` must point to a valid socket address returned from the OS.
225 pub(crate) unsafe fn maybe_read_sockaddr_os(
226 storage: *const c::sockaddr_storage,
227 len: usize,
228 ) -> Option<SocketAddrAny> {
229 if len == 0 {
230 return None;
231 }
232
233 assert!(len >= size_of::<c::sa_family_t>());
234 let family = read_ss_family(storage).into();
235 if family == c::AF_UNSPEC {
236 None
237 } else {
238 Some(inner_read_sockaddr_os(family, storage, len))
239 }
240 }
241
242 /// Read a socket address returned from the OS.
243 ///
244 /// # Safety
245 ///
246 /// `storage` must point to a valid socket address returned from the OS.
247 pub(crate) unsafe fn read_sockaddr_os(
248 storage: *const c::sockaddr_storage,
249 len: usize,
250 ) -> SocketAddrAny {
251 assert!(len >= size_of::<c::sa_family_t>());
252 let family = read_ss_family(storage).into();
253 inner_read_sockaddr_os(family, storage, len)
254 }
255
256 unsafe fn inner_read_sockaddr_os(
257 family: c::c_int,
258 storage: *const c::sockaddr_storage,
259 len: usize,
260 ) -> SocketAddrAny {
261 #[cfg(unix)]
262 let offsetof_sun_path = super::addr::offsetof_sun_path();
263
264 assert!(len >= size_of::<c::sa_family_t>());
265 match family {
266 c::AF_INET => {
267 assert!(len >= size_of::<c::sockaddr_in>());
268 let decode = &*storage.cast::<c::sockaddr_in>();
269 SocketAddrAny::V4(SocketAddrV4::new(
270 Ipv4Addr::from(u32::from_be(in_addr_s_addr(decode.sin_addr))),
271 u16::from_be(decode.sin_port),
272 ))
273 }
274 c::AF_INET6 => {
275 assert!(len >= size_of::<c::sockaddr_in6>());
276 let decode = &*storage.cast::<c::sockaddr_in6>();
277 SocketAddrAny::V6(SocketAddrV6::new(
278 Ipv6Addr::from(in6_addr_s6_addr(decode.sin6_addr)),
279 u16::from_be(decode.sin6_port),
280 u32::from_be(decode.sin6_flowinfo),
281 sockaddr_in6_sin6_scope_id(decode),
282 ))
283 }
284 #[cfg(unix)]
285 c::AF_UNIX => {
286 assert!(len >= offsetof_sun_path);
287 if len == offsetof_sun_path {
288 SocketAddrAny::Unix(SocketAddrUnix::new(&[][..]).unwrap())
289 } else {
290 let decode = &*storage.cast::<c::sockaddr_un>();
291
292 // On Linux check for Linux's [abstract namespace].
293 //
294 // [abstract namespace]: https://man7.org/linux/man-pages/man7/unix.7.html
295 #[cfg(linux_kernel)]
296 if decode.sun_path[0] == 0 {
297 return SocketAddrAny::Unix(
298 SocketAddrUnix::new_abstract_name(core::mem::transmute::<
299 &[c::c_char],
300 &[u8],
301 >(
302 &decode.sun_path[1..len - offsetof_sun_path],
303 ))
304 .unwrap(),
305 );
306 }
307
308 // Otherwise we expect a NUL-terminated filesystem path.
309 assert_eq!(decode.sun_path[len - 1 - offsetof_sun_path], 0);
310 let path_bytes = &decode.sun_path[..len - 1 - offsetof_sun_path];
311
312 // FreeBSD and illumos sometimes set the length to longer than
313 // the length of the NUL-terminated string. Find the NUL and
314 // truncate the string accordingly.
315 #[cfg(any(solarish, target_os = "freebsd"))]
316 let path_bytes = &path_bytes[..path_bytes.iter().position(|b| *b == 0).unwrap()];
317
318 SocketAddrAny::Unix(
319 SocketAddrUnix::new(core::mem::transmute::<&[c::c_char], &[u8]>(path_bytes))
320 .unwrap(),
321 )
322 }
323 }
324 #[cfg(target_os = "linux")]
325 c::AF_XDP => {
326 assert!(len >= size_of::<c::sockaddr_xdp>());
327 let decode = &*storage.cast::<c::sockaddr_xdp>();
328 SocketAddrAny::Xdp(SocketAddrXdp::new(
329 SockaddrXdpFlags::from_bits_retain(decode.sxdp_flags),
330 u32::from_be(decode.sxdp_ifindex),
331 u32::from_be(decode.sxdp_queue_id),
332 u32::from_be(decode.sxdp_shared_umem_fd),
333 ))
334 }
335 other => unimplemented!("{:?}", other),
336 }
337 }