Debian Codegraph @

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

raw
1 //! libc syscalls supporting `rustix::net::sockopt`.
2
3 use super::ext::{in6_addr_new, in_addr_new};
4 use crate::backend::c;
5 use crate::backend::conv::{borrowed_fd, ret};
6 use crate::fd::BorrowedFd;
7 #[cfg(feature = "alloc")]
8 #[cfg(any(
9 linux_like,
10 target_os = "freebsd",
11 target_os = "fuchsia",
12 target_os = "illumos"
13 ))]
14 use crate::ffi::CStr;
15 use crate::io;
16 use crate::net::sockopt::Timeout;
17 #[cfg(target_os = "linux")]
18 use crate::net::xdp::{XdpMmapOffsets, XdpOptionsFlags, XdpRingOffset, XdpStatistics, XdpUmemReg};
19 #[cfg(not(any(
20 apple,
21 windows,
22 target_os = "aix",
23 target_os = "dragonfly",
24 target_os = "emscripten",
25 target_os = "espidf",
26 target_os = "haiku",
27 target_os = "netbsd",
28 target_os = "nto",
29 target_os = "vita",
30 )))]
31 use crate::net::AddressFamily;
32 #[cfg(any(
33 linux_kernel,
34 target_os = "freebsd",
35 target_os = "fuchsia",
36 target_os = "openbsd",
37 target_os = "redox",
38 target_env = "newlib"
39 ))]
40 use crate::net::Protocol;
41 #[cfg(any(
42 linux_kernel,
43 target_os = "freebsd",
44 target_os = "fuchsia",
45 target_os = "openbsd",
46 target_os = "redox",
47 target_env = "newlib"
48 ))]
49 use crate::net::RawProtocol;
50 use crate::net::{Ipv4Addr, Ipv6Addr, SocketType};
51 #[cfg(any(linux_kernel, target_os = "fuchsia"))]
52 use crate::net::{SocketAddrAny, SocketAddrStorage, SocketAddrV4};
53 #[cfg(linux_kernel)]
54 use crate::net::{SocketAddrV6, UCred};
55 use crate::utils::as_mut_ptr;
56 #[cfg(feature = "alloc")]
57 #[cfg(any(
58 linux_like,
59 target_os = "freebsd",
60 target_os = "fuchsia",
61 target_os = "illumos"
62 ))]
63 use alloc::borrow::ToOwned;
64 #[cfg(feature = "alloc")]
65 #[cfg(any(
66 linux_like,
67 target_os = "freebsd",
68 target_os = "fuchsia",
69 target_os = "illumos"
70 ))]
71 use alloc::string::String;
72 #[cfg(apple)]
73 use c::TCP_KEEPALIVE as TCP_KEEPIDLE;
74 #[cfg(not(any(apple, target_os = "openbsd", target_os = "haiku", target_os = "nto")))]
75 use c::TCP_KEEPIDLE;
76 use core::mem::{size_of, MaybeUninit};
77 use core::time::Duration;
78 #[cfg(target_os = "linux")]
79 use linux_raw_sys::xdp::{xdp_mmap_offsets, xdp_statistics, xdp_statistics_v1};
80 #[cfg(windows)]
81 use windows_sys::Win32::Foundation::BOOL;
82
83 #[inline]
84 fn getsockopt<T: Copy>(fd: BorrowedFd<'_>, level: i32, optname: i32) -> io::Result<T> {
85 let mut optlen = core::mem::size_of::<T>().try_into().unwrap();
86 debug_assert!(
87 optlen as usize >= core::mem::size_of::<c::c_int>(),
88 "Socket APIs don't ever use `bool` directly"
89 );
90
91 let mut value = MaybeUninit::<T>::zeroed();
92 getsockopt_raw(fd, level, optname, &mut value, &mut optlen)?;
93
94 // On Windows at least, `getsockopt` has been observed writing 1
95 // byte on at least (`IPPROTO_TCP`, `TCP_NODELAY`), even though
96 // Windows' documentation says that should write a 4-byte `BOOL`.
97 // So, we initialize the memory to zeros above, and just assert
98 // that `getsockopt` doesn't write too many bytes here.
99 assert!(
100 optlen as usize <= size_of::<T>(),
101 "unexpected getsockopt size"
102 );
103
104 unsafe { Ok(value.assume_init()) }
105 }
106
107 #[inline]
108 fn getsockopt_raw<T>(
109 fd: BorrowedFd<'_>,
110 level: i32,
111 optname: i32,
112 value: &mut MaybeUninit<T>,
113 optlen: &mut c::socklen_t,
114 ) -> io::Result<()> {
115 unsafe {
116 ret(c::getsockopt(
117 borrowed_fd(fd),
118 level,
119 optname,
120 as_mut_ptr(value).cast(),
121 optlen,
122 ))
123 }
124 }
125
126 #[inline]
127 fn setsockopt<T: Copy>(fd: BorrowedFd<'_>, level: i32, optname: i32, value: T) -> io::Result<()> {
128 let optlen = core::mem::size_of::<T>().try_into().unwrap();
129 debug_assert!(
130 optlen as usize >= core::mem::size_of::<c::c_int>(),
131 "Socket APIs don't ever use `bool` directly"
132 );
133 setsockopt_raw(fd, level, optname, &value, optlen)
134 }
135
136 #[inline]
137 fn setsockopt_raw<T>(
138 fd: BorrowedFd<'_>,
139 level: i32,
140 optname: i32,
141 ptr: *const T,
142 optlen: c::socklen_t,
143 ) -> io::Result<()> {
144 unsafe {
145 ret(c::setsockopt(
146 borrowed_fd(fd),
147 level,
148 optname,
149 ptr.cast(),
150 optlen,
151 ))
152 }
153 }
154
155 #[inline]
156 pub(crate) fn get_socket_type(fd: BorrowedFd<'_>) -> io::Result<SocketType> {
157 getsockopt(fd, c::SOL_SOCKET, c::SO_TYPE)
158 }
159
160 #[inline]
161 pub(crate) fn set_socket_reuseaddr(fd: BorrowedFd<'_>, reuseaddr: bool) -> io::Result<()> {
162 setsockopt(fd, c::SOL_SOCKET, c::SO_REUSEADDR, from_bool(reuseaddr))
163 }
164
165 #[inline]
166 pub(crate) fn get_socket_reuseaddr(fd: BorrowedFd<'_>) -> io::Result<bool> {
167 getsockopt(fd, c::SOL_SOCKET, c::SO_REUSEADDR).map(to_bool)
168 }
169
170 #[inline]
171 pub(crate) fn set_socket_broadcast(fd: BorrowedFd<'_>, broadcast: bool) -> io::Result<()> {
172 setsockopt(fd, c::SOL_SOCKET, c::SO_BROADCAST, from_bool(broadcast))
173 }
174
175 #[inline]
176 pub(crate) fn get_socket_broadcast(fd: BorrowedFd<'_>) -> io::Result<bool> {
177 getsockopt(fd, c::SOL_SOCKET, c::SO_BROADCAST).map(to_bool)
178 }
179
180 #[inline]
181 pub(crate) fn set_socket_linger(fd: BorrowedFd<'_>, linger: Option<Duration>) -> io::Result<()> {
182 // Convert `linger` to seconds, rounding up.
183 let l_linger = if let Some(linger) = linger {
184 duration_to_secs(linger)?
185 } else {
186 0
187 };
188 let linger = c::linger {
189 l_onoff: linger.is_some().into(),
190 l_linger,
191 };
192 setsockopt(fd, c::SOL_SOCKET, c::SO_LINGER, linger)
193 }
194
195 #[inline]
196 pub(crate) fn get_socket_linger(fd: BorrowedFd<'_>) -> io::Result<Option<Duration>> {
197 let linger: c::linger = getsockopt(fd, c::SOL_SOCKET, c::SO_LINGER)?;
198 Ok((linger.l_onoff != 0).then(|| Duration::from_secs(linger.l_linger as u64)))
199 }
200
201 #[cfg(linux_kernel)]
202 #[inline]
203 pub(crate) fn set_socket_passcred(fd: BorrowedFd<'_>, passcred: bool) -> io::Result<()> {
204 setsockopt(fd, c::SOL_SOCKET, c::SO_PASSCRED, from_bool(passcred))
205 }
206
207 #[cfg(linux_kernel)]
208 #[inline]
209 pub(crate) fn get_socket_passcred(fd: BorrowedFd<'_>) -> io::Result<bool> {
210 getsockopt(fd, c::SOL_SOCKET, c::SO_PASSCRED).map(to_bool)
211 }
212
213 #[inline]
214 pub(crate) fn set_socket_timeout(
215 fd: BorrowedFd<'_>,
216 id: Timeout,
217 timeout: Option<Duration>,
218 ) -> io::Result<()> {
219 let optname = match id {
220 Timeout::Recv => c::SO_RCVTIMEO,
221 Timeout::Send => c::SO_SNDTIMEO,
222 };
223
224 #[cfg(not(windows))]
225 let timeout = match timeout {
226 Some(timeout) => {
227 if timeout == Duration::ZERO {
228 return Err(io::Errno::INVAL);
229 }
230
231 // Rust's musl libc bindings deprecated `time_t` while they
232 // transition to 64-bit `time_t`. What we want here is just
233 // “whatever type `timeval`'s `tv_sec` is”, so we're ok using
234 // the deprecated type.
235 #[allow(deprecated)]
236 let tv_sec = timeout.as_secs().try_into().unwrap_or(c::time_t::MAX);
237
238 // `subsec_micros` rounds down, so we use `subsec_nanos` and
239 // manually round up.
240 let mut timeout = c::timeval {
241 tv_sec,
242 tv_usec: ((timeout.subsec_nanos() + 999) / 1000) as _,
243 };
244 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
245 timeout.tv_usec = 1;
246 }
247 timeout
248 }
249 None => c::timeval {
250 tv_sec: 0,
251 tv_usec: 0,
252 },
253 };
254
255 #[cfg(windows)]
256 let timeout: u32 = match timeout {
257 Some(timeout) => {
258 if timeout == Duration::ZERO {
259 return Err(io::Errno::INVAL);
260 }
261
262 // `as_millis` rounds down, so we use `as_nanos` and
263 // manually round up.
264 let mut timeout: u32 = ((timeout.as_nanos() + 999_999) / 1_000_000)
265 .try_into()
266 .map_err(|_convert_err| io::Errno::INVAL)?;
267 if timeout == 0 {
268 timeout = 1;
269 }
270 timeout
271 }
272 None => 0,
273 };
274
275 setsockopt(fd, c::SOL_SOCKET, optname, timeout)
276 }
277
278 #[inline]
279 pub(crate) fn get_socket_timeout(fd: BorrowedFd<'_>, id: Timeout) -> io::Result<Option<Duration>> {
280 let optname = match id {
281 Timeout::Recv => c::SO_RCVTIMEO,
282 Timeout::Send => c::SO_SNDTIMEO,
283 };
284
285 #[cfg(not(windows))]
286 {
287 let timeout: c::timeval = getsockopt(fd, c::SOL_SOCKET, optname)?;
288 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
289 Ok(None)
290 } else {
291 Ok(Some(
292 Duration::from_secs(timeout.tv_sec as u64)
293 + Duration::from_micros(timeout.tv_usec as u64),
294 ))
295 }
296 }
297
298 #[cfg(windows)]
299 {
300 let timeout: u32 = getsockopt(fd, c::SOL_SOCKET, optname)?;
301 if timeout == 0 {
302 Ok(None)
303 } else {
304 Ok(Some(Duration::from_millis(timeout as u64)))
305 }
306 }
307 }
308
309 #[cfg(any(apple, freebsdlike, target_os = "netbsd"))]
310 #[inline]
311 pub(crate) fn get_socket_nosigpipe(fd: BorrowedFd<'_>) -> io::Result<bool> {
312 getsockopt(fd, c::SOL_SOCKET, c::SO_NOSIGPIPE).map(to_bool)
313 }
314
315 #[cfg(any(apple, freebsdlike, target_os = "netbsd"))]
316 #[inline]
317 pub(crate) fn set_socket_nosigpipe(fd: BorrowedFd<'_>, val: bool) -> io::Result<()> {
318 setsockopt(fd, c::SOL_SOCKET, c::SO_NOSIGPIPE, from_bool(val))
319 }
320
321 #[inline]
322 pub(crate) fn get_socket_error(fd: BorrowedFd<'_>) -> io::Result<Result<(), io::Errno>> {
323 let err: c::c_int = getsockopt(fd, c::SOL_SOCKET, c::SO_ERROR)?;
324 Ok(if err == 0 {
325 Ok(())
326 } else {
327 Err(io::Errno::from_raw_os_error(err))
328 })
329 }
330
331 #[inline]
332 pub(crate) fn set_socket_keepalive(fd: BorrowedFd<'_>, keepalive: bool) -> io::Result<()> {
333 setsockopt(fd, c::SOL_SOCKET, c::SO_KEEPALIVE, from_bool(keepalive))
334 }
335
336 #[inline]
337 pub(crate) fn get_socket_keepalive(fd: BorrowedFd<'_>) -> io::Result<bool> {
338 getsockopt(fd, c::SOL_SOCKET, c::SO_KEEPALIVE).map(to_bool)
339 }
340
341 #[inline]
342 pub(crate) fn set_socket_recv_buffer_size(fd: BorrowedFd<'_>, size: usize) -> io::Result<()> {
343 let size: c::c_int = size.try_into().map_err(|_| io::Errno::INVAL)?;
344 setsockopt(fd, c::SOL_SOCKET, c::SO_RCVBUF, size)
345 }
346
347 #[cfg(any(linux_kernel, target_os = "fuchsia", target_os = "redox"))]
348 #[inline]
349 pub(crate) fn set_socket_recv_buffer_size_force(fd: BorrowedFd<'_>, size: usize) -> io::Result<()> {
350 let size: c::c_int = size.try_into().map_err(|_| io::Errno::INVAL)?;
351 setsockopt(fd, c::SOL_SOCKET, c::SO_RCVBUFFORCE, size)
352 }
353
354 #[inline]
355 pub(crate) fn get_socket_recv_buffer_size(fd: BorrowedFd<'_>) -> io::Result<usize> {
356 getsockopt(fd, c::SOL_SOCKET, c::SO_RCVBUF).map(|size: u32| size as usize)
357 }
358
359 #[inline]
360 pub(crate) fn set_socket_send_buffer_size(fd: BorrowedFd<'_>, size: usize) -> io::Result<()> {
361 let size: c::c_int = size.try_into().map_err(|_| io::Errno::INVAL)?;
362 setsockopt(fd, c::SOL_SOCKET, c::SO_SNDBUF, size)
363 }
364
365 #[inline]
366 pub(crate) fn get_socket_send_buffer_size(fd: BorrowedFd<'_>) -> io::Result<usize> {
367 getsockopt(fd, c::SOL_SOCKET, c::SO_SNDBUF).map(|size: u32| size as usize)
368 }
369
370 #[inline]
371 #[cfg(not(any(
372 apple,
373 windows,
374 target_os = "aix",
375 target_os = "dragonfly",
376 target_os = "emscripten",
377 target_os = "espidf",
378 target_os = "haiku",
379 target_os = "hurd",
380 target_os = "netbsd",
381 target_os = "nto",
382 target_os = "vita",
383 )))]
384 pub(crate) fn get_socket_domain(fd: BorrowedFd<'_>) -> io::Result<AddressFamily> {
385 let domain: c::c_int = getsockopt(fd, c::SOL_SOCKET, c::SO_DOMAIN)?;
386 Ok(AddressFamily(
387 domain.try_into().map_err(|_| io::Errno::OPNOTSUPP)?,
388 ))
389 }
390
391 #[inline]
392 #[cfg(not(apple))] // Apple platforms declare the constant, but do not actually implement it.
393 pub(crate) fn get_socket_acceptconn(fd: BorrowedFd<'_>) -> io::Result<bool> {
394 getsockopt(fd, c::SOL_SOCKET, c::SO_ACCEPTCONN).map(to_bool)
395 }
396
397 #[inline]
398 pub(crate) fn set_socket_oobinline(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
399 setsockopt(fd, c::SOL_SOCKET, c::SO_OOBINLINE, from_bool(value))
400 }
401
402 #[inline]
403 pub(crate) fn get_socket_oobinline(fd: BorrowedFd<'_>) -> io::Result<bool> {
404 getsockopt(fd, c::SOL_SOCKET, c::SO_OOBINLINE).map(to_bool)
405 }
406
407 #[cfg(not(any(solarish, windows)))]
408 #[inline]
409 pub(crate) fn set_socket_reuseport(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
410 setsockopt(fd, c::SOL_SOCKET, c::SO_REUSEPORT, from_bool(value))
411 }
412
413 #[cfg(not(any(solarish, windows)))]
414 #[inline]
415 pub(crate) fn get_socket_reuseport(fd: BorrowedFd<'_>) -> io::Result<bool> {
416 getsockopt(fd, c::SOL_SOCKET, c::SO_REUSEPORT).map(to_bool)
417 }
418
419 #[cfg(target_os = "freebsd")]
420 #[inline]
421 pub(crate) fn set_socket_reuseport_lb(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
422 setsockopt(fd, c::SOL_SOCKET, c::SO_REUSEPORT_LB, from_bool(value))
423 }
424
425 #[cfg(target_os = "freebsd")]
426 #[inline]
427 pub(crate) fn get_socket_reuseport_lb(fd: BorrowedFd<'_>) -> io::Result<bool> {
428 getsockopt(fd, c::SOL_SOCKET, c::SO_REUSEPORT_LB).map(to_bool)
429 }
430
431 #[cfg(any(
432 linux_kernel,
433 target_os = "freebsd",
434 target_os = "fuchsia",
435 target_os = "openbsd",
436 target_os = "redox",
437 target_env = "newlib"
438 ))]
439 #[inline]
440 pub(crate) fn get_socket_protocol(fd: BorrowedFd<'_>) -> io::Result<Option<Protocol>> {
441 getsockopt(fd, c::SOL_SOCKET, c::SO_PROTOCOL)
442 .map(|raw| RawProtocol::new(raw).map(Protocol::from_raw))
443 }
444
445 #[cfg(target_os = "linux")]
446 #[inline]
447 pub(crate) fn get_socket_cookie(fd: BorrowedFd<'_>) -> io::Result<u64> {
448 getsockopt(fd, c::SOL_SOCKET, c::SO_COOKIE)
449 }
450
451 #[cfg(target_os = "linux")]
452 #[inline]
453 pub(crate) fn get_socket_incoming_cpu(fd: BorrowedFd<'_>) -> io::Result<u32> {
454 getsockopt(fd, c::SOL_SOCKET, c::SO_INCOMING_CPU)
455 }
456
457 #[cfg(target_os = "linux")]
458 #[inline]
459 pub(crate) fn set_socket_incoming_cpu(fd: BorrowedFd<'_>, value: u32) -> io::Result<()> {
460 setsockopt(fd, c::SOL_SOCKET, c::SO_INCOMING_CPU, value)
461 }
462
463 #[inline]
464 pub(crate) fn set_ip_ttl(fd: BorrowedFd<'_>, ttl: u32) -> io::Result<()> {
465 setsockopt(fd, c::IPPROTO_IP, c::IP_TTL, ttl)
466 }
467
468 #[inline]
469 pub(crate) fn get_ip_ttl(fd: BorrowedFd<'_>) -> io::Result<u32> {
470 getsockopt(fd, c::IPPROTO_IP, c::IP_TTL)
471 }
472
473 #[inline]
474 pub(crate) fn set_ipv6_v6only(fd: BorrowedFd<'_>, only_v6: bool) -> io::Result<()> {
475 setsockopt(fd, c::IPPROTO_IPV6, c::IPV6_V6ONLY, from_bool(only_v6))
476 }
477
478 #[inline]
479 pub(crate) fn get_ipv6_v6only(fd: BorrowedFd<'_>) -> io::Result<bool> {
480 getsockopt(fd, c::IPPROTO_IPV6, c::IPV6_V6ONLY).map(to_bool)
481 }
482
483 #[inline]
484 pub(crate) fn set_ip_multicast_loop(fd: BorrowedFd<'_>, multicast_loop: bool) -> io::Result<()> {
485 setsockopt(
486 fd,
487 c::IPPROTO_IP,
488 c::IP_MULTICAST_LOOP,
489 from_bool(multicast_loop),
490 )
491 }
492
493 #[inline]
494 pub(crate) fn get_ip_multicast_loop(fd: BorrowedFd<'_>) -> io::Result<bool> {
495 getsockopt(fd, c::IPPROTO_IP, c::IP_MULTICAST_LOOP).map(to_bool)
496 }
497
498 #[inline]
499 pub(crate) fn set_ip_multicast_ttl(fd: BorrowedFd<'_>, multicast_ttl: u32) -> io::Result<()> {
500 setsockopt(fd, c::IPPROTO_IP, c::IP_MULTICAST_TTL, multicast_ttl)
501 }
502
503 #[inline]
504 pub(crate) fn get_ip_multicast_ttl(fd: BorrowedFd<'_>) -> io::Result<u32> {
505 getsockopt(fd, c::IPPROTO_IP, c::IP_MULTICAST_TTL)
506 }
507
508 #[inline]
509 pub(crate) fn set_ipv6_multicast_loop(fd: BorrowedFd<'_>, multicast_loop: bool) -> io::Result<()> {
510 setsockopt(
511 fd,
512 c::IPPROTO_IPV6,
513 c::IPV6_MULTICAST_LOOP,
514 from_bool(multicast_loop),
515 )
516 }
517
518 #[inline]
519 pub(crate) fn get_ipv6_multicast_loop(fd: BorrowedFd<'_>) -> io::Result<bool> {
520 getsockopt(fd, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP).map(to_bool)
521 }
522
523 #[inline]
524 pub(crate) fn set_ipv6_multicast_hops(fd: BorrowedFd<'_>, multicast_hops: u32) -> io::Result<()> {
525 setsockopt(fd, c::IPPROTO_IP, c::IPV6_MULTICAST_HOPS, multicast_hops)
526 }
527
528 #[inline]
529 pub(crate) fn get_ipv6_multicast_hops(fd: BorrowedFd<'_>) -> io::Result<u32> {
530 getsockopt(fd, c::IPPROTO_IP, c::IPV6_MULTICAST_HOPS)
531 }
532
533 #[inline]
534 pub(crate) fn set_ip_add_membership(
535 fd: BorrowedFd<'_>,
536 multiaddr: &Ipv4Addr,
537 interface: &Ipv4Addr,
538 ) -> io::Result<()> {
539 let mreq = to_ip_mreq(multiaddr, interface);
540 setsockopt(fd, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
541 }
542
543 #[cfg(any(
544 apple,
545 freebsdlike,
546 linux_like,
547 target_os = "fuchsia",
548 target_os = "openbsd"
549 ))]
550 #[inline]
551 pub(crate) fn set_ip_add_membership_with_ifindex(
552 fd: BorrowedFd<'_>,
553 multiaddr: &Ipv4Addr,
554 address: &Ipv4Addr,
555 ifindex: i32,
556 ) -> io::Result<()> {
557 let mreqn = to_ip_mreqn(multiaddr, address, ifindex);
558 setsockopt(fd, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreqn)
559 }
560
561 #[cfg(any(apple, freebsdlike, linux_like, solarish, target_os = "aix"))]
562 #[inline]
563 pub(crate) fn set_ip_add_source_membership(
564 fd: BorrowedFd<'_>,
565 multiaddr: &Ipv4Addr,
566 interface: &Ipv4Addr,
567 sourceaddr: &Ipv4Addr,
568 ) -> io::Result<()> {
569 let mreq_source = to_imr_source(multiaddr, interface, sourceaddr);
570 setsockopt(fd, c::IPPROTO_IP, c::IP_ADD_SOURCE_MEMBERSHIP, mreq_source)
571 }
572
573 #[cfg(any(apple, freebsdlike, linux_like, solarish, target_os = "aix"))]
574 #[inline]
575 pub(crate) fn set_ip_drop_source_membership(
576 fd: BorrowedFd<'_>,
577 multiaddr: &Ipv4Addr,
578 interface: &Ipv4Addr,
579 sourceaddr: &Ipv4Addr,
580 ) -> io::Result<()> {
581 let mreq_source = to_imr_source(multiaddr, interface, sourceaddr);
582 setsockopt(fd, c::IPPROTO_IP, c::IP_DROP_SOURCE_MEMBERSHIP, mreq_source)
583 }
584
585 #[inline]
586 pub(crate) fn set_ipv6_add_membership(
587 fd: BorrowedFd<'_>,
588 multiaddr: &Ipv6Addr,
589 interface: u32,
590 ) -> io::Result<()> {
591 #[cfg(not(any(
592 bsd,
593 solarish,
594 target_os = "haiku",
595 target_os = "l4re",
596 target_os = "nto"
597 )))]
598 use c::IPV6_ADD_MEMBERSHIP;
599 #[cfg(any(
600 bsd,
601 solarish,
602 target_os = "haiku",
603 target_os = "l4re",
604 target_os = "nto"
605 ))]
606 use c::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
607
608 let mreq = to_ipv6mr(multiaddr, interface);
609 setsockopt(fd, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq)
610 }
611
612 #[inline]
613 pub(crate) fn set_ip_drop_membership(
614 fd: BorrowedFd<'_>,
615 multiaddr: &Ipv4Addr,
616 interface: &Ipv4Addr,
617 ) -> io::Result<()> {
618 let mreq = to_ip_mreq(multiaddr, interface);
619 setsockopt(fd, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
620 }
621
622 #[cfg(any(
623 apple,
624 freebsdlike,
625 linux_like,
626 target_os = "fuchsia",
627 target_os = "openbsd"
628 ))]
629 #[inline]
630 pub(crate) fn set_ip_drop_membership_with_ifindex(
631 fd: BorrowedFd<'_>,
632 multiaddr: &Ipv4Addr,
633 address: &Ipv4Addr,
634 ifindex: i32,
635 ) -> io::Result<()> {
636 let mreqn = to_ip_mreqn(multiaddr, address, ifindex);
637 setsockopt(fd, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreqn)
638 }
639
640 #[inline]
641 pub(crate) fn set_ipv6_drop_membership(
642 fd: BorrowedFd<'_>,
643 multiaddr: &Ipv6Addr,
644 interface: u32,
645 ) -> io::Result<()> {
646 #[cfg(not(any(
647 bsd,
648 solarish,
649 target_os = "haiku",
650 target_os = "l4re",
651 target_os = "nto"
652 )))]
653 use c::IPV6_DROP_MEMBERSHIP;
654 #[cfg(any(
655 bsd,
656 solarish,
657 target_os = "haiku",
658 target_os = "l4re",
659 target_os = "nto"
660 ))]
661 use c::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
662
663 let mreq = to_ipv6mr(multiaddr, interface);
664 setsockopt(fd, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq)
665 }
666
667 #[inline]
668 pub(crate) fn get_ipv6_unicast_hops(fd: BorrowedFd<'_>) -> io::Result<u8> {
669 getsockopt(fd, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS).map(|hops: c::c_int| hops as u8)
670 }
671
672 #[inline]
673 pub(crate) fn set_ipv6_unicast_hops(fd: BorrowedFd<'_>, hops: Option<u8>) -> io::Result<()> {
674 let hops = match hops {
675 Some(hops) => hops as c::c_int,
676 None => -1,
677 };
678 setsockopt(fd, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS, hops)
679 }
680
681 #[cfg(any(
682 bsd,
683 linux_like,
684 target_os = "aix",
685 target_os = "fuchsia",
686 target_os = "haiku",
687 target_os = "nto",
688 target_env = "newlib"
689 ))]
690 #[inline]
691 pub(crate) fn set_ip_tos(fd: BorrowedFd<'_>, value: u8) -> io::Result<()> {
692 setsockopt(fd, c::IPPROTO_IP, c::IP_TOS, i32::from(value))
693 }
694
695 #[cfg(any(
696 bsd,
697 linux_like,
698 target_os = "aix",
699 target_os = "fuchsia",
700 target_os = "haiku",
701 target_os = "nto",
702 target_env = "newlib"
703 ))]
704 #[inline]
705 pub(crate) fn get_ip_tos(fd: BorrowedFd<'_>) -> io::Result<u8> {
706 let value: i32 = getsockopt(fd, c::IPPROTO_IP, c::IP_TOS)?;
707 Ok(value as u8)
708 }
709
710 #[cfg(any(apple, linux_like, target_os = "freebsd", target_os = "fuchsia"))]
711 #[inline]
712 pub(crate) fn set_ip_recvtos(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
713 setsockopt(fd, c::IPPROTO_IP, c::IP_RECVTOS, from_bool(value))
714 }
715
716 #[cfg(any(apple, linux_like, target_os = "freebsd", target_os = "fuchsia"))]
717 #[inline]
718 pub(crate) fn get_ip_recvtos(fd: BorrowedFd<'_>) -> io::Result<bool> {
719 getsockopt(fd, c::IPPROTO_IP, c::IP_RECVTOS).map(to_bool)
720 }
721
722 #[cfg(any(
723 bsd,
724 linux_like,
725 target_os = "aix",
726 target_os = "fuchsia",
727 target_os = "nto"
728 ))]
729 #[inline]
730 pub(crate) fn set_ipv6_recvtclass(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
731 setsockopt(fd, c::IPPROTO_IPV6, c::IPV6_RECVTCLASS, from_bool(value))
732 }
733
734 #[cfg(any(
735 bsd,
736 linux_like,
737 target_os = "aix",
738 target_os = "fuchsia",
739 target_os = "nto"
740 ))]
741 #[inline]
742 pub(crate) fn get_ipv6_recvtclass(fd: BorrowedFd<'_>) -> io::Result<bool> {
743 getsockopt(fd, c::IPPROTO_IPV6, c::IPV6_RECVTCLASS).map(to_bool)
744 }
745
746 #[cfg(any(linux_kernel, target_os = "fuchsia"))]
747 #[inline]
748 pub(crate) fn set_ip_freebind(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
749 setsockopt(fd, c::IPPROTO_IP, c::IP_FREEBIND, from_bool(value))
750 }
751
752 #[cfg(any(linux_kernel, target_os = "fuchsia"))]
753 #[inline]
754 pub(crate) fn get_ip_freebind(fd: BorrowedFd<'_>) -> io::Result<bool> {
755 getsockopt(fd, c::IPPROTO_IP, c::IP_FREEBIND).map(to_bool)
756 }
757
758 #[cfg(linux_kernel)]
759 #[inline]
760 pub(crate) fn set_ipv6_freebind(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
761 setsockopt(fd, c::IPPROTO_IPV6, c::IPV6_FREEBIND, from_bool(value))
762 }
763
764 #[cfg(linux_kernel)]
765 #[inline]
766 pub(crate) fn get_ipv6_freebind(fd: BorrowedFd<'_>) -> io::Result<bool> {
767 getsockopt(fd, c::IPPROTO_IPV6, c::IPV6_FREEBIND).map(to_bool)
768 }
769
770 #[cfg(any(linux_kernel, target_os = "fuchsia"))]
771 #[inline]
772 pub(crate) fn get_ip_original_dst(fd: BorrowedFd<'_>) -> io::Result<SocketAddrV4> {
773 let level = c::IPPROTO_IP;
774 let optname = c::SO_ORIGINAL_DST;
775 let mut value = MaybeUninit::<SocketAddrStorage>::uninit();
776 let mut optlen = core::mem::size_of_val(&value).try_into().unwrap();
777
778 getsockopt_raw(fd, level, optname, &mut value, &mut optlen)?;
779
780 let any = unsafe { SocketAddrAny::read(value.as_ptr(), optlen as usize)? };
781 match any {
782 SocketAddrAny::V4(v4) => Ok(v4),
783 _ => unreachable!(),
784 }
785 }
786
787 #[cfg(linux_kernel)]
788 #[inline]
789 pub(crate) fn get_ipv6_original_dst(fd: BorrowedFd<'_>) -> io::Result<SocketAddrV6> {
790 let level = c::IPPROTO_IPV6;
791 let optname = c::IP6T_SO_ORIGINAL_DST;
792 let mut value = MaybeUninit::<SocketAddrStorage>::uninit();
793 let mut optlen = core::mem::size_of_val(&value).try_into().unwrap();
794
795 getsockopt_raw(fd, level, optname, &mut value, &mut optlen)?;
796
797 let any = unsafe { SocketAddrAny::read(value.as_ptr(), optlen as usize)? };
798 match any {
799 SocketAddrAny::V6(v6) => Ok(v6),
800 _ => unreachable!(),
801 }
802 }
803
804 #[cfg(not(any(
805 solarish,
806 windows,
807 target_os = "espidf",
808 target_os = "haiku",
809 target_os = "vita"
810 )))]
811 #[inline]
812 pub(crate) fn set_ipv6_tclass(fd: BorrowedFd<'_>, value: u32) -> io::Result<()> {
813 setsockopt(fd, c::IPPROTO_IPV6, c::IPV6_TCLASS, value)
814 }
815
816 #[cfg(not(any(
817 solarish,
818 windows,
819 target_os = "espidf",
820 target_os = "haiku",
821 target_os = "vita"
822 )))]
823 #[inline]
824 pub(crate) fn get_ipv6_tclass(fd: BorrowedFd<'_>) -> io::Result<u32> {
825 getsockopt(fd, c::IPPROTO_IPV6, c::IPV6_TCLASS)
826 }
827
828 #[inline]
829 pub(crate) fn set_tcp_nodelay(fd: BorrowedFd<'_>, nodelay: bool) -> io::Result<()> {
830 setsockopt(fd, c::IPPROTO_TCP, c::TCP_NODELAY, from_bool(nodelay))
831 }
832
833 #[inline]
834 pub(crate) fn get_tcp_nodelay(fd: BorrowedFd<'_>) -> io::Result<bool> {
835 getsockopt(fd, c::IPPROTO_TCP, c::TCP_NODELAY).map(to_bool)
836 }
837
838 #[inline]
839 #[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "nto")))]
840 pub(crate) fn set_tcp_keepcnt(fd: BorrowedFd<'_>, count: u32) -> io::Result<()> {
841 setsockopt(fd, c::IPPROTO_TCP, c::TCP_KEEPCNT, count)
842 }
843
844 #[inline]
845 #[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "nto")))]
846 pub(crate) fn get_tcp_keepcnt(fd: BorrowedFd<'_>) -> io::Result<u32> {
847 getsockopt(fd, c::IPPROTO_TCP, c::TCP_KEEPCNT)
848 }
849
850 #[inline]
851 #[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "nto")))]
852 pub(crate) fn set_tcp_keepidle(fd: BorrowedFd<'_>, duration: Duration) -> io::Result<()> {
853 let secs: c::c_uint = duration_to_secs(duration)?;
854 setsockopt(fd, c::IPPROTO_TCP, TCP_KEEPIDLE, secs)
855 }
856
857 #[inline]
858 #[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "nto")))]
859 pub(crate) fn get_tcp_keepidle(fd: BorrowedFd<'_>) -> io::Result<Duration> {
860 let secs: c::c_uint = getsockopt(fd, c::IPPROTO_TCP, TCP_KEEPIDLE)?;
861 Ok(Duration::from_secs(secs as u64))
862 }
863
864 #[inline]
865 #[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "nto")))]
866 pub(crate) fn set_tcp_keepintvl(fd: BorrowedFd<'_>, duration: Duration) -> io::Result<()> {
867 let secs: c::c_uint = duration_to_secs(duration)?;
868 setsockopt(fd, c::IPPROTO_TCP, c::TCP_KEEPINTVL, secs)
869 }
870
871 #[inline]
872 #[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "nto")))]
873 pub(crate) fn get_tcp_keepintvl(fd: BorrowedFd<'_>) -> io::Result<Duration> {
874 let secs: c::c_uint = getsockopt(fd, c::IPPROTO_TCP, c::TCP_KEEPINTVL)?;
875 Ok(Duration::from_secs(secs as u64))
876 }
877
878 #[inline]
879 #[cfg(any(linux_like, target_os = "fuchsia"))]
880 pub(crate) fn set_tcp_user_timeout(fd: BorrowedFd<'_>, value: u32) -> io::Result<()> {
881 setsockopt(fd, c::IPPROTO_TCP, c::TCP_USER_TIMEOUT, value)
882 }
883
884 #[inline]
885 #[cfg(any(linux_like, target_os = "fuchsia"))]
886 pub(crate) fn get_tcp_user_timeout(fd: BorrowedFd<'_>) -> io::Result<u32> {
887 getsockopt(fd, c::IPPROTO_TCP, c::TCP_USER_TIMEOUT)
888 }
889
890 #[cfg(any(linux_like, target_os = "fuchsia"))]
891 #[inline]
892 pub(crate) fn set_tcp_quickack(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
893 setsockopt(fd, c::IPPROTO_TCP, c::TCP_QUICKACK, from_bool(value))
894 }
895
896 #[cfg(any(linux_like, target_os = "fuchsia"))]
897 #[inline]
898 pub(crate) fn get_tcp_quickack(fd: BorrowedFd<'_>) -> io::Result<bool> {
899 getsockopt(fd, c::IPPROTO_TCP, c::TCP_QUICKACK).map(to_bool)
900 }
901
902 #[cfg(any(
903 linux_like,
904 target_os = "freebsd",
905 target_os = "fuchsia",
906 target_os = "illumos"
907 ))]
908 #[inline]
909 pub(crate) fn set_tcp_congestion(fd: BorrowedFd<'_>, value: &str) -> io::Result<()> {
910 let level = c::IPPROTO_TCP;
911 let optname = c::TCP_CONGESTION;
912 let optlen = value.len().try_into().unwrap();
913 setsockopt_raw(fd, level, optname, value.as_ptr(), optlen)
914 }
915
916 #[cfg(feature = "alloc")]
917 #[cfg(any(
918 linux_like,
919 target_os = "freebsd",
920 target_os = "fuchsia",
921 target_os = "illumos"
922 ))]
923 #[inline]
924 pub(crate) fn get_tcp_congestion(fd: BorrowedFd<'_>) -> io::Result<String> {
925 const OPTLEN: c::socklen_t = 16;
926
927 let level = c::IPPROTO_TCP;
928 let optname = c::TCP_CONGESTION;
929 let mut value = MaybeUninit::<[MaybeUninit<u8>; OPTLEN as usize]>::uninit();
930 let mut optlen = OPTLEN;
931 getsockopt_raw(fd, level, optname, &mut value, &mut optlen)?;
932 unsafe {
933 let value = value.assume_init();
934 let slice: &[u8] = core::mem::transmute(&value[..optlen as usize]);
935 assert!(slice.iter().any(|b| *b == b'\0'));
936 Ok(
937 core::str::from_utf8(CStr::from_ptr(slice.as_ptr().cast()).to_bytes())
938 .unwrap()
939 .to_owned(),
940 )
941 }
942 }
943
944 #[cfg(any(linux_like, target_os = "fuchsia"))]
945 #[inline]
946 pub(crate) fn set_tcp_thin_linear_timeouts(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
947 setsockopt(
948 fd,
949 c::IPPROTO_TCP,
950 c::TCP_THIN_LINEAR_TIMEOUTS,
951 from_bool(value),
952 )
953 }
954
955 #[cfg(any(linux_like, target_os = "fuchsia"))]
956 #[inline]
957 pub(crate) fn get_tcp_thin_linear_timeouts(fd: BorrowedFd<'_>) -> io::Result<bool> {
958 getsockopt(fd, c::IPPROTO_TCP, c::TCP_THIN_LINEAR_TIMEOUTS).map(to_bool)
959 }
960
961 #[cfg(any(linux_like, solarish, target_os = "fuchsia"))]
962 #[inline]
963 pub(crate) fn set_tcp_cork(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
964 setsockopt(fd, c::IPPROTO_TCP, c::TCP_CORK, from_bool(value))
965 }
966
967 #[cfg(any(linux_like, solarish, target_os = "fuchsia"))]
968 #[inline]
969 pub(crate) fn get_tcp_cork(fd: BorrowedFd<'_>) -> io::Result<bool> {
970 getsockopt(fd, c::IPPROTO_TCP, c::TCP_CORK).map(to_bool)
971 }
972
973 #[cfg(linux_kernel)]
974 #[inline]
975 pub(crate) fn get_socket_peercred(fd: BorrowedFd<'_>) -> io::Result<UCred> {
976 getsockopt(fd, c::SOL_SOCKET, c::SO_PEERCRED)
977 }
978
979 #[cfg(target_os = "linux")]
980 #[inline]
981 pub(crate) fn set_xdp_umem_reg(fd: BorrowedFd<'_>, value: XdpUmemReg) -> io::Result<()> {
982 setsockopt(fd, c::SOL_XDP, c::XDP_UMEM_REG, value)
983 }
984
985 #[cfg(target_os = "linux")]
986 #[inline]
987 pub(crate) fn set_xdp_umem_fill_ring_size(fd: BorrowedFd<'_>, value: u32) -> io::Result<()> {
988 setsockopt(fd, c::SOL_XDP, c::XDP_UMEM_FILL_RING, value)
989 }
990
991 #[cfg(target_os = "linux")]
992 #[inline]
993 pub(crate) fn set_xdp_umem_completion_ring_size(fd: BorrowedFd<'_>, value: u32) -> io::Result<()> {
994 setsockopt(fd, c::SOL_XDP, c::XDP_UMEM_COMPLETION_RING, value)
995 }
996
997 #[cfg(target_os = "linux")]
998 #[inline]
999 pub(crate) fn set_xdp_tx_ring_size(fd: BorrowedFd<'_>, value: u32) -> io::Result<()> {
1000 setsockopt(fd, c::SOL_XDP, c::XDP_TX_RING, value)
1001 }
1002
1003 #[cfg(target_os = "linux")]
1004 #[inline]
1005 pub(crate) fn set_xdp_rx_ring_size(fd: BorrowedFd<'_>, value: u32) -> io::Result<()> {
1006 setsockopt(fd, c::SOL_XDP, c::XDP_RX_RING, value)
1007 }
1008
1009 #[cfg(target_os = "linux")]
1010 #[inline]
1011 pub(crate) fn get_xdp_mmap_offsets(fd: BorrowedFd<'_>) -> io::Result<XdpMmapOffsets> {
1012 // The kernel will write `xdp_mmap_offsets` or `xdp_mmap_offsets_v1` to the
1013 // supplied pointer, depending on the kernel version. Both structs only
1014 // contain u64 values. By using the larger of both as the parameter, we can
1015 // shuffle the values to the non-v1 version returned by
1016 // `get_xdp_mmap_offsets` while keeping the return type unaffected by the
1017 // kernel version. This works because C will layout all struct members one
1018 // after the other.
1019
1020 let mut optlen = core::mem::size_of::<xdp_mmap_offsets>().try_into().unwrap();
1021 debug_assert!(
1022 optlen as usize >= core::mem::size_of::<c::c_int>(),
1023 "Socket APIs don't ever use `bool` directly"
1024 );
1025 let mut value = MaybeUninit::<xdp_mmap_offsets>::zeroed();
1026 getsockopt_raw(fd, c::SOL_XDP, c::XDP_MMAP_OFFSETS, &mut value, &mut optlen)?;
1027
1028 if optlen as usize == core::mem::size_of::<c::xdp_mmap_offsets_v1>() {
1029 // Safety: All members of xdp_mmap_offsets are u64 and thus are correctly
1030 // initialized by `MaybeUninit::<xdp_statistics>::zeroed()`
1031 let xpd_mmap_offsets = unsafe { value.assume_init() };
1032 Ok(XdpMmapOffsets {
1033 rx: XdpRingOffset {
1034 producer: xpd_mmap_offsets.rx.producer,
1035 consumer: xpd_mmap_offsets.rx.consumer,
1036 desc: xpd_mmap_offsets.rx.desc,
1037 flags: None,
1038 },
1039 tx: XdpRingOffset {
1040 producer: xpd_mmap_offsets.rx.flags,
1041 consumer: xpd_mmap_offsets.tx.producer,
1042 desc: xpd_mmap_offsets.tx.consumer,
1043 flags: None,
1044 },
1045 fr: XdpRingOffset {
1046 producer: xpd_mmap_offsets.tx.desc,
1047 consumer: xpd_mmap_offsets.tx.flags,
1048 desc: xpd_mmap_offsets.fr.producer,
1049 flags: None,
1050 },
1051 cr: XdpRingOffset {
1052 producer: xpd_mmap_offsets.fr.consumer,
1053 consumer: xpd_mmap_offsets.fr.desc,
1054 desc: xpd_mmap_offsets.fr.flags,
1055 flags: None,
1056 },
1057 })
1058 } else {
1059 assert_eq!(
1060 optlen as usize,
1061 core::mem::size_of::<xdp_mmap_offsets>(),
1062 "unexpected getsockopt size"
1063 );
1064 // Safety: All members of xdp_mmap_offsets are u64 and thus are correctly
1065 // initialized by `MaybeUninit::<xdp_statistics>::zeroed()`
1066 let xpd_mmap_offsets = unsafe { value.assume_init() };
1067 Ok(XdpMmapOffsets {
1068 rx: XdpRingOffset {
1069 producer: xpd_mmap_offsets.rx.producer,
1070 consumer: xpd_mmap_offsets.rx.consumer,
1071 desc: xpd_mmap_offsets.rx.desc,
1072 flags: Some(xpd_mmap_offsets.rx.flags),
1073 },
1074 tx: XdpRingOffset {
1075 producer: xpd_mmap_offsets.tx.producer,
1076 consumer: xpd_mmap_offsets.tx.consumer,
1077 desc: xpd_mmap_offsets.tx.desc,
1078 flags: Some(xpd_mmap_offsets.tx.flags),
1079 },
1080 fr: XdpRingOffset {
1081 producer: xpd_mmap_offsets.fr.producer,
1082 consumer: xpd_mmap_offsets.fr.consumer,
1083 desc: xpd_mmap_offsets.fr.desc,
1084 flags: Some(xpd_mmap_offsets.fr.flags),
1085 },
1086 cr: XdpRingOffset {
1087 producer: xpd_mmap_offsets.cr.producer,
1088 consumer: xpd_mmap_offsets.cr.consumer,
1089 desc: xpd_mmap_offsets.cr.desc,
1090 flags: Some(xpd_mmap_offsets.cr.flags),
1091 },
1092 })
1093 }
1094 }
1095
1096 #[cfg(target_os = "linux")]
1097 #[inline]
1098 pub(crate) fn get_xdp_statistics(fd: BorrowedFd<'_>) -> io::Result<XdpStatistics> {
1099 let mut optlen = core::mem::size_of::<xdp_statistics>().try_into().unwrap();
1100 debug_assert!(
1101 optlen as usize >= core::mem::size_of::<c::c_int>(),
1102 "Socket APIs don't ever use `bool` directly"
1103 );
1104 let mut value = MaybeUninit::<xdp_statistics>::zeroed();
1105 getsockopt_raw(fd, c::SOL_XDP, c::XDP_STATISTICS, &mut value, &mut optlen)?;
1106
1107 if optlen as usize == core::mem::size_of::<xdp_statistics_v1>() {
1108 // Safety: All members of xdp_statistics are u64 and thus are correctly
1109 // initialized by `MaybeUninit::<xdp_statistics>::zeroed()`
1110 let xdp_statistics = unsafe { value.assume_init() };
1111 Ok(XdpStatistics {
1112 rx_dropped: xdp_statistics.rx_dropped,
1113 rx_invalid_descs: xdp_statistics.rx_dropped,
1114 tx_invalid_descs: xdp_statistics.rx_dropped,
1115 rx_ring_full: None,
1116 rx_fill_ring_empty_descs: None,
1117 tx_ring_empty_descs: None,
1118 })
1119 } else {
1120 assert_eq!(
1121 optlen as usize,
1122 core::mem::size_of::<xdp_statistics>(),
1123 "unexpected getsockopt size"
1124 );
1125 // Safety: All members of xdp_statistics are u64 and thus are correctly
1126 // initialized by `MaybeUninit::<xdp_statistics>::zeroed()`
1127 let xdp_statistics = unsafe { value.assume_init() };
1128 Ok(XdpStatistics {
1129 rx_dropped: xdp_statistics.rx_dropped,
1130 rx_invalid_descs: xdp_statistics.rx_invalid_descs,
1131 tx_invalid_descs: xdp_statistics.tx_invalid_descs,
1132 rx_ring_full: Some(xdp_statistics.rx_ring_full),
1133 rx_fill_ring_empty_descs: Some(xdp_statistics.rx_fill_ring_empty_descs),
1134 tx_ring_empty_descs: Some(xdp_statistics.tx_ring_empty_descs),
1135 })
1136 }
1137 }
1138
1139 #[cfg(target_os = "linux")]
1140 #[inline]
1141 pub(crate) fn get_xdp_options(fd: BorrowedFd<'_>) -> io::Result<XdpOptionsFlags> {
1142 getsockopt(fd, c::SOL_XDP, c::XDP_OPTIONS)
1143 }
1144
1145 #[inline]
1146 fn to_ip_mreq(multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> c::ip_mreq {
1147 c::ip_mreq {
1148 imr_multiaddr: to_imr_addr(multiaddr),
1149 imr_interface: to_imr_addr(interface),
1150 }
1151 }
1152
1153 #[cfg(any(
1154 apple,
1155 freebsdlike,
1156 linux_like,
1157 target_os = "fuchsia",
1158 target_os = "openbsd"
1159 ))]
1160 #[inline]
1161 fn to_ip_mreqn(multiaddr: &Ipv4Addr, address: &Ipv4Addr, ifindex: i32) -> c::ip_mreqn {
1162 c::ip_mreqn {
1163 imr_multiaddr: to_imr_addr(multiaddr),
1164 imr_address: to_imr_addr(address),
1165 imr_ifindex: ifindex,
1166 }
1167 }
1168
1169 #[cfg(any(apple, freebsdlike, linux_like, solarish, target_os = "aix"))]
1170 #[inline]
1171 fn to_imr_source(
1172 multiaddr: &Ipv4Addr,
1173 interface: &Ipv4Addr,
1174 sourceaddr: &Ipv4Addr,
1175 ) -> c::ip_mreq_source {
1176 c::ip_mreq_source {
1177 imr_multiaddr: to_imr_addr(multiaddr),
1178 imr_interface: to_imr_addr(interface),
1179 imr_sourceaddr: to_imr_addr(sourceaddr),
1180 }
1181 }
1182
1183 #[inline]
1184 fn to_imr_addr(addr: &Ipv4Addr) -> c::in_addr {
1185 in_addr_new(u32::from_ne_bytes(addr.octets()))
1186 }
1187
1188 #[inline]
1189 fn to_ipv6mr(multiaddr: &Ipv6Addr, interface: u32) -> c::ipv6_mreq {
1190 c::ipv6_mreq {
1191 ipv6mr_multiaddr: to_ipv6mr_multiaddr(multiaddr),
1192 ipv6mr_interface: to_ipv6mr_interface(interface),
1193 }
1194 }
1195
1196 #[inline]
1197 fn to_ipv6mr_multiaddr(multiaddr: &Ipv6Addr) -> c::in6_addr {
1198 in6_addr_new(multiaddr.octets())
1199 }
1200
1201 #[cfg(target_os = "android")]
1202 #[inline]
1203 fn to_ipv6mr_interface(interface: u32) -> c::c_int {
1204 interface as c::c_int
1205 }
1206
1207 #[cfg(not(target_os = "android"))]
1208 #[inline]
1209 fn to_ipv6mr_interface(interface: u32) -> c::c_uint {
1210 interface as c::c_uint
1211 }
1212
1213 // `getsockopt` and `setsockopt` represent boolean values as integers.
1214 #[cfg(not(windows))]
1215 type RawSocketBool = c::c_int;
1216 #[cfg(windows)]
1217 type RawSocketBool = BOOL;
1218
1219 // Wrap `RawSocketBool` in a newtype to discourage misuse.
1220 #[repr(transparent)]
1221 #[derive(Copy, Clone)]
1222 struct SocketBool(RawSocketBool);
1223
1224 // Convert from a `bool` to a `SocketBool`.
1225 #[inline]
1226 fn from_bool(value: bool) -> SocketBool {
1227 SocketBool(value.into())
1228 }
1229
1230 // Convert from a `SocketBool` to a `bool`.
1231 #[inline]
1232 fn to_bool(value: SocketBool) -> bool {
1233 value.0 != 0
1234 }
1235
1236 /// Convert to seconds, rounding up if necessary.
1237 #[inline]
1238 fn duration_to_secs<T: TryFrom<u64>>(duration: Duration) -> io::Result<T> {
1239 let mut secs = duration.as_secs();
1240 if duration.subsec_nanos() != 0 {
1241 secs = secs.checked_add(1).ok_or(io::Errno::INVAL)?;
1242 }
1243 T::try_from(secs).map_err(|_e| io::Errno::INVAL)
1244 }