Debian Codegraph @

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