1// Copyright 2015 The Rust Project Developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use std::cmp::min;
10use std::ffi::OsStr;
11#[cfg(not(target_os = "redox"))]
12use std::io::IoSlice;
13use std::marker::PhantomData;
14use std::mem::{self, size_of, MaybeUninit};
15use std::net::Shutdown;
16use std::net::{Ipv4Addr, Ipv6Addr};
17#[cfg(all(
18 feature = "all",
19 any(
20 target_os = "ios",
21 target_os = "macos",
22 target_os = "tvos",
23 target_os = "watchos",
24 )
25))]
26use std::num::NonZeroU32;
27#[cfg(all(
28 feature = "all",
29 any(
30 target_os = "aix",
31 target_os = "android",
32 target_os = "freebsd",
33 target_os = "ios",
34 target_os = "linux",
35 target_os = "macos",
36 target_os = "tvos",
37 target_os = "watchos",
38 )
39))]
40use std::num::NonZeroUsize;
41use std::os::unix::ffi::OsStrExt;
42#[cfg(all(
43 feature = "all",
44 any(
45 target_os = "aix",
46 target_os = "android",
47 target_os = "freebsd",
48 target_os = "ios",
49 target_os = "linux",
50 target_os = "macos",
51 target_os = "tvos",
52 target_os = "watchos",
53 )
54))]
55use std::os::unix::io::RawFd;
56use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd};
57#[cfg(feature = "all")]
58use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
59use std::path::Path;
60use std::ptr;
61use std::time::{Duration, Instant};
62use std::{io, slice};
63
64#[cfg(not(any(
65 target_os = "ios",
66 target_os = "macos",
67 target_os = "tvos",
68 target_os = "watchos",
69)))]
70use libc::ssize_t;
71use libc::{in6_addr, in_addr};
72
73use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type};
74#[cfg(not(target_os = "redox"))]
75use crate::{MsgHdr, MsgHdrMut, RecvFlags};
76
77pub(crate) use libc::c_int;
78
79// Used in `Domain`.
80pub(crate) use libc::{AF_INET, AF_INET6, AF_UNIX};
81// Used in `Type`.
82#[cfg(all(feature = "all", target_os = "linux"))]
83pub(crate) use libc::SOCK_DCCP;
84#[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))]
85pub(crate) use libc::SOCK_RAW;
86#[cfg(all(feature = "all", not(target_os = "espidf")))]
87pub(crate) use libc::SOCK_SEQPACKET;
88pub(crate) use libc::{SOCK_DGRAM, SOCK_STREAM};
89// Used in `Protocol`.
90#[cfg(all(feature = "all", target_os = "linux"))]
91pub(crate) use libc::IPPROTO_DCCP;
92#[cfg(target_os = "linux")]
93pub(crate) use libc::IPPROTO_MPTCP;
94#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
95pub(crate) use libc::IPPROTO_SCTP;
96#[cfg(all(
97 feature = "all",
98 any(
99 target_os = "android",
100 target_os = "freebsd",
101 target_os = "fuchsia",
102 target_os = "linux",
103 )
104))]
105pub(crate) use libc::IPPROTO_UDPLITE;
106pub(crate) use libc::{IPPROTO_ICMP, IPPROTO_ICMPV6, IPPROTO_TCP, IPPROTO_UDP};
107// Used in `SockAddr`.
108#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))]
109pub(crate) use libc::IPPROTO_DIVERT;
110pub(crate) use libc::{
111 sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, socklen_t,
112};
113// Used in `RecvFlags`.
114#[cfg(not(any(target_os = "redox", target_os = "espidf")))]
115pub(crate) use libc::MSG_TRUNC;
116#[cfg(not(target_os = "redox"))]
117pub(crate) use libc::SO_OOBINLINE;
118// Used in `Socket`.
119#[cfg(not(target_os = "nto"))]
120pub(crate) use libc::ipv6_mreq as Ipv6Mreq;
121#[cfg(not(any(
122 target_os = "dragonfly",
123 target_os = "fuchsia",
124 target_os = "hurd",
125 target_os = "illumos",
126 target_os = "netbsd",
127 target_os = "openbsd",
128 target_os = "redox",
129 target_os = "solaris",
130 target_os = "haiku",
131 target_os = "espidf",
132 target_os = "vita",
133)))]
134pub(crate) use libc::IPV6_RECVTCLASS;
135#[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))]
136pub(crate) use libc::IP_HDRINCL;
137#[cfg(not(any(
138 target_os = "aix",
139 target_os = "dragonfly",
140 target_os = "fuchsia",
141 target_os = "illumos",
142 target_os = "netbsd",
143 target_os = "openbsd",
144 target_os = "redox",
145 target_os = "solaris",
146 target_os = "haiku",
147 target_os = "hurd",
148 target_os = "nto",
149 target_os = "espidf",
150 target_os = "vita",
151)))]
152pub(crate) use libc::IP_RECVTOS;
153#[cfg(not(any(
154 target_os = "fuchsia",
155 target_os = "redox",
156 target_os = "solaris",
157 target_os = "haiku",
158 target_os = "illumos",
159)))]
160pub(crate) use libc::IP_TOS;
161#[cfg(not(any(
162 target_os = "ios",
163 target_os = "macos",
164 target_os = "tvos",
165 target_os = "watchos",
166)))]
167pub(crate) use libc::SO_LINGER;
168#[cfg(any(
169 target_os = "ios",
170 target_os = "macos",
171 target_os = "tvos",
172 target_os = "watchos",
173))]
174pub(crate) use libc::SO_LINGER_SEC as SO_LINGER;
175pub(crate) use libc::{
176 ip_mreq as IpMreq, linger, IPPROTO_IP, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF,
177 IPV6_MULTICAST_LOOP, IPV6_UNICAST_HOPS, IPV6_V6ONLY, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP,
178 IP_MULTICAST_IF, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL, MSG_OOB, MSG_PEEK, SOL_SOCKET,
179 SO_BROADCAST, SO_ERROR, SO_KEEPALIVE, SO_RCVBUF, SO_RCVTIMEO, SO_REUSEADDR, SO_SNDBUF,
180 SO_SNDTIMEO, SO_TYPE, TCP_NODELAY,
181};
182#[cfg(not(any(
183 target_os = "dragonfly",
184 target_os = "haiku",
185 target_os = "hurd",
186 target_os = "netbsd",
187 target_os = "openbsd",
188 target_os = "redox",
189 target_os = "fuchsia",
190 target_os = "nto",
191 target_os = "espidf",
192 target_os = "vita",
193)))]
194pub(crate) use libc::{
195 ip_mreq_source as IpMreqSource, IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_SOURCE_MEMBERSHIP,
196};
197#[cfg(not(any(
198 target_os = "dragonfly",
199 target_os = "freebsd",
200 target_os = "haiku",
201 target_os = "illumos",
202 target_os = "ios",
203 target_os = "macos",
204 target_os = "netbsd",
205 target_os = "nto",
206 target_os = "openbsd",
207 target_os = "solaris",
208 target_os = "tvos",
209 target_os = "watchos",
210)))]
211pub(crate) use libc::{IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP};
212#[cfg(any(
213 target_os = "dragonfly",
214 target_os = "freebsd",
215 target_os = "haiku",
216 target_os = "illumos",
217 target_os = "ios",
218 target_os = "macos",
219 target_os = "netbsd",
220 target_os = "openbsd",
221 target_os = "solaris",
222 target_os = "tvos",
223 target_os = "watchos",
224))]
225pub(crate) use libc::{
226 IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP, IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP,
227};
228#[cfg(all(
229 feature = "all",
230 any(
231 target_os = "android",
232 target_os = "dragonfly",
233 target_os = "freebsd",
234 target_os = "fuchsia",
235 target_os = "illumos",
236 target_os = "ios",
237 target_os = "linux",
238 target_os = "macos",
239 target_os = "netbsd",
240 target_os = "tvos",
241 target_os = "watchos",
242 )
243))]
244pub(crate) use libc::{TCP_KEEPCNT, TCP_KEEPINTVL};
245
246// See this type in the Windows file.
247pub(crate) type Bool = c_int;
248
249#[cfg(any(
250 target_os = "ios",
251 target_os = "macos",
252 target_os = "nto",
253 target_os = "tvos",
254 target_os = "watchos",
255))]
256use libc::TCP_KEEPALIVE as KEEPALIVE_TIME;
257#[cfg(not(any(
258 target_os = "haiku",
259 target_os = "ios",
260 target_os = "macos",
261 target_os = "nto",
262 target_os = "openbsd",
263 target_os = "tvos",
264 target_os = "watchos",
265 target_os = "vita",
266)))]
267use libc::TCP_KEEPIDLE as KEEPALIVE_TIME;
268
269/// Helper macro to execute a system call that returns an `io::Result`.
270macro_rules! syscall {
271 ($fn: ident ( $($arg: expr),* $(,)* ) ) => {{
272 #[allow(unused_unsafe)]
273 let res = unsafe { libc::$fn($($arg, )*) };
274 if res == -1 {
275 Err(std::io::Error::last_os_error())
276 } else {
277 Ok(res)
278 }
279 }};
280}
281
282/// Maximum size of a buffer passed to system call like `recv` and `send`.
283#[cfg(not(any(
284 target_os = "ios",
285 target_os = "macos",
286 target_os = "tvos",
287 target_os = "watchos",
288)))]
289const MAX_BUF_LEN: usize = ssize_t::MAX as usize;
290
291// The maximum read limit on most posix-like systems is `SSIZE_MAX`, with the
292// man page quoting that if the count of bytes to read is greater than
293// `SSIZE_MAX` the result is "unspecified".
294//
295// On macOS, however, apparently the 64-bit libc is either buggy or
296// intentionally showing odd behavior by rejecting any read with a size larger
297// than or equal to INT_MAX. To handle both of these the read size is capped on
298// both platforms.
299#[cfg(any(
300 target_os = "ios",
301 target_os = "macos",
302 target_os = "tvos",
303 target_os = "watchos",
304))]
305const MAX_BUF_LEN: usize = c_int::MAX as usize - 1;
306
307// TCP_CA_NAME_MAX isn't defined in user space include files(not in libc)
308#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
309const TCP_CA_NAME_MAX: usize = 16;
310
311#[cfg(any(
312 all(
313 target_os = "linux",
314 any(
315 target_env = "gnu",
316 all(target_env = "uclibc", target_pointer_width = "64")
317 )
318 ),
319 target_os = "android",
320))]
321type IovLen = usize;
322
323#[cfg(any(
324 all(
325 target_os = "linux",
326 any(
327 target_env = "musl",
328 target_env = "ohos",
329 all(target_env = "uclibc", target_pointer_width = "32")
330 )
331 ),
332 target_os = "aix",
333 target_os = "dragonfly",
334 target_os = "freebsd",
335 target_os = "fuchsia",
336 target_os = "haiku",
337 target_os = "hurd",
338 target_os = "illumos",
339 target_os = "ios",
340 target_os = "macos",
341 target_os = "netbsd",
342 target_os = "nto",
343 target_os = "openbsd",
344 target_os = "solaris",
345 target_os = "tvos",
346 target_os = "watchos",
347 target_os = "espidf",
348 target_os = "vita",
349))]
350type IovLen = c_int;
351
352/// Unix only API.
353impl Domain {
354 /// Domain for low-level packet interface, corresponding to `AF_PACKET`.
355 #[cfg(all(
356 feature = "all",
357 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
358 ))]
359 #[cfg_attr(
360 docsrs,
361 doc(cfg(all(
362 feature = "all",
363 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
364 )))
365 )]
366 pub const PACKET: Domain = Domain(libc::AF_PACKET);
367
368 /// Domain for low-level VSOCK interface, corresponding to `AF_VSOCK`.
369 #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
370 #[cfg_attr(
371 docsrs,
372 doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
373 )]
374 pub const VSOCK: Domain = Domain(libc::AF_VSOCK);
375}
376
377impl_debug!(
378 Domain,
379 libc::AF_INET,
380 libc::AF_INET6,
381 libc::AF_UNIX,
382 #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
383 #[cfg_attr(
384 docsrs,
385 doc(cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux")))
386 )]
387 libc::AF_PACKET,
388 #[cfg(any(target_os = "android", target_os = "linux"))]
389 #[cfg_attr(docsrs, doc(cfg(any(target_os = "android", target_os = "linux"))))]
390 libc::AF_VSOCK,
391 libc::AF_UNSPEC, // = 0.
392);
393
394/// Unix only API.
395impl Type {
396 /// Set `SOCK_NONBLOCK` on the `Type`.
397 #[cfg(all(
398 feature = "all",
399 any(
400 target_os = "android",
401 target_os = "dragonfly",
402 target_os = "freebsd",
403 target_os = "fuchsia",
404 target_os = "illumos",
405 target_os = "linux",
406 target_os = "netbsd",
407 target_os = "openbsd"
408 )
409 ))]
410 #[cfg_attr(
411 docsrs,
412 doc(cfg(all(
413 feature = "all",
414 any(
415 target_os = "android",
416 target_os = "dragonfly",
417 target_os = "freebsd",
418 target_os = "fuchsia",
419 target_os = "illumos",
420 target_os = "linux",
421 target_os = "netbsd",
422 target_os = "openbsd"
423 )
424 )))
425 )]
426 pub const fn nonblocking(self) -> Type {
427 Type(self.0 | libc::SOCK_NONBLOCK)
428 }
429
430 /// Set `SOCK_CLOEXEC` on the `Type`.
431 #[cfg(all(
432 feature = "all",
433 any(
434 target_os = "android",
435 target_os = "dragonfly",
436 target_os = "freebsd",
437 target_os = "fuchsia",
438 target_os = "hurd",
439 target_os = "illumos",
440 target_os = "linux",
441 target_os = "netbsd",
442 target_os = "openbsd",
443 target_os = "redox",
444 target_os = "solaris",
445 )
446 ))]
447 #[cfg_attr(
448 docsrs,
449 doc(cfg(all(
450 feature = "all",
451 any(
452 target_os = "android",
453 target_os = "dragonfly",
454 target_os = "freebsd",
455 target_os = "fuchsia",
456 target_os = "hurd",
457 target_os = "illumos",
458 target_os = "linux",
459 target_os = "netbsd",
460 target_os = "openbsd",
461 target_os = "redox",
462 target_os = "solaris",
463 )
464 )))
465 )]
466 pub const fn cloexec(self) -> Type {
467 self._cloexec()
468 }
469
470 #[cfg(any(
471 target_os = "android",
472 target_os = "dragonfly",
473 target_os = "freebsd",
474 target_os = "fuchsia",
475 target_os = "hurd",
476 target_os = "illumos",
477 target_os = "linux",
478 target_os = "netbsd",
479 target_os = "openbsd",
480 target_os = "redox",
481 target_os = "solaris",
482 ))]
483 pub(crate) const fn _cloexec(self) -> Type {
484 Type(self.0 | libc::SOCK_CLOEXEC)
485 }
486}
487
488impl_debug!(
489 Type,
490 libc::SOCK_STREAM,
491 libc::SOCK_DGRAM,
492 #[cfg(all(feature = "all", target_os = "linux"))]
493 libc::SOCK_DCCP,
494 #[cfg(not(any(target_os = "redox", target_os = "espidf")))]
495 libc::SOCK_RAW,
496 #[cfg(not(any(target_os = "redox", target_os = "haiku", target_os = "espidf")))]
497 libc::SOCK_RDM,
498 #[cfg(not(target_os = "espidf"))]
499 libc::SOCK_SEQPACKET,
500 /* TODO: add these optional bit OR-ed flags:
501 #[cfg(any(
502 target_os = "android",
503 target_os = "dragonfly",
504 target_os = "freebsd",
505 target_os = "fuchsia",
506 target_os = "linux",
507 target_os = "netbsd",
508 target_os = "openbsd"
509 ))]
510 libc::SOCK_NONBLOCK,
511 #[cfg(any(
512 target_os = "android",
513 target_os = "dragonfly",
514 target_os = "freebsd",
515 target_os = "fuchsia",
516 target_os = "linux",
517 target_os = "netbsd",
518 target_os = "openbsd"
519 ))]
520 libc::SOCK_CLOEXEC,
521 */
522);
523
524impl_debug!(
525 Protocol,
526 libc::IPPROTO_ICMP,
527 libc::IPPROTO_ICMPV6,
528 libc::IPPROTO_TCP,
529 libc::IPPROTO_UDP,
530 #[cfg(target_os = "linux")]
531 libc::IPPROTO_MPTCP,
532 #[cfg(all(feature = "all", target_os = "linux"))]
533 libc::IPPROTO_DCCP,
534 #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
535 libc::IPPROTO_SCTP,
536 #[cfg(all(
537 feature = "all",
538 any(
539 target_os = "android",
540 target_os = "freebsd",
541 target_os = "fuchsia",
542 target_os = "linux",
543 )
544 ))]
545 libc::IPPROTO_UDPLITE,
546 #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))]
547 libc::IPPROTO_DIVERT,
548);
549
550/// Unix-only API.
551#[cfg(not(target_os = "redox"))]
552impl RecvFlags {
553 /// Check if the message terminates a record.
554 ///
555 /// Not all socket types support the notion of records. For socket types
556 /// that do support it (such as [`SEQPACKET`]), a record is terminated by
557 /// sending a message with the end-of-record flag set.
558 ///
559 /// On Unix this corresponds to the `MSG_EOR` flag.
560 ///
561 /// [`SEQPACKET`]: Type::SEQPACKET
562 #[cfg(not(target_os = "espidf"))]
563 pub const fn is_end_of_record(self) -> bool {
564 self.0 & libc::MSG_EOR != 0
565 }
566
567 /// Check if the message contains out-of-band data.
568 ///
569 /// This is useful for protocols where you receive out-of-band data
570 /// mixed in with the normal data stream.
571 ///
572 /// On Unix this corresponds to the `MSG_OOB` flag.
573 pub const fn is_out_of_band(self) -> bool {
574 self.0 & libc::MSG_OOB != 0
575 }
576}
577
578#[cfg(not(target_os = "redox"))]
579impl std::fmt::Debug for RecvFlags {
580 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
581 let mut s: DebugStruct<'_, '_> = f.debug_struct(name:"RecvFlags");
582 #[cfg(not(target_os = "espidf"))]
583 s.field(name:"is_end_of_record", &self.is_end_of_record());
584 s.field(name:"is_out_of_band", &self.is_out_of_band());
585 #[cfg(not(target_os = "espidf"))]
586 s.field(name:"is_truncated", &self.is_truncated());
587 s.finish()
588 }
589}
590
591#[repr(transparent)]
592pub struct MaybeUninitSlice<'a> {
593 vec: libc::iovec,
594 _lifetime: PhantomData<&'a mut [MaybeUninit<u8>]>,
595}
596
597unsafe impl<'a> Send for MaybeUninitSlice<'a> {}
598
599unsafe impl<'a> Sync for MaybeUninitSlice<'a> {}
600
601impl<'a> MaybeUninitSlice<'a> {
602 pub(crate) fn new(buf: &'a mut [MaybeUninit<u8>]) -> MaybeUninitSlice<'a> {
603 MaybeUninitSlice {
604 vec: libc::iovec {
605 iov_base: buf.as_mut_ptr().cast(),
606 iov_len: buf.len(),
607 },
608 _lifetime: PhantomData,
609 }
610 }
611
612 pub(crate) fn as_slice(&self) -> &[MaybeUninit<u8>] {
613 unsafe { slice::from_raw_parts(self.vec.iov_base.cast(), self.vec.iov_len) }
614 }
615
616 pub(crate) fn as_mut_slice(&mut self) -> &mut [MaybeUninit<u8>] {
617 unsafe { slice::from_raw_parts_mut(self.vec.iov_base.cast(), self.vec.iov_len) }
618 }
619}
620
621/// Returns the offset of the `sun_path` member of the passed unix socket address.
622pub(crate) fn offset_of_path(storage: &libc::sockaddr_un) -> usize {
623 let base: usize = storage as *const _ as usize;
624 let path: usize = ptr::addr_of!(storage.sun_path) as usize;
625 path - base
626}
627
628#[allow(unsafe_op_in_unsafe_fn)]
629pub(crate) fn unix_sockaddr(path: &Path) -> io::Result<SockAddr> {
630 // SAFETY: a `sockaddr_storage` of all zeros is valid.
631 let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
632 let len = {
633 let storage = unsafe { &mut *ptr::addr_of_mut!(storage).cast::<libc::sockaddr_un>() };
634
635 let bytes = path.as_os_str().as_bytes();
636 let too_long = match bytes.first() {
637 None => false,
638 // linux abstract namespaces aren't null-terminated
639 Some(&0) => bytes.len() > storage.sun_path.len(),
640 Some(_) => bytes.len() >= storage.sun_path.len(),
641 };
642 if too_long {
643 return Err(io::Error::new(
644 io::ErrorKind::InvalidInput,
645 "path must be shorter than SUN_LEN",
646 ));
647 }
648
649 storage.sun_family = libc::AF_UNIX as sa_family_t;
650 // SAFETY: `bytes` and `addr.sun_path` are not overlapping and
651 // both point to valid memory.
652 // `storage` was initialized to zero above, so the path is
653 // already NULL terminated.
654 unsafe {
655 ptr::copy_nonoverlapping(
656 bytes.as_ptr(),
657 storage.sun_path.as_mut_ptr().cast(),
658 bytes.len(),
659 );
660 }
661
662 let sun_path_offset = offset_of_path(storage);
663 sun_path_offset
664 + bytes.len()
665 + match bytes.first() {
666 Some(&0) | None => 0,
667 Some(_) => 1,
668 }
669 };
670 Ok(unsafe { SockAddr::new(storage, len as socklen_t) })
671}
672
673// Used in `MsgHdr`.
674#[cfg(not(target_os = "redox"))]
675pub(crate) use libc::msghdr;
676
677#[cfg(not(target_os = "redox"))]
678pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) {
679 msg.msg_name = name.as_ptr() as *mut _;
680 msg.msg_namelen = name.len();
681}
682
683#[cfg(not(target_os = "redox"))]
684#[allow(clippy::unnecessary_cast)] // IovLen type can be `usize`.
685pub(crate) fn set_msghdr_iov(msg: &mut msghdr, ptr: *mut libc::iovec, len: usize) {
686 msg.msg_iov = ptr;
687 msg.msg_iovlen = min(v1:len, v2:IovLen::MAX as usize) as IovLen;
688}
689
690#[cfg(not(target_os = "redox"))]
691pub(crate) fn set_msghdr_control(msg: &mut msghdr, ptr: *mut libc::c_void, len: usize) {
692 msg.msg_control = ptr;
693 msg.msg_controllen = len as _;
694}
695
696#[cfg(not(target_os = "redox"))]
697pub(crate) fn set_msghdr_flags(msg: &mut msghdr, flags: libc::c_int) {
698 msg.msg_flags = flags;
699}
700
701#[cfg(not(target_os = "redox"))]
702pub(crate) fn msghdr_flags(msg: &msghdr) -> RecvFlags {
703 RecvFlags(msg.msg_flags)
704}
705
706/// Unix only API.
707impl SockAddr {
708 /// Constructs a `SockAddr` with the family `AF_VSOCK` and the provided CID/port.
709 ///
710 /// # Errors
711 ///
712 /// This function can never fail. In a future version of this library it will be made
713 /// infallible.
714 #[allow(unsafe_op_in_unsafe_fn)]
715 #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
716 #[cfg_attr(
717 docsrs,
718 doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
719 )]
720 pub fn vsock(cid: u32, port: u32) -> SockAddr {
721 // SAFETY: a `sockaddr_storage` of all zeros is valid.
722 let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
723 {
724 let storage: &mut libc::sockaddr_vm =
725 unsafe { &mut *((&mut storage as *mut sockaddr_storage).cast()) };
726 storage.svm_family = libc::AF_VSOCK as sa_family_t;
727 storage.svm_cid = cid;
728 storage.svm_port = port;
729 }
730 unsafe { SockAddr::new(storage, mem::size_of::<libc::sockaddr_vm>() as socklen_t) }
731 }
732
733 /// Returns this address VSOCK CID/port if it is in the `AF_VSOCK` family,
734 /// otherwise return `None`.
735 #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
736 #[cfg_attr(
737 docsrs,
738 doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
739 )]
740 pub fn as_vsock_address(&self) -> Option<(u32, u32)> {
741 if self.family() == libc::AF_VSOCK as sa_family_t {
742 // Safety: if the ss_family field is AF_VSOCK then storage must be a sockaddr_vm.
743 let addr = unsafe { &*(self.as_ptr() as *const libc::sockaddr_vm) };
744 Some((addr.svm_cid, addr.svm_port))
745 } else {
746 None
747 }
748 }
749
750 /// Returns true if this address is an unnamed address from the `AF_UNIX` family (for local
751 /// interprocess communication), false otherwise.
752 pub fn is_unnamed(&self) -> bool {
753 self.as_sockaddr_un()
754 .map(|storage| {
755 self.len() == offset_of_path(storage) as _
756 // On some non-linux platforms a zeroed path is returned for unnamed.
757 // Abstract addresses only exist on Linux.
758 // NOTE: although Fuchsia does define `AF_UNIX` it's not actually implemented.
759 // See https://github.com/rust-lang/socket2/pull/403#discussion_r1123557978
760 || (cfg!(not(any(target_os = "linux", target_os = "android")))
761 && storage.sun_path[0] == 0)
762 })
763 .unwrap_or_default()
764 }
765
766 /// Returns the underlying `sockaddr_un` object if this addres is from the `AF_UNIX` family,
767 /// otherwise returns `None`.
768 pub(crate) fn as_sockaddr_un(&self) -> Option<&libc::sockaddr_un> {
769 self.is_unix().then(|| {
770 // SAFETY: if unix socket, i.e. the `ss_family` field is `AF_UNIX` then storage must be
771 // a `sockaddr_un`.
772 unsafe { &*self.as_ptr().cast::<libc::sockaddr_un>() }
773 })
774 }
775
776 /// Get the length of the path bytes of the address, not including the terminating or initial
777 /// (for abstract names) null byte.
778 ///
779 /// Should not be called on unnamed addresses.
780 fn path_len(&self, storage: &libc::sockaddr_un) -> usize {
781 debug_assert!(!self.is_unnamed());
782 self.len() as usize - offset_of_path(storage) - 1
783 }
784
785 /// Get a u8 slice for the bytes of the pathname or abstract name.
786 ///
787 /// Should not be called on unnamed addresses.
788 fn path_bytes(&self, storage: &libc::sockaddr_un, abstract_name: bool) -> &[u8] {
789 debug_assert!(!self.is_unnamed());
790 // SAFETY: the pointed objects of type `i8` have the same memory layout as `u8`. The path is
791 // the last field in the storage and so its length is equal to
792 // TOTAL_LENGTH - OFFSET_OF_PATH -1
793 // Where the 1 is either a terminating null if we have a pathname address, or the initial
794 // null byte, if it's an abstract name address. In the latter case, the path bytes start
795 // after the initial null byte, hence the `offset`.
796 // There is no safe way to convert a `&[i8]` to `&[u8]`
797 unsafe {
798 slice::from_raw_parts(
799 (storage.sun_path.as_ptr() as *const u8).offset(abstract_name as isize),
800 self.path_len(storage),
801 )
802 }
803 }
804
805 /// Returns this address as Unix `SocketAddr` if it is an `AF_UNIX` pathname
806 /// address, otherwise returns `None`.
807 pub fn as_unix(&self) -> Option<std::os::unix::net::SocketAddr> {
808 let path = self.as_pathname()?;
809 // SAFETY: we can represent this as a valid pathname, then so can the
810 // standard library.
811 Some(std::os::unix::net::SocketAddr::from_pathname(path).unwrap())
812 }
813
814 /// Returns this address as a `Path` reference if it is an `AF_UNIX`
815 /// pathname address, otherwise returns `None`.
816 pub fn as_pathname(&self) -> Option<&Path> {
817 self.as_sockaddr_un().and_then(|storage| {
818 (self.len() > offset_of_path(storage) as _ && storage.sun_path[0] != 0).then(|| {
819 let path_slice = self.path_bytes(storage, false);
820 Path::new::<OsStr>(OsStrExt::from_bytes(path_slice))
821 })
822 })
823 }
824
825 /// Returns this address as a slice of bytes representing an abstract address if it is an
826 /// `AF_UNIX` abstract address, otherwise returns `None`.
827 ///
828 /// Abstract addresses are a Linux extension, so this method returns `None` on all non-Linux
829 /// platforms.
830 pub fn as_abstract_namespace(&self) -> Option<&[u8]> {
831 // NOTE: although Fuchsia does define `AF_UNIX` it's not actually implemented.
832 // See https://github.com/rust-lang/socket2/pull/403#discussion_r1123557978
833 #[cfg(any(target_os = "linux", target_os = "android"))]
834 {
835 self.as_sockaddr_un().and_then(|storage| {
836 (self.len() > offset_of_path(storage) as _ && storage.sun_path[0] == 0)
837 .then(|| self.path_bytes(storage, true))
838 })
839 }
840 #[cfg(not(any(target_os = "linux", target_os = "android")))]
841 None
842 }
843}
844
845pub(crate) type Socket = c_int;
846
847pub(crate) unsafe fn socket_from_raw(socket: Socket) -> crate::socket::Inner {
848 crate::socket::Inner::from_raw_fd(socket)
849}
850
851pub(crate) fn socket_as_raw(socket: &crate::socket::Inner) -> Socket {
852 socket.as_raw_fd()
853}
854
855pub(crate) fn socket_into_raw(socket: crate::socket::Inner) -> Socket {
856 socket.into_raw_fd()
857}
858
859pub(crate) fn socket(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> {
860 syscall!(socket(family, ty, protocol))
861}
862
863#[cfg(all(feature = "all", unix))]
864#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))]
865pub(crate) fn socketpair(family: c_int, ty: c_int, protocol: c_int) -> io::Result<[Socket; 2]> {
866 let mut fds: [i32; 2] = [0, 0];
867 syscall!(socketpair(family, ty, protocol, fds.as_mut_ptr())).map(|_| fds)
868}
869
870pub(crate) fn bind(fd: Socket, addr: &SockAddr) -> io::Result<()> {
871 syscall!(bind(fd, addr.as_ptr(), addr.len() as _)).map(|_| ())
872}
873
874pub(crate) fn connect(fd: Socket, addr: &SockAddr) -> io::Result<()> {
875 syscall!(connect(fd, addr.as_ptr(), addr.len())).map(|_| ())
876}
877
878pub(crate) fn poll_connect(socket: &crate::Socket, timeout: Duration) -> io::Result<()> {
879 let start = Instant::now();
880
881 let mut pollfd = libc::pollfd {
882 fd: socket.as_raw(),
883 events: libc::POLLIN | libc::POLLOUT,
884 revents: 0,
885 };
886
887 loop {
888 let elapsed = start.elapsed();
889 if elapsed >= timeout {
890 return Err(io::ErrorKind::TimedOut.into());
891 }
892
893 let timeout = (timeout - elapsed).as_millis();
894 let timeout = timeout.clamp(1, c_int::MAX as u128) as c_int;
895
896 match syscall!(poll(&mut pollfd, 1, timeout)) {
897 Ok(0) => return Err(io::ErrorKind::TimedOut.into()),
898 Ok(_) => {
899 // Error or hang up indicates an error (or failure to connect).
900 if (pollfd.revents & libc::POLLHUP) != 0 || (pollfd.revents & libc::POLLERR) != 0 {
901 match socket.take_error() {
902 Ok(Some(err)) | Err(err) => return Err(err),
903 Ok(None) => {
904 return Err(io::Error::new(
905 io::ErrorKind::Other,
906 "no error set after POLLHUP",
907 ))
908 }
909 }
910 }
911 return Ok(());
912 }
913 // Got interrupted, try again.
914 Err(ref err) if err.kind() == io::ErrorKind::Interrupted => continue,
915 Err(err) => return Err(err),
916 }
917 }
918}
919
920pub(crate) fn listen(fd: Socket, backlog: c_int) -> io::Result<()> {
921 syscall!(listen(fd, backlog)).map(|_| ())
922}
923
924pub(crate) fn accept(fd: Socket) -> io::Result<(Socket, SockAddr)> {
925 // Safety: `accept` initialises the `SockAddr` for us.
926 unsafe { SockAddr::try_init(|storage: *mut sockaddr_storage, len: *mut u32| syscall!(accept(fd, storage.cast(), len))) }
927}
928
929pub(crate) fn getsockname(fd: Socket) -> io::Result<SockAddr> {
930 // Safety: `accept` initialises the `SockAddr` for us.
931 unsafe { SockAddr::try_init(|storage, len| syscall!(getsockname(fd, storage.cast(), len))) }
932 .map(|(_, addr: SockAddr)| addr)
933}
934
935pub(crate) fn getpeername(fd: Socket) -> io::Result<SockAddr> {
936 // Safety: `accept` initialises the `SockAddr` for us.
937 unsafe { SockAddr::try_init(|storage, len| syscall!(getpeername(fd, storage.cast(), len))) }
938 .map(|(_, addr: SockAddr)| addr)
939}
940
941pub(crate) fn try_clone(fd: Socket) -> io::Result<Socket> {
942 syscall!(fcntl(fd, libc::F_DUPFD_CLOEXEC, 0))
943}
944
945#[cfg(all(feature = "all", unix, not(target_os = "vita")))]
946pub(crate) fn nonblocking(fd: Socket) -> io::Result<bool> {
947 let file_status_flags: i32 = fcntl_get(fd, cmd:libc::F_GETFL)?;
948 Ok((file_status_flags & libc::O_NONBLOCK) != 0)
949}
950
951#[cfg(all(feature = "all", target_os = "vita"))]
952pub(crate) fn nonblocking(fd: Socket) -> io::Result<bool> {
953 unsafe {
954 getsockopt::<Bool>(fd, libc::SOL_SOCKET, libc::SO_NONBLOCK).map(|non_block| non_block != 0)
955 }
956}
957
958#[cfg(not(target_os = "vita"))]
959pub(crate) fn set_nonblocking(fd: Socket, nonblocking: bool) -> io::Result<()> {
960 if nonblocking {
961 fcntl_add(fd, get_cmd:libc::F_GETFL, set_cmd:libc::F_SETFL, flag:libc::O_NONBLOCK)
962 } else {
963 fcntl_remove(fd, get_cmd:libc::F_GETFL, set_cmd:libc::F_SETFL, flag:libc::O_NONBLOCK)
964 }
965}
966
967#[cfg(target_os = "vita")]
968pub(crate) fn set_nonblocking(fd: Socket, nonblocking: bool) -> io::Result<()> {
969 unsafe {
970 setsockopt(
971 fd,
972 libc::SOL_SOCKET,
973 libc::SO_NONBLOCK,
974 nonblocking as libc::c_int,
975 )
976 }
977}
978
979pub(crate) fn shutdown(fd: Socket, how: Shutdown) -> io::Result<()> {
980 let how: i32 = match how {
981 Shutdown::Write => libc::SHUT_WR,
982 Shutdown::Read => libc::SHUT_RD,
983 Shutdown::Both => libc::SHUT_RDWR,
984 };
985 syscall!(shutdown(fd, how)).map(|_| ())
986}
987
988pub(crate) fn recv(fd: Socket, buf: &mut [MaybeUninit<u8>], flags: c_int) -> io::Result<usize> {
989 syscall!(recv(
990 fd,
991 buf.as_mut_ptr().cast(),
992 min(buf.len(), MAX_BUF_LEN),
993 flags,
994 ))
995 .map(|n: isize| n as usize)
996}
997
998pub(crate) fn recv_from(
999 fd: Socket,
1000 buf: &mut [MaybeUninit<u8>],
1001 flags: c_int,
1002) -> io::Result<(usize, SockAddr)> {
1003 // Safety: `recvfrom` initialises the `SockAddr` for us.
1004 unsafe {
1005 SockAddr::try_init(|addr: *mut sockaddr_storage, addrlen: *mut u32| {
1006 syscall!(recvfrom(
1007 fd,
1008 buf.as_mut_ptr().cast(),
1009 min(buf.len(), MAX_BUF_LEN),
1010 flags,
1011 addr.cast(),
1012 addrlen
1013 ))
1014 .map(|n: isize| n as usize)
1015 })
1016 }
1017}
1018
1019pub(crate) fn peek_sender(fd: Socket) -> io::Result<SockAddr> {
1020 // Unix-like platforms simply truncate the returned data, so this implementation is trivial.
1021 // However, for Windows this requires suppressing the `WSAEMSGSIZE` error,
1022 // so that requires a different approach.
1023 // NOTE: macOS does not populate `sockaddr` if you pass a zero-sized buffer.
1024 let (_, sender: SockAddr) = recv_from(fd, &mut [MaybeUninit::uninit(); 8], MSG_PEEK)?;
1025 Ok(sender)
1026}
1027
1028#[cfg(not(target_os = "redox"))]
1029pub(crate) fn recv_vectored(
1030 fd: Socket,
1031 bufs: &mut [crate::MaybeUninitSlice<'_>],
1032 flags: c_int,
1033) -> io::Result<(usize, RecvFlags)> {
1034 let mut msg: MsgHdrMut<'_, '_, '_> = MsgHdrMut::new().with_buffers(bufs);
1035 let n: usize = recvmsg(fd, &mut msg, flags)?;
1036 Ok((n, msg.flags()))
1037}
1038
1039#[cfg(not(target_os = "redox"))]
1040pub(crate) fn recv_from_vectored(
1041 fd: Socket,
1042 bufs: &mut [crate::MaybeUninitSlice<'_>],
1043 flags: c_int,
1044) -> io::Result<(usize, RecvFlags, SockAddr)> {
1045 let mut msg: MsgHdrMut<'_, '_, '_> = MsgHdrMut::new().with_buffers(bufs);
1046 // SAFETY: `recvmsg` initialises the address storage and we set the length
1047 // manually.
1048 let (n: usize, addr: SockAddr) = unsafe {
1049 SockAddr::try_init(|storage: *mut sockaddr_storage, len: *mut u32| {
1050 msg.inner.msg_name = storage.cast();
1051 msg.inner.msg_namelen = *len;
1052 let n: usize = recvmsg(fd, &mut msg, flags)?;
1053 // Set the correct address length.
1054 *len = msg.inner.msg_namelen;
1055 Ok(n)
1056 })?
1057 };
1058 Ok((n, msg.flags(), addr))
1059}
1060
1061#[cfg(not(target_os = "redox"))]
1062pub(crate) fn recvmsg(
1063 fd: Socket,
1064 msg: &mut MsgHdrMut<'_, '_, '_>,
1065 flags: c_int,
1066) -> io::Result<usize> {
1067 syscall!(recvmsg(fd, &mut msg.inner, flags)).map(|n: isize| n as usize)
1068}
1069
1070pub(crate) fn send(fd: Socket, buf: &[u8], flags: c_int) -> io::Result<usize> {
1071 syscall!(send(
1072 fd,
1073 buf.as_ptr().cast(),
1074 min(buf.len(), MAX_BUF_LEN),
1075 flags,
1076 ))
1077 .map(|n: isize| n as usize)
1078}
1079
1080#[cfg(not(target_os = "redox"))]
1081pub(crate) fn send_vectored(fd: Socket, bufs: &[IoSlice<'_>], flags: c_int) -> io::Result<usize> {
1082 let msg: MsgHdr<'_, '_, '_> = MsgHdr::new().with_buffers(bufs);
1083 sendmsg(fd, &msg, flags)
1084}
1085
1086pub(crate) fn send_to(fd: Socket, buf: &[u8], addr: &SockAddr, flags: c_int) -> io::Result<usize> {
1087 syscall!(sendto(
1088 fd,
1089 buf.as_ptr().cast(),
1090 min(buf.len(), MAX_BUF_LEN),
1091 flags,
1092 addr.as_ptr(),
1093 addr.len(),
1094 ))
1095 .map(|n: isize| n as usize)
1096}
1097
1098#[cfg(not(target_os = "redox"))]
1099pub(crate) fn send_to_vectored(
1100 fd: Socket,
1101 bufs: &[IoSlice<'_>],
1102 addr: &SockAddr,
1103 flags: c_int,
1104) -> io::Result<usize> {
1105 let msg: MsgHdr<'_, '_, '_> = MsgHdr::new().with_addr(addr).with_buffers(bufs);
1106 sendmsg(fd, &msg, flags)
1107}
1108
1109#[cfg(not(target_os = "redox"))]
1110pub(crate) fn sendmsg(fd: Socket, msg: &MsgHdr<'_, '_, '_>, flags: c_int) -> io::Result<usize> {
1111 syscall!(sendmsg(fd, &msg.inner, flags)).map(|n: isize| n as usize)
1112}
1113
1114/// Wrapper around `getsockopt` to deal with platform specific timeouts.
1115pub(crate) fn timeout_opt(fd: Socket, opt: c_int, val: c_int) -> io::Result<Option<Duration>> {
1116 unsafe { getsockopt(fd, opt, val).map(op:from_timeval) }
1117}
1118
1119const fn from_timeval(duration: libc::timeval) -> Option<Duration> {
1120 if duration.tv_sec == 0 && duration.tv_usec == 0 {
1121 None
1122 } else {
1123 let sec: u64 = duration.tv_sec as u64;
1124 let nsec: u32 = (duration.tv_usec as u32) * 1000;
1125 Some(Duration::new(secs:sec, nanos:nsec))
1126 }
1127}
1128
1129/// Wrapper around `setsockopt` to deal with platform specific timeouts.
1130pub(crate) fn set_timeout_opt(
1131 fd: Socket,
1132 opt: c_int,
1133 val: c_int,
1134 duration: Option<Duration>,
1135) -> io::Result<()> {
1136 let duration: timeval = into_timeval(duration);
1137 unsafe { setsockopt(fd, opt, val, payload:duration) }
1138}
1139
1140fn into_timeval(duration: Option<Duration>) -> libc::timeval {
1141 match duration {
1142 // https://github.com/rust-lang/libc/issues/1848
1143 #[cfg_attr(target_env = "musl", allow(deprecated))]
1144 Some(duration: Duration) => libc::timeval {
1145 tv_sec: min(v1:duration.as_secs(), v2:libc::time_t::MAX as u64) as libc::time_t,
1146 tv_usec: duration.subsec_micros() as libc::suseconds_t,
1147 },
1148 None => libc::timeval {
1149 tv_sec: 0,
1150 tv_usec: 0,
1151 },
1152 }
1153}
1154
1155#[cfg(all(
1156 feature = "all",
1157 not(any(target_os = "haiku", target_os = "openbsd", target_os = "vita"))
1158))]
1159#[cfg_attr(
1160 docsrs,
1161 doc(cfg(all(
1162 feature = "all",
1163 not(any(target_os = "haiku", target_os = "openbsd", target_os = "vita"))
1164 )))
1165)]
1166pub(crate) fn keepalive_time(fd: Socket) -> io::Result<Duration> {
1167 unsafe {
1168 getsockopt::<c_int>(fd, IPPROTO_TCP, KEEPALIVE_TIME)
1169 .map(|secs: i32| Duration::from_secs(secs as u64))
1170 }
1171}
1172
1173#[allow(unused_variables)]
1174pub(crate) fn set_tcp_keepalive(fd: Socket, keepalive: &TcpKeepalive) -> io::Result<()> {
1175 #[cfg(not(any(
1176 target_os = "haiku",
1177 target_os = "openbsd",
1178 target_os = "nto",
1179 target_os = "vita"
1180 )))]
1181 if let Some(time) = keepalive.time {
1182 let secs = into_secs(time);
1183 unsafe { setsockopt(fd, libc::IPPROTO_TCP, KEEPALIVE_TIME, secs)? }
1184 }
1185
1186 #[cfg(any(
1187 target_os = "aix",
1188 target_os = "android",
1189 target_os = "dragonfly",
1190 target_os = "freebsd",
1191 target_os = "fuchsia",
1192 target_os = "hurd",
1193 target_os = "illumos",
1194 target_os = "ios",
1195 target_os = "linux",
1196 target_os = "macos",
1197 target_os = "netbsd",
1198 target_os = "tvos",
1199 target_os = "watchos",
1200 ))]
1201 {
1202 if let Some(interval) = keepalive.interval {
1203 let secs = into_secs(interval);
1204 unsafe { setsockopt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL, secs)? }
1205 }
1206
1207 if let Some(retries) = keepalive.retries {
1208 unsafe { setsockopt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT, retries as c_int)? }
1209 }
1210 }
1211
1212 #[cfg(target_os = "nto")]
1213 if let Some(time) = keepalive.time {
1214 let secs = into_timeval(Some(time));
1215 unsafe { setsockopt(fd, libc::IPPROTO_TCP, KEEPALIVE_TIME, secs)? }
1216 }
1217
1218 Ok(())
1219}
1220
1221#[cfg(not(any(
1222 target_os = "haiku",
1223 target_os = "openbsd",
1224 target_os = "nto",
1225 target_os = "vita"
1226)))]
1227fn into_secs(duration: Duration) -> c_int {
1228 min(v1:duration.as_secs(), v2:c_int::MAX as u64) as c_int
1229}
1230
1231/// Get the flags using `cmd`.
1232#[cfg(not(target_os = "vita"))]
1233fn fcntl_get(fd: Socket, cmd: c_int) -> io::Result<c_int> {
1234 syscall!(fcntl(fd, cmd))
1235}
1236
1237/// Add `flag` to the current set flags of `F_GETFD`.
1238#[cfg(not(target_os = "vita"))]
1239fn fcntl_add(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> {
1240 let previous: i32 = fcntl_get(fd, get_cmd)?;
1241 let new: i32 = previous | flag;
1242 if new != previous {
1243 syscall!(fcntl(fd, set_cmd, new)).map(|_| ())
1244 } else {
1245 // Flag was already set.
1246 Ok(())
1247 }
1248}
1249
1250/// Remove `flag` to the current set flags of `F_GETFD`.
1251#[cfg(not(target_os = "vita"))]
1252fn fcntl_remove(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> {
1253 let previous: i32 = fcntl_get(fd, get_cmd)?;
1254 let new: i32 = previous & !flag;
1255 if new != previous {
1256 syscall!(fcntl(fd, set_cmd, new)).map(|_| ())
1257 } else {
1258 // Flag was already set.
1259 Ok(())
1260 }
1261}
1262
1263/// Caller must ensure `T` is the correct type for `opt` and `val`.
1264pub(crate) unsafe fn getsockopt<T>(fd: Socket, opt: c_int, val: c_int) -> io::Result<T> {
1265 let mut payload: MaybeUninit<T> = MaybeUninit::uninit();
1266 let mut len: u32 = size_of::<T>() as libc::socklen_t;
1267 syscall!(getsockopt(
1268 fd,
1269 opt,
1270 val,
1271 payload.as_mut_ptr().cast(),
1272 &mut len,
1273 ))
1274 .map(|_| {
1275 debug_assert_eq!(len as usize, size_of::<T>());
1276 // Safety: `getsockopt` initialised `payload` for us.
1277 payload.assume_init()
1278 })
1279}
1280
1281/// Caller must ensure `T` is the correct type for `opt` and `val`.
1282pub(crate) unsafe fn setsockopt<T>(
1283 fd: Socket,
1284 opt: c_int,
1285 val: c_int,
1286 payload: T,
1287) -> io::Result<()> {
1288 let payload: *const c_void = ptr::addr_of!(payload).cast();
1289 syscall!(setsockopt(
1290 fd,
1291 opt,
1292 val,
1293 payload,
1294 mem::size_of::<T>() as libc::socklen_t,
1295 ))
1296 .map(|_| ())
1297}
1298
1299pub(crate) const fn to_in_addr(addr: &Ipv4Addr) -> in_addr {
1300 // `s_addr` is stored as BE on all machines, and the array is in BE order.
1301 // So the native endian conversion method is used so that it's never
1302 // swapped.
1303 in_addr {
1304 s_addr: u32::from_ne_bytes(addr.octets()),
1305 }
1306}
1307
1308pub(crate) fn from_in_addr(in_addr: in_addr) -> Ipv4Addr {
1309 Ipv4Addr::from(in_addr.s_addr.to_ne_bytes())
1310}
1311
1312pub(crate) const fn to_in6_addr(addr: &Ipv6Addr) -> in6_addr {
1313 in6_addr {
1314 s6_addr: addr.octets(),
1315 }
1316}
1317
1318pub(crate) fn from_in6_addr(addr: in6_addr) -> Ipv6Addr {
1319 Ipv6Addr::from(addr.s6_addr)
1320}
1321
1322#[cfg(not(any(
1323 target_os = "aix",
1324 target_os = "haiku",
1325 target_os = "illumos",
1326 target_os = "netbsd",
1327 target_os = "openbsd",
1328 target_os = "redox",
1329 target_os = "solaris",
1330 target_os = "nto",
1331 target_os = "espidf",
1332 target_os = "vita",
1333)))]
1334pub(crate) const fn to_mreqn(
1335 multiaddr: &Ipv4Addr,
1336 interface: &crate::socket::InterfaceIndexOrAddress,
1337) -> libc::ip_mreqn {
1338 match interface {
1339 crate::socket::InterfaceIndexOrAddress::Index(interface: &u32) => libc::ip_mreqn {
1340 imr_multiaddr: to_in_addr(multiaddr),
1341 imr_address: to_in_addr(&Ipv4Addr::UNSPECIFIED),
1342 imr_ifindex: *interface as _,
1343 },
1344 crate::socket::InterfaceIndexOrAddress::Address(interface: &Ipv4Addr) => libc::ip_mreqn {
1345 imr_multiaddr: to_in_addr(multiaddr),
1346 imr_address: to_in_addr(interface),
1347 imr_ifindex: 0,
1348 },
1349 }
1350}
1351
1352/// Unix only API.
1353impl crate::Socket {
1354 /// Accept a new incoming connection from this listener.
1355 ///
1356 /// This function directly corresponds to the `accept4(2)` function.
1357 ///
1358 /// This function will block the calling thread until a new connection is
1359 /// established. When established, the corresponding `Socket` and the remote
1360 /// peer's address will be returned.
1361 #[doc = man_links!(unix: accept4(2))]
1362 #[cfg(all(
1363 feature = "all",
1364 any(
1365 target_os = "android",
1366 target_os = "dragonfly",
1367 target_os = "freebsd",
1368 target_os = "fuchsia",
1369 target_os = "illumos",
1370 target_os = "linux",
1371 target_os = "netbsd",
1372 target_os = "openbsd",
1373 )
1374 ))]
1375 #[cfg_attr(
1376 docsrs,
1377 doc(cfg(all(
1378 feature = "all",
1379 any(
1380 target_os = "android",
1381 target_os = "dragonfly",
1382 target_os = "freebsd",
1383 target_os = "fuchsia",
1384 target_os = "illumos",
1385 target_os = "linux",
1386 target_os = "netbsd",
1387 target_os = "openbsd",
1388 )
1389 )))
1390 )]
1391 pub fn accept4(&self, flags: c_int) -> io::Result<(crate::Socket, SockAddr)> {
1392 self._accept4(flags)
1393 }
1394
1395 #[cfg(any(
1396 target_os = "android",
1397 target_os = "dragonfly",
1398 target_os = "freebsd",
1399 target_os = "fuchsia",
1400 target_os = "illumos",
1401 target_os = "linux",
1402 target_os = "netbsd",
1403 target_os = "openbsd",
1404 ))]
1405 pub(crate) fn _accept4(&self, flags: c_int) -> io::Result<(crate::Socket, SockAddr)> {
1406 // Safety: `accept4` initialises the `SockAddr` for us.
1407 unsafe {
1408 SockAddr::try_init(|storage, len| {
1409 syscall!(accept4(self.as_raw(), storage.cast(), len, flags))
1410 .map(crate::Socket::from_raw)
1411 })
1412 }
1413 }
1414
1415 /// Sets `CLOEXEC` on the socket.
1416 ///
1417 /// # Notes
1418 ///
1419 /// On supported platforms you can use [`Type::cloexec`].
1420 #[cfg_attr(
1421 any(
1422 target_os = "ios",
1423 target_os = "macos",
1424 target_os = "tvos",
1425 target_os = "watchos"
1426 ),
1427 allow(rustdoc::broken_intra_doc_links)
1428 )]
1429 #[cfg(all(feature = "all", not(target_os = "vita")))]
1430 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))]
1431 pub fn set_cloexec(&self, close_on_exec: bool) -> io::Result<()> {
1432 self._set_cloexec(close_on_exec)
1433 }
1434
1435 #[cfg(not(target_os = "vita"))]
1436 pub(crate) fn _set_cloexec(&self, close_on_exec: bool) -> io::Result<()> {
1437 if close_on_exec {
1438 fcntl_add(
1439 self.as_raw(),
1440 libc::F_GETFD,
1441 libc::F_SETFD,
1442 libc::FD_CLOEXEC,
1443 )
1444 } else {
1445 fcntl_remove(
1446 self.as_raw(),
1447 libc::F_GETFD,
1448 libc::F_SETFD,
1449 libc::FD_CLOEXEC,
1450 )
1451 }
1452 }
1453
1454 /// Sets `SO_NOSIGPIPE` on the socket.
1455 #[cfg(all(
1456 feature = "all",
1457 any(
1458 target_os = "ios",
1459 target_os = "macos",
1460 target_os = "tvos",
1461 target_os = "watchos",
1462 )
1463 ))]
1464 #[cfg_attr(
1465 docsrs,
1466 doc(cfg(all(
1467 feature = "all",
1468 any(
1469 target_os = "ios",
1470 target_os = "macos",
1471 target_os = "tvos",
1472 target_os = "watchos",
1473 )
1474 )))
1475 )]
1476 pub fn set_nosigpipe(&self, nosigpipe: bool) -> io::Result<()> {
1477 self._set_nosigpipe(nosigpipe)
1478 }
1479
1480 #[cfg(any(
1481 target_os = "ios",
1482 target_os = "macos",
1483 target_os = "tvos",
1484 target_os = "watchos",
1485 ))]
1486 pub(crate) fn _set_nosigpipe(&self, nosigpipe: bool) -> io::Result<()> {
1487 unsafe {
1488 setsockopt(
1489 self.as_raw(),
1490 libc::SOL_SOCKET,
1491 libc::SO_NOSIGPIPE,
1492 nosigpipe as c_int,
1493 )
1494 }
1495 }
1496
1497 /// Gets the value of the `TCP_MAXSEG` option on this socket.
1498 ///
1499 /// For more information about this option, see [`set_mss`].
1500 ///
1501 /// [`set_mss`]: crate::Socket::set_mss
1502 #[cfg(all(feature = "all", not(target_os = "redox")))]
1503 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix, not(target_os = "redox")))))]
1504 pub fn mss(&self) -> io::Result<u32> {
1505 unsafe {
1506 getsockopt::<c_int>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_MAXSEG)
1507 .map(|mss| mss as u32)
1508 }
1509 }
1510
1511 /// Sets the value of the `TCP_MAXSEG` option on this socket.
1512 ///
1513 /// The `TCP_MAXSEG` option denotes the TCP Maximum Segment Size and is only
1514 /// available on TCP sockets.
1515 #[cfg(all(feature = "all", not(target_os = "redox")))]
1516 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix, not(target_os = "redox")))))]
1517 pub fn set_mss(&self, mss: u32) -> io::Result<()> {
1518 unsafe {
1519 setsockopt(
1520 self.as_raw(),
1521 libc::IPPROTO_TCP,
1522 libc::TCP_MAXSEG,
1523 mss as c_int,
1524 )
1525 }
1526 }
1527
1528 /// Returns `true` if `listen(2)` was called on this socket by checking the
1529 /// `SO_ACCEPTCONN` option on this socket.
1530 #[cfg(all(
1531 feature = "all",
1532 any(
1533 target_os = "aix",
1534 target_os = "android",
1535 target_os = "freebsd",
1536 target_os = "fuchsia",
1537 target_os = "linux",
1538 )
1539 ))]
1540 #[cfg_attr(
1541 docsrs,
1542 doc(cfg(all(
1543 feature = "all",
1544 any(
1545 target_os = "aix",
1546 target_os = "android",
1547 target_os = "freebsd",
1548 target_os = "fuchsia",
1549 target_os = "linux",
1550 )
1551 )))
1552 )]
1553 pub fn is_listener(&self) -> io::Result<bool> {
1554 unsafe {
1555 getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_ACCEPTCONN)
1556 .map(|v| v != 0)
1557 }
1558 }
1559
1560 /// Returns the [`Domain`] of this socket by checking the `SO_DOMAIN` option
1561 /// on this socket.
1562 #[cfg(all(
1563 feature = "all",
1564 any(
1565 target_os = "android",
1566 // TODO: add FreeBSD.
1567 // target_os = "freebsd",
1568 target_os = "fuchsia",
1569 target_os = "linux",
1570 )
1571 ))]
1572 #[cfg_attr(docsrs, doc(cfg(all(
1573 feature = "all",
1574 any(
1575 target_os = "android",
1576 // TODO: add FreeBSD.
1577 // target_os = "freebsd",
1578 target_os = "fuchsia",
1579 target_os = "linux",
1580 )
1581 ))))]
1582 pub fn domain(&self) -> io::Result<Domain> {
1583 unsafe { getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_DOMAIN).map(Domain) }
1584 }
1585
1586 /// Returns the [`Protocol`] of this socket by checking the `SO_PROTOCOL`
1587 /// option on this socket.
1588 #[cfg(all(
1589 feature = "all",
1590 any(
1591 target_os = "android",
1592 target_os = "freebsd",
1593 target_os = "fuchsia",
1594 target_os = "linux",
1595 )
1596 ))]
1597 #[cfg_attr(
1598 docsrs,
1599 doc(cfg(all(
1600 feature = "all",
1601 any(
1602 target_os = "android",
1603 target_os = "freebsd",
1604 target_os = "fuchsia",
1605 target_os = "linux",
1606 )
1607 )))
1608 )]
1609 pub fn protocol(&self) -> io::Result<Option<Protocol>> {
1610 unsafe {
1611 getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_PROTOCOL).map(|v| match v
1612 {
1613 0 => None,
1614 p => Some(Protocol(p)),
1615 })
1616 }
1617 }
1618
1619 /// Gets the value for the `SO_MARK` option on this socket.
1620 ///
1621 /// This value gets the socket mark field for each packet sent through
1622 /// this socket.
1623 ///
1624 /// On Linux this function requires the `CAP_NET_ADMIN` capability.
1625 #[cfg(all(
1626 feature = "all",
1627 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1628 ))]
1629 #[cfg_attr(
1630 docsrs,
1631 doc(cfg(all(
1632 feature = "all",
1633 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1634 )))
1635 )]
1636 pub fn mark(&self) -> io::Result<u32> {
1637 unsafe {
1638 getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_MARK)
1639 .map(|mark| mark as u32)
1640 }
1641 }
1642
1643 /// Sets the value for the `SO_MARK` option on this socket.
1644 ///
1645 /// This value sets the socket mark field for each packet sent through
1646 /// this socket. Changing the mark can be used for mark-based routing
1647 /// without netfilter or for packet filtering.
1648 ///
1649 /// On Linux this function requires the `CAP_NET_ADMIN` capability.
1650 #[cfg(all(
1651 feature = "all",
1652 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1653 ))]
1654 #[cfg_attr(
1655 docsrs,
1656 doc(cfg(all(
1657 feature = "all",
1658 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1659 )))
1660 )]
1661 pub fn set_mark(&self, mark: u32) -> io::Result<()> {
1662 unsafe {
1663 setsockopt::<c_int>(
1664 self.as_raw(),
1665 libc::SOL_SOCKET,
1666 libc::SO_MARK,
1667 mark as c_int,
1668 )
1669 }
1670 }
1671
1672 /// Get the value of the `TCP_CORK` option on this socket.
1673 ///
1674 /// For more information about this option, see [`set_cork`].
1675 ///
1676 /// [`set_cork`]: crate::Socket::set_cork
1677 #[cfg(all(
1678 feature = "all",
1679 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1680 ))]
1681 #[cfg_attr(
1682 docsrs,
1683 doc(cfg(all(
1684 feature = "all",
1685 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1686 )))
1687 )]
1688 pub fn cork(&self) -> io::Result<bool> {
1689 unsafe {
1690 getsockopt::<Bool>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_CORK)
1691 .map(|cork| cork != 0)
1692 }
1693 }
1694
1695 /// Set the value of the `TCP_CORK` option on this socket.
1696 ///
1697 /// If set, don't send out partial frames. All queued partial frames are
1698 /// sent when the option is cleared again. There is a 200 millisecond ceiling on
1699 /// the time for which output is corked by `TCP_CORK`. If this ceiling is reached,
1700 /// then queued data is automatically transmitted.
1701 #[cfg(all(
1702 feature = "all",
1703 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1704 ))]
1705 #[cfg_attr(
1706 docsrs,
1707 doc(cfg(all(
1708 feature = "all",
1709 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1710 )))
1711 )]
1712 pub fn set_cork(&self, cork: bool) -> io::Result<()> {
1713 unsafe {
1714 setsockopt(
1715 self.as_raw(),
1716 libc::IPPROTO_TCP,
1717 libc::TCP_CORK,
1718 cork as c_int,
1719 )
1720 }
1721 }
1722
1723 /// Get the value of the `TCP_QUICKACK` option on this socket.
1724 ///
1725 /// For more information about this option, see [`set_quickack`].
1726 ///
1727 /// [`set_quickack`]: crate::Socket::set_quickack
1728 #[cfg(all(
1729 feature = "all",
1730 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1731 ))]
1732 #[cfg_attr(
1733 docsrs,
1734 doc(cfg(all(
1735 feature = "all",
1736 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1737 )))
1738 )]
1739 pub fn quickack(&self) -> io::Result<bool> {
1740 unsafe {
1741 getsockopt::<Bool>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_QUICKACK)
1742 .map(|quickack| quickack != 0)
1743 }
1744 }
1745
1746 /// Set the value of the `TCP_QUICKACK` option on this socket.
1747 ///
1748 /// If set, acks are sent immediately, rather than delayed if needed in accordance to normal
1749 /// TCP operation. This flag is not permanent, it only enables a switch to or from quickack mode.
1750 /// Subsequent operation of the TCP protocol will once again enter/leave quickack mode depending on
1751 /// internal protocol processing and factors such as delayed ack timeouts occurring and data transfer.
1752 #[cfg(all(
1753 feature = "all",
1754 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1755 ))]
1756 #[cfg_attr(
1757 docsrs,
1758 doc(cfg(all(
1759 feature = "all",
1760 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1761 )))
1762 )]
1763 pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
1764 unsafe {
1765 setsockopt(
1766 self.as_raw(),
1767 libc::IPPROTO_TCP,
1768 libc::TCP_QUICKACK,
1769 quickack as c_int,
1770 )
1771 }
1772 }
1773
1774 /// Get the value of the `TCP_THIN_LINEAR_TIMEOUTS` option on this socket.
1775 ///
1776 /// For more information about this option, see [`set_thin_linear_timeouts`].
1777 ///
1778 /// [`set_thin_linear_timeouts`]: crate::Socket::set_thin_linear_timeouts
1779 #[cfg(all(
1780 feature = "all",
1781 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1782 ))]
1783 #[cfg_attr(
1784 docsrs,
1785 doc(cfg(all(
1786 feature = "all",
1787 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1788 )))
1789 )]
1790 pub fn thin_linear_timeouts(&self) -> io::Result<bool> {
1791 unsafe {
1792 getsockopt::<Bool>(
1793 self.as_raw(),
1794 libc::IPPROTO_TCP,
1795 libc::TCP_THIN_LINEAR_TIMEOUTS,
1796 )
1797 .map(|timeouts| timeouts != 0)
1798 }
1799 }
1800
1801 /// Set the value of the `TCP_THIN_LINEAR_TIMEOUTS` option on this socket.
1802 ///
1803 /// If set, the kernel will dynamically detect a thin-stream connection if there are less than four packets in flight.
1804 /// With less than four packets in flight the normal TCP fast retransmission will not be effective.
1805 /// The kernel will modify the retransmission to avoid the very high latencies that thin stream suffer because of exponential backoff.
1806 #[cfg(all(
1807 feature = "all",
1808 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1809 ))]
1810 #[cfg_attr(
1811 docsrs,
1812 doc(cfg(all(
1813 feature = "all",
1814 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1815 )))
1816 )]
1817 pub fn set_thin_linear_timeouts(&self, timeouts: bool) -> io::Result<()> {
1818 unsafe {
1819 setsockopt(
1820 self.as_raw(),
1821 libc::IPPROTO_TCP,
1822 libc::TCP_THIN_LINEAR_TIMEOUTS,
1823 timeouts as c_int,
1824 )
1825 }
1826 }
1827
1828 /// Gets the value for the `SO_BINDTODEVICE` option on this socket.
1829 ///
1830 /// This value gets the socket binded device's interface name.
1831 #[cfg(all(
1832 feature = "all",
1833 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1834 ))]
1835 #[cfg_attr(
1836 docsrs,
1837 doc(cfg(all(
1838 feature = "all",
1839 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1840 )))
1841 )]
1842 pub fn device(&self) -> io::Result<Option<Vec<u8>>> {
1843 // TODO: replace with `MaybeUninit::uninit_array` once stable.
1844 let mut buf: [MaybeUninit<u8>; libc::IFNAMSIZ] =
1845 unsafe { MaybeUninit::uninit().assume_init() };
1846 let mut len = buf.len() as libc::socklen_t;
1847 syscall!(getsockopt(
1848 self.as_raw(),
1849 libc::SOL_SOCKET,
1850 libc::SO_BINDTODEVICE,
1851 buf.as_mut_ptr().cast(),
1852 &mut len,
1853 ))?;
1854 if len == 0 {
1855 Ok(None)
1856 } else {
1857 let buf = &buf[..len as usize - 1];
1858 // TODO: use `MaybeUninit::slice_assume_init_ref` once stable.
1859 Ok(Some(unsafe { &*(buf as *const [_] as *const [u8]) }.into()))
1860 }
1861 }
1862
1863 /// Sets the value for the `SO_BINDTODEVICE` option on this socket.
1864 ///
1865 /// If a socket is bound to an interface, only packets received from that
1866 /// particular interface are processed by the socket. Note that this only
1867 /// works for some socket types, particularly `AF_INET` sockets.
1868 ///
1869 /// If `interface` is `None` or an empty string it removes the binding.
1870 #[cfg(all(
1871 feature = "all",
1872 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1873 ))]
1874 #[cfg_attr(
1875 docsrs,
1876 doc(cfg(all(
1877 feature = "all",
1878 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
1879 )))
1880 )]
1881 pub fn bind_device(&self, interface: Option<&[u8]>) -> io::Result<()> {
1882 let (value, len) = if let Some(interface) = interface {
1883 (interface.as_ptr(), interface.len())
1884 } else {
1885 (ptr::null(), 0)
1886 };
1887 syscall!(setsockopt(
1888 self.as_raw(),
1889 libc::SOL_SOCKET,
1890 libc::SO_BINDTODEVICE,
1891 value.cast(),
1892 len as libc::socklen_t,
1893 ))
1894 .map(|_| ())
1895 }
1896
1897 /// Sets the value for the `SO_SETFIB` option on this socket.
1898 ///
1899 /// Bind socket to the specified forwarding table (VRF) on a FreeBSD.
1900 #[cfg(all(feature = "all", target_os = "freebsd"))]
1901 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "freebsd"))))]
1902 pub fn set_fib(&self, fib: u32) -> io::Result<()> {
1903 syscall!(setsockopt(
1904 self.as_raw(),
1905 libc::SOL_SOCKET,
1906 libc::SO_SETFIB,
1907 (&fib as *const u32).cast(),
1908 mem::size_of::<u32>() as libc::socklen_t,
1909 ))
1910 .map(|_| ())
1911 }
1912
1913 /// This method is deprecated, use [`crate::Socket::bind_device_by_index_v4`].
1914 #[cfg(all(
1915 feature = "all",
1916 any(
1917 target_os = "ios",
1918 target_os = "macos",
1919 target_os = "tvos",
1920 target_os = "watchos",
1921 )
1922 ))]
1923 #[cfg_attr(
1924 docsrs,
1925 doc(cfg(all(
1926 feature = "all",
1927 any(
1928 target_os = "ios",
1929 target_os = "macos",
1930 target_os = "tvos",
1931 target_os = "watchos",
1932 )
1933 )))
1934 )]
1935 #[deprecated = "Use `Socket::bind_device_by_index_v4` instead"]
1936 pub fn bind_device_by_index(&self, interface: Option<NonZeroU32>) -> io::Result<()> {
1937 self.bind_device_by_index_v4(interface)
1938 }
1939
1940 /// Sets the value for `IP_BOUND_IF` option on this socket.
1941 ///
1942 /// If a socket is bound to an interface, only packets received from that
1943 /// particular interface are processed by the socket.
1944 ///
1945 /// If `interface` is `None`, the binding is removed. If the `interface`
1946 /// index is not valid, an error is returned.
1947 ///
1948 /// One can use [`libc::if_nametoindex`] to convert an interface alias to an
1949 /// index.
1950 #[cfg(all(
1951 feature = "all",
1952 any(
1953 target_os = "ios",
1954 target_os = "macos",
1955 target_os = "tvos",
1956 target_os = "watchos",
1957 )
1958 ))]
1959 #[cfg_attr(
1960 docsrs,
1961 doc(cfg(all(
1962 feature = "all",
1963 any(
1964 target_os = "ios",
1965 target_os = "macos",
1966 target_os = "tvos",
1967 target_os = "watchos",
1968 )
1969 )))
1970 )]
1971 pub fn bind_device_by_index_v4(&self, interface: Option<NonZeroU32>) -> io::Result<()> {
1972 let index = interface.map_or(0, NonZeroU32::get);
1973 unsafe { setsockopt(self.as_raw(), IPPROTO_IP, libc::IP_BOUND_IF, index) }
1974 }
1975
1976 /// Sets the value for `IPV6_BOUND_IF` option on this socket.
1977 ///
1978 /// If a socket is bound to an interface, only packets received from that
1979 /// particular interface are processed by the socket.
1980 ///
1981 /// If `interface` is `None`, the binding is removed. If the `interface`
1982 /// index is not valid, an error is returned.
1983 ///
1984 /// One can use [`libc::if_nametoindex`] to convert an interface alias to an
1985 /// index.
1986 #[cfg(all(
1987 feature = "all",
1988 any(
1989 target_os = "ios",
1990 target_os = "macos",
1991 target_os = "tvos",
1992 target_os = "watchos",
1993 )
1994 ))]
1995 #[cfg_attr(
1996 docsrs,
1997 doc(cfg(all(
1998 feature = "all",
1999 any(
2000 target_os = "ios",
2001 target_os = "macos",
2002 target_os = "tvos",
2003 target_os = "watchos",
2004 )
2005 )))
2006 )]
2007 pub fn bind_device_by_index_v6(&self, interface: Option<NonZeroU32>) -> io::Result<()> {
2008 let index = interface.map_or(0, NonZeroU32::get);
2009 unsafe { setsockopt(self.as_raw(), IPPROTO_IPV6, libc::IPV6_BOUND_IF, index) }
2010 }
2011
2012 /// Gets the value for `IP_BOUND_IF` option on this socket, i.e. the index
2013 /// for the interface to which the socket is bound.
2014 ///
2015 /// Returns `None` if the socket is not bound to any interface, otherwise
2016 /// returns an interface index.
2017 #[cfg(all(
2018 feature = "all",
2019 any(
2020 target_os = "ios",
2021 target_os = "macos",
2022 target_os = "tvos",
2023 target_os = "watchos",
2024 )
2025 ))]
2026 #[cfg_attr(
2027 docsrs,
2028 doc(cfg(all(
2029 feature = "all",
2030 any(
2031 target_os = "ios",
2032 target_os = "macos",
2033 target_os = "tvos",
2034 target_os = "watchos",
2035 )
2036 )))
2037 )]
2038 pub fn device_index_v4(&self) -> io::Result<Option<NonZeroU32>> {
2039 let index =
2040 unsafe { getsockopt::<libc::c_uint>(self.as_raw(), IPPROTO_IP, libc::IP_BOUND_IF)? };
2041 Ok(NonZeroU32::new(index))
2042 }
2043
2044 /// This method is deprecated, use [`crate::Socket::device_index_v4`].
2045 #[cfg(all(
2046 feature = "all",
2047 any(
2048 target_os = "ios",
2049 target_os = "macos",
2050 target_os = "tvos",
2051 target_os = "watchos",
2052 )
2053 ))]
2054 #[cfg_attr(
2055 docsrs,
2056 doc(cfg(all(
2057 feature = "all",
2058 any(
2059 target_os = "ios",
2060 target_os = "macos",
2061 target_os = "tvos",
2062 target_os = "watchos",
2063 )
2064 )))
2065 )]
2066 #[deprecated = "Use `Socket::device_index_v4` instead"]
2067 pub fn device_index(&self) -> io::Result<Option<NonZeroU32>> {
2068 self.device_index_v4()
2069 }
2070
2071 /// Gets the value for `IPV6_BOUND_IF` option on this socket, i.e. the index
2072 /// for the interface to which the socket is bound.
2073 ///
2074 /// Returns `None` if the socket is not bound to any interface, otherwise
2075 /// returns an interface index.
2076 #[cfg(all(
2077 feature = "all",
2078 any(
2079 target_os = "ios",
2080 target_os = "macos",
2081 target_os = "tvos",
2082 target_os = "watchos",
2083 )
2084 ))]
2085 #[cfg_attr(
2086 docsrs,
2087 doc(cfg(all(
2088 feature = "all",
2089 any(
2090 target_os = "ios",
2091 target_os = "macos",
2092 target_os = "tvos",
2093 target_os = "watchos",
2094 )
2095 )))
2096 )]
2097 pub fn device_index_v6(&self) -> io::Result<Option<NonZeroU32>> {
2098 let index = unsafe {
2099 getsockopt::<libc::c_uint>(self.as_raw(), IPPROTO_IPV6, libc::IPV6_BOUND_IF)?
2100 };
2101 Ok(NonZeroU32::new(index))
2102 }
2103
2104 /// Get the value of the `SO_INCOMING_CPU` option on this socket.
2105 ///
2106 /// For more information about this option, see [`set_cpu_affinity`].
2107 ///
2108 /// [`set_cpu_affinity`]: crate::Socket::set_cpu_affinity
2109 #[cfg(all(feature = "all", target_os = "linux"))]
2110 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2111 pub fn cpu_affinity(&self) -> io::Result<usize> {
2112 unsafe {
2113 getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_INCOMING_CPU)
2114 .map(|cpu| cpu as usize)
2115 }
2116 }
2117
2118 /// Set value for the `SO_INCOMING_CPU` option on this socket.
2119 ///
2120 /// Sets the CPU affinity of the socket.
2121 #[cfg(all(feature = "all", target_os = "linux"))]
2122 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2123 pub fn set_cpu_affinity(&self, cpu: usize) -> io::Result<()> {
2124 unsafe {
2125 setsockopt(
2126 self.as_raw(),
2127 libc::SOL_SOCKET,
2128 libc::SO_INCOMING_CPU,
2129 cpu as c_int,
2130 )
2131 }
2132 }
2133
2134 /// Get the value of the `SO_REUSEPORT` option on this socket.
2135 ///
2136 /// For more information about this option, see [`set_reuse_port`].
2137 ///
2138 /// [`set_reuse_port`]: crate::Socket::set_reuse_port
2139 #[cfg(all(
2140 feature = "all",
2141 not(any(target_os = "solaris", target_os = "illumos"))
2142 ))]
2143 #[cfg_attr(
2144 docsrs,
2145 doc(cfg(all(
2146 feature = "all",
2147 unix,
2148 not(any(target_os = "solaris", target_os = "illumos"))
2149 )))
2150 )]
2151 pub fn reuse_port(&self) -> io::Result<bool> {
2152 unsafe {
2153 getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_REUSEPORT)
2154 .map(|reuse| reuse != 0)
2155 }
2156 }
2157
2158 /// Set value for the `SO_REUSEPORT` option on this socket.
2159 ///
2160 /// This indicates that further calls to `bind` may allow reuse of local
2161 /// addresses. For IPv4 sockets this means that a socket may bind even when
2162 /// there's a socket already listening on this port.
2163 #[cfg(all(
2164 feature = "all",
2165 not(any(target_os = "solaris", target_os = "illumos"))
2166 ))]
2167 #[cfg_attr(
2168 docsrs,
2169 doc(cfg(all(
2170 feature = "all",
2171 unix,
2172 not(any(target_os = "solaris", target_os = "illumos"))
2173 )))
2174 )]
2175 pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> {
2176 unsafe {
2177 setsockopt(
2178 self.as_raw(),
2179 libc::SOL_SOCKET,
2180 libc::SO_REUSEPORT,
2181 reuse as c_int,
2182 )
2183 }
2184 }
2185
2186 /// Get the value of the `SO_REUSEPORT_LB` option on this socket.
2187 ///
2188 /// For more information about this option, see [`set_reuse_port_lb`].
2189 ///
2190 /// [`set_reuse_port_lb`]: crate::Socket::set_reuse_port_lb
2191 #[cfg(all(feature = "all", target_os = "freebsd"))]
2192 pub fn reuse_port_lb(&self) -> io::Result<bool> {
2193 unsafe {
2194 getsockopt::<c_int>(self.as_raw(), libc::SOL_SOCKET, libc::SO_REUSEPORT_LB)
2195 .map(|reuse| reuse != 0)
2196 }
2197 }
2198
2199 /// Set value for the `SO_REUSEPORT_LB` option on this socket.
2200 ///
2201 /// This allows multiple programs or threads to bind to the same port and
2202 /// incoming connections will be load balanced using a hash function.
2203 #[cfg(all(feature = "all", target_os = "freebsd"))]
2204 pub fn set_reuse_port_lb(&self, reuse: bool) -> io::Result<()> {
2205 unsafe {
2206 setsockopt(
2207 self.as_raw(),
2208 libc::SOL_SOCKET,
2209 libc::SO_REUSEPORT_LB,
2210 reuse as c_int,
2211 )
2212 }
2213 }
2214
2215 /// Get the value of the `IP_FREEBIND` option on this socket.
2216 ///
2217 /// For more information about this option, see [`set_freebind`].
2218 ///
2219 /// [`set_freebind`]: crate::Socket::set_freebind
2220 #[cfg(all(
2221 feature = "all",
2222 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2223 ))]
2224 #[cfg_attr(
2225 docsrs,
2226 doc(cfg(all(
2227 feature = "all",
2228 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2229 )))
2230 )]
2231 pub fn freebind(&self) -> io::Result<bool> {
2232 unsafe {
2233 getsockopt::<c_int>(self.as_raw(), libc::SOL_IP, libc::IP_FREEBIND)
2234 .map(|freebind| freebind != 0)
2235 }
2236 }
2237
2238 /// Set value for the `IP_FREEBIND` option on this socket.
2239 ///
2240 /// If enabled, this boolean option allows binding to an IP address that is
2241 /// nonlocal or does not (yet) exist. This permits listening on a socket,
2242 /// without requiring the underlying network interface or the specified
2243 /// dynamic IP address to be up at the time that the application is trying
2244 /// to bind to it.
2245 #[cfg(all(
2246 feature = "all",
2247 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2248 ))]
2249 #[cfg_attr(
2250 docsrs,
2251 doc(cfg(all(
2252 feature = "all",
2253 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2254 )))
2255 )]
2256 pub fn set_freebind(&self, freebind: bool) -> io::Result<()> {
2257 unsafe {
2258 setsockopt(
2259 self.as_raw(),
2260 libc::SOL_IP,
2261 libc::IP_FREEBIND,
2262 freebind as c_int,
2263 )
2264 }
2265 }
2266
2267 /// Get the value of the `IPV6_FREEBIND` option on this socket.
2268 ///
2269 /// This is an IPv6 counterpart of `IP_FREEBIND` socket option on
2270 /// Android/Linux. For more information about this option, see
2271 /// [`set_freebind`].
2272 ///
2273 /// [`set_freebind`]: crate::Socket::set_freebind
2274 #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
2275 #[cfg_attr(
2276 docsrs,
2277 doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
2278 )]
2279 pub fn freebind_ipv6(&self) -> io::Result<bool> {
2280 unsafe {
2281 getsockopt::<c_int>(self.as_raw(), libc::SOL_IPV6, libc::IPV6_FREEBIND)
2282 .map(|freebind| freebind != 0)
2283 }
2284 }
2285
2286 /// Set value for the `IPV6_FREEBIND` option on this socket.
2287 ///
2288 /// This is an IPv6 counterpart of `IP_FREEBIND` socket option on
2289 /// Android/Linux. For more information about this option, see
2290 /// [`set_freebind`].
2291 ///
2292 /// [`set_freebind`]: crate::Socket::set_freebind
2293 ///
2294 /// # Examples
2295 ///
2296 /// On Linux:
2297 ///
2298 /// ```
2299 /// use socket2::{Domain, Socket, Type};
2300 /// use std::io::{self, Error, ErrorKind};
2301 ///
2302 /// fn enable_freebind(socket: &Socket) -> io::Result<()> {
2303 /// match socket.domain()? {
2304 /// Domain::IPV4 => socket.set_freebind(true)?,
2305 /// Domain::IPV6 => socket.set_freebind_ipv6(true)?,
2306 /// _ => return Err(Error::new(ErrorKind::Other, "unsupported domain")),
2307 /// };
2308 /// Ok(())
2309 /// }
2310 ///
2311 /// # fn main() -> io::Result<()> {
2312 /// # let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
2313 /// # enable_freebind(&socket)
2314 /// # }
2315 /// ```
2316 #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
2317 #[cfg_attr(
2318 docsrs,
2319 doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
2320 )]
2321 pub fn set_freebind_ipv6(&self, freebind: bool) -> io::Result<()> {
2322 unsafe {
2323 setsockopt(
2324 self.as_raw(),
2325 libc::SOL_IPV6,
2326 libc::IPV6_FREEBIND,
2327 freebind as c_int,
2328 )
2329 }
2330 }
2331
2332 /// Get the value for the `SO_ORIGINAL_DST` option on this socket.
2333 ///
2334 /// This value contains the original destination IPv4 address of the connection
2335 /// redirected using `iptables` `REDIRECT` or `TPROXY`.
2336 #[cfg(all(
2337 feature = "all",
2338 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2339 ))]
2340 #[cfg_attr(
2341 docsrs,
2342 doc(cfg(all(
2343 feature = "all",
2344 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2345 )))
2346 )]
2347 pub fn original_dst(&self) -> io::Result<SockAddr> {
2348 // Safety: `getsockopt` initialises the `SockAddr` for us.
2349 unsafe {
2350 SockAddr::try_init(|storage, len| {
2351 syscall!(getsockopt(
2352 self.as_raw(),
2353 libc::SOL_IP,
2354 libc::SO_ORIGINAL_DST,
2355 storage.cast(),
2356 len
2357 ))
2358 })
2359 }
2360 .map(|(_, addr)| addr)
2361 }
2362
2363 /// Get the value for the `IP6T_SO_ORIGINAL_DST` option on this socket.
2364 ///
2365 /// This value contains the original destination IPv6 address of the connection
2366 /// redirected using `ip6tables` `REDIRECT` or `TPROXY`.
2367 #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
2368 #[cfg_attr(
2369 docsrs,
2370 doc(cfg(all(feature = "all", any(target_os = "android", target_os = "linux"))))
2371 )]
2372 pub fn original_dst_ipv6(&self) -> io::Result<SockAddr> {
2373 // Safety: `getsockopt` initialises the `SockAddr` for us.
2374 unsafe {
2375 SockAddr::try_init(|storage, len| {
2376 syscall!(getsockopt(
2377 self.as_raw(),
2378 libc::SOL_IPV6,
2379 libc::IP6T_SO_ORIGINAL_DST,
2380 storage.cast(),
2381 len
2382 ))
2383 })
2384 }
2385 .map(|(_, addr)| addr)
2386 }
2387
2388 /// Copies data between a `file` and this socket using the `sendfile(2)`
2389 /// system call. Because this copying is done within the kernel,
2390 /// `sendfile()` is more efficient than the combination of `read(2)` and
2391 /// `write(2)`, which would require transferring data to and from user
2392 /// space.
2393 ///
2394 /// Different OSs support different kinds of `file`s, see the OS
2395 /// documentation for what kind of files are supported. Generally *regular*
2396 /// files are supported by all OSs.
2397 #[doc = man_links!(unix: sendfile(2))]
2398 ///
2399 /// The `offset` is the absolute offset into the `file` to use as starting
2400 /// point.
2401 ///
2402 /// Depending on the OS this function *may* change the offset of `file`. For
2403 /// the best results reset the offset of the file before using it again.
2404 ///
2405 /// The `length` determines how many bytes to send, where a length of `None`
2406 /// means it will try to send all bytes.
2407 #[cfg(all(
2408 feature = "all",
2409 any(
2410 target_os = "aix",
2411 target_os = "android",
2412 target_os = "freebsd",
2413 target_os = "ios",
2414 target_os = "linux",
2415 target_os = "macos",
2416 target_os = "tvos",
2417 target_os = "watchos",
2418 )
2419 ))]
2420 #[cfg_attr(
2421 docsrs,
2422 doc(cfg(all(
2423 feature = "all",
2424 any(
2425 target_os = "aix",
2426 target_os = "android",
2427 target_os = "freebsd",
2428 target_os = "ios",
2429 target_os = "linux",
2430 target_os = "macos",
2431 target_os = "tvos",
2432 target_os = "watchos",
2433 )
2434 )))
2435 )]
2436 pub fn sendfile<F>(
2437 &self,
2438 file: &F,
2439 offset: usize,
2440 length: Option<NonZeroUsize>,
2441 ) -> io::Result<usize>
2442 where
2443 F: AsRawFd,
2444 {
2445 self._sendfile(file.as_raw_fd(), offset as _, length)
2446 }
2447
2448 #[cfg(all(
2449 feature = "all",
2450 any(
2451 target_os = "ios",
2452 target_os = "macos",
2453 target_os = "tvos",
2454 target_os = "watchos",
2455 )
2456 ))]
2457 fn _sendfile(
2458 &self,
2459 file: RawFd,
2460 offset: libc::off_t,
2461 length: Option<NonZeroUsize>,
2462 ) -> io::Result<usize> {
2463 // On macOS `length` is value-result parameter. It determines the number
2464 // of bytes to write and returns the number of bytes written.
2465 let mut length = match length {
2466 Some(n) => n.get() as libc::off_t,
2467 // A value of `0` means send all bytes.
2468 None => 0,
2469 };
2470 syscall!(sendfile(
2471 file,
2472 self.as_raw(),
2473 offset,
2474 &mut length,
2475 ptr::null_mut(),
2476 0,
2477 ))
2478 .map(|_| length as usize)
2479 }
2480
2481 #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))]
2482 fn _sendfile(
2483 &self,
2484 file: RawFd,
2485 offset: libc::off_t,
2486 length: Option<NonZeroUsize>,
2487 ) -> io::Result<usize> {
2488 let count = match length {
2489 Some(n) => n.get() as libc::size_t,
2490 // The maximum the Linux kernel will write in a single call.
2491 None => 0x7ffff000, // 2,147,479,552 bytes.
2492 };
2493 let mut offset = offset;
2494 syscall!(sendfile(self.as_raw(), file, &mut offset, count)).map(|n| n as usize)
2495 }
2496
2497 #[cfg(all(feature = "all", target_os = "freebsd"))]
2498 fn _sendfile(
2499 &self,
2500 file: RawFd,
2501 offset: libc::off_t,
2502 length: Option<NonZeroUsize>,
2503 ) -> io::Result<usize> {
2504 let nbytes = match length {
2505 Some(n) => n.get() as libc::size_t,
2506 // A value of `0` means send all bytes.
2507 None => 0,
2508 };
2509 let mut sbytes: libc::off_t = 0;
2510 syscall!(sendfile(
2511 file,
2512 self.as_raw(),
2513 offset,
2514 nbytes,
2515 ptr::null_mut(),
2516 &mut sbytes,
2517 0,
2518 ))
2519 .map(|_| sbytes as usize)
2520 }
2521
2522 #[cfg(all(feature = "all", target_os = "aix"))]
2523 fn _sendfile(
2524 &self,
2525 file: RawFd,
2526 offset: libc::off_t,
2527 length: Option<NonZeroUsize>,
2528 ) -> io::Result<usize> {
2529 let nbytes = match length {
2530 Some(n) => n.get() as i64,
2531 None => -1,
2532 };
2533 let mut params = libc::sf_parms {
2534 header_data: ptr::null_mut(),
2535 header_length: 0,
2536 file_descriptor: file,
2537 file_size: 0,
2538 file_offset: offset as u64,
2539 file_bytes: nbytes,
2540 trailer_data: ptr::null_mut(),
2541 trailer_length: 0,
2542 bytes_sent: 0,
2543 };
2544 // AIX doesn't support SF_REUSE, socket will be closed after successful transmission.
2545 syscall!(send_file(
2546 &mut self.as_raw() as *mut _,
2547 &mut params as *mut _,
2548 libc::SF_CLOSE as libc::c_uint,
2549 ))
2550 .map(|_| params.bytes_sent as usize)
2551 }
2552
2553 /// Set the value of the `TCP_USER_TIMEOUT` option on this socket.
2554 ///
2555 /// If set, this specifies the maximum amount of time that transmitted data may remain
2556 /// unacknowledged or buffered data may remain untransmitted before TCP will forcibly close the
2557 /// corresponding connection.
2558 ///
2559 /// Setting `timeout` to `None` or a zero duration causes the system default timeouts to
2560 /// be used. If `timeout` in milliseconds is larger than `c_uint::MAX`, the timeout is clamped
2561 /// to `c_uint::MAX`. For example, when `c_uint` is a 32-bit value, this limits the timeout to
2562 /// approximately 49.71 days.
2563 #[cfg(all(
2564 feature = "all",
2565 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2566 ))]
2567 #[cfg_attr(
2568 docsrs,
2569 doc(cfg(all(
2570 feature = "all",
2571 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2572 )))
2573 )]
2574 pub fn set_tcp_user_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
2575 let timeout = timeout.map_or(0, |to| {
2576 min(to.as_millis(), libc::c_uint::MAX as u128) as libc::c_uint
2577 });
2578 unsafe {
2579 setsockopt(
2580 self.as_raw(),
2581 libc::IPPROTO_TCP,
2582 libc::TCP_USER_TIMEOUT,
2583 timeout,
2584 )
2585 }
2586 }
2587
2588 /// Get the value of the `TCP_USER_TIMEOUT` option on this socket.
2589 ///
2590 /// For more information about this option, see [`set_tcp_user_timeout`].
2591 ///
2592 /// [`set_tcp_user_timeout`]: crate::Socket::set_tcp_user_timeout
2593 #[cfg(all(
2594 feature = "all",
2595 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2596 ))]
2597 #[cfg_attr(
2598 docsrs,
2599 doc(cfg(all(
2600 feature = "all",
2601 any(target_os = "android", target_os = "fuchsia", target_os = "linux")
2602 )))
2603 )]
2604 pub fn tcp_user_timeout(&self) -> io::Result<Option<Duration>> {
2605 unsafe {
2606 getsockopt::<libc::c_uint>(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT)
2607 .map(|millis| {
2608 if millis == 0 {
2609 None
2610 } else {
2611 Some(Duration::from_millis(millis as u64))
2612 }
2613 })
2614 }
2615 }
2616
2617 /// Attach Berkeley Packet Filter(BPF) on this socket.
2618 ///
2619 /// BPF allows a user-space program to attach a filter onto any socket
2620 /// and allow or disallow certain types of data to come through the socket.
2621 ///
2622 /// For more information about this option, see [filter](https://www.kernel.org/doc/html/v5.12/networking/filter.html)
2623 #[cfg(all(feature = "all", any(target_os = "linux", target_os = "android")))]
2624 pub fn attach_filter(&self, filters: &[libc::sock_filter]) -> io::Result<()> {
2625 let prog = libc::sock_fprog {
2626 len: filters.len() as u16,
2627 filter: filters.as_ptr() as *mut _,
2628 };
2629
2630 unsafe {
2631 setsockopt(
2632 self.as_raw(),
2633 libc::SOL_SOCKET,
2634 libc::SO_ATTACH_FILTER,
2635 prog,
2636 )
2637 }
2638 }
2639
2640 /// Detach Berkeley Packet Filter(BPF) from this socket.
2641 ///
2642 /// For more information about this option, see [`attach_filter`]
2643 ///
2644 /// [`attach_filter`]: crate::Socket::attach_filter
2645 #[cfg(all(feature = "all", any(target_os = "linux", target_os = "android")))]
2646 pub fn detach_filter(&self) -> io::Result<()> {
2647 unsafe { setsockopt(self.as_raw(), libc::SOL_SOCKET, libc::SO_DETACH_FILTER, 0) }
2648 }
2649
2650 /// Gets the value for the `SO_COOKIE` option on this socket.
2651 ///
2652 /// The socket cookie is a unique, kernel-managed identifier tied to each socket.
2653 /// Therefore, there is no corresponding `set` helper.
2654 ///
2655 /// For more information about this option, see [Linux patch](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5daab9db7b65df87da26fd8cfa695fb9546a1ddb)
2656 #[cfg(all(feature = "all", target_os = "linux"))]
2657 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2658 pub fn cookie(&self) -> io::Result<u64> {
2659 unsafe { getsockopt::<libc::c_ulonglong>(self.as_raw(), libc::SOL_SOCKET, libc::SO_COOKIE) }
2660 }
2661
2662 /// Get the value of the `IPV6_TCLASS` option for this socket.
2663 ///
2664 /// For more information about this option, see [`set_tclass_v6`].
2665 ///
2666 /// [`set_tclass_v6`]: crate::Socket::set_tclass_v6
2667 #[cfg(all(
2668 feature = "all",
2669 any(
2670 target_os = "android",
2671 target_os = "dragonfly",
2672 target_os = "freebsd",
2673 target_os = "fuchsia",
2674 target_os = "linux",
2675 target_os = "macos",
2676 target_os = "netbsd",
2677 target_os = "openbsd"
2678 )
2679 ))]
2680 #[cfg_attr(
2681 docsrs,
2682 doc(cfg(all(
2683 feature = "all",
2684 any(
2685 target_os = "android",
2686 target_os = "dragonfly",
2687 target_os = "freebsd",
2688 target_os = "fuchsia",
2689 target_os = "linux",
2690 target_os = "macos",
2691 target_os = "netbsd",
2692 target_os = "openbsd"
2693 )
2694 )))
2695 )]
2696 pub fn tclass_v6(&self) -> io::Result<u32> {
2697 unsafe {
2698 getsockopt::<c_int>(self.as_raw(), IPPROTO_IPV6, libc::IPV6_TCLASS)
2699 .map(|tclass| tclass as u32)
2700 }
2701 }
2702
2703 /// Set the value of the `IPV6_TCLASS` option for this socket.
2704 ///
2705 /// Specifies the traffic class field that is used in every packets
2706 /// sent from this socket.
2707 #[cfg(all(
2708 feature = "all",
2709 any(
2710 target_os = "android",
2711 target_os = "dragonfly",
2712 target_os = "freebsd",
2713 target_os = "fuchsia",
2714 target_os = "linux",
2715 target_os = "macos",
2716 target_os = "netbsd",
2717 target_os = "openbsd"
2718 )
2719 ))]
2720 #[cfg_attr(
2721 docsrs,
2722 doc(cfg(all(
2723 feature = "all",
2724 any(
2725 target_os = "android",
2726 target_os = "dragonfly",
2727 target_os = "freebsd",
2728 target_os = "fuchsia",
2729 target_os = "linux",
2730 target_os = "macos",
2731 target_os = "netbsd",
2732 target_os = "openbsd"
2733 )
2734 )))
2735 )]
2736 pub fn set_tclass_v6(&self, tclass: u32) -> io::Result<()> {
2737 unsafe {
2738 setsockopt(
2739 self.as_raw(),
2740 IPPROTO_IPV6,
2741 libc::IPV6_TCLASS,
2742 tclass as c_int,
2743 )
2744 }
2745 }
2746
2747 /// Get the value of the `TCP_CONGESTION` option for this socket.
2748 ///
2749 /// For more information about this option, see [`set_tcp_congestion`].
2750 ///
2751 /// [`set_tcp_congestion`]: crate::Socket::set_tcp_congestion
2752 #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
2753 #[cfg_attr(
2754 docsrs,
2755 doc(cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux"))))
2756 )]
2757 pub fn tcp_congestion(&self) -> io::Result<Vec<u8>> {
2758 let mut payload: [u8; TCP_CA_NAME_MAX] = [0; TCP_CA_NAME_MAX];
2759 let mut len = payload.len() as libc::socklen_t;
2760 syscall!(getsockopt(
2761 self.as_raw(),
2762 IPPROTO_TCP,
2763 libc::TCP_CONGESTION,
2764 payload.as_mut_ptr().cast(),
2765 &mut len,
2766 ))
2767 .map(|_| payload[..len as usize].to_vec())
2768 }
2769
2770 /// Set the value of the `TCP_CONGESTION` option for this socket.
2771 ///
2772 /// Specifies the TCP congestion control algorithm to use for this socket.
2773 ///
2774 /// The value must be a valid TCP congestion control algorithm name of the
2775 /// platform. For example, Linux may supports "reno", "cubic".
2776 #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
2777 #[cfg_attr(
2778 docsrs,
2779 doc(cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux"))))
2780 )]
2781 pub fn set_tcp_congestion(&self, tcp_ca_name: &[u8]) -> io::Result<()> {
2782 syscall!(setsockopt(
2783 self.as_raw(),
2784 IPPROTO_TCP,
2785 libc::TCP_CONGESTION,
2786 tcp_ca_name.as_ptr() as *const _,
2787 tcp_ca_name.len() as libc::socklen_t,
2788 ))
2789 .map(|_| ())
2790 }
2791
2792 /// Set value for the `DCCP_SOCKOPT_SERVICE` option on this socket.
2793 ///
2794 /// Sets the DCCP service. The specification mandates use of service codes.
2795 /// If this socket option is not set, the socket will fall back to 0 (which
2796 /// means that no meaningful service code is present). On active sockets
2797 /// this is set before [`connect`]. On passive sockets up to 32 service
2798 /// codes can be set before calling [`bind`]
2799 ///
2800 /// [`connect`]: crate::Socket::connect
2801 /// [`bind`]: crate::Socket::bind
2802 #[cfg(all(feature = "all", target_os = "linux"))]
2803 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2804 pub fn set_dccp_service(&self, code: u32) -> io::Result<()> {
2805 unsafe {
2806 setsockopt(
2807 self.as_raw(),
2808 libc::SOL_DCCP,
2809 libc::DCCP_SOCKOPT_SERVICE,
2810 code,
2811 )
2812 }
2813 }
2814
2815 /// Get the value of the `DCCP_SOCKOPT_SERVICE` option on this socket.
2816 ///
2817 /// For more information about this option see [`set_dccp_service`]
2818 ///
2819 /// [`set_dccp_service`]: crate::Socket::set_dccp_service
2820 #[cfg(all(feature = "all", target_os = "linux"))]
2821 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2822 pub fn dccp_service(&self) -> io::Result<u32> {
2823 unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_SERVICE) }
2824 }
2825
2826 /// Set value for the `DCCP_SOCKOPT_CCID` option on this socket.
2827 ///
2828 /// This option sets both the TX and RX CCIDs at the same time.
2829 #[cfg(all(feature = "all", target_os = "linux"))]
2830 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2831 pub fn set_dccp_ccid(&self, ccid: u8) -> io::Result<()> {
2832 unsafe { setsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_CCID, ccid) }
2833 }
2834
2835 /// Get the value of the `DCCP_SOCKOPT_TX_CCID` option on this socket.
2836 ///
2837 /// For more information about this option see [`set_dccp_ccid`].
2838 ///
2839 /// [`set_dccp_ccid`]: crate::Socket::set_dccp_ccid
2840 #[cfg(all(feature = "all", target_os = "linux"))]
2841 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2842 pub fn dccp_tx_ccid(&self) -> io::Result<u32> {
2843 unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_TX_CCID) }
2844 }
2845
2846 /// Get the value of the `DCCP_SOCKOPT_RX_CCID` option on this socket.
2847 ///
2848 /// For more information about this option see [`set_dccp_ccid`].
2849 ///
2850 /// [`set_dccp_ccid`]: crate::Socket::set_dccp_ccid
2851 #[cfg(all(feature = "all", target_os = "linux"))]
2852 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2853 pub fn dccp_xx_ccid(&self) -> io::Result<u32> {
2854 unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_RX_CCID) }
2855 }
2856
2857 /// Set value for the `DCCP_SOCKOPT_SERVER_TIMEWAIT` option on this socket.
2858 ///
2859 /// Enables a listening socket to hold timewait state when closing the
2860 /// connection. This option must be set after `accept` returns.
2861 #[cfg(all(feature = "all", target_os = "linux"))]
2862 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2863 pub fn set_dccp_server_timewait(&self, hold_timewait: bool) -> io::Result<()> {
2864 unsafe {
2865 setsockopt(
2866 self.as_raw(),
2867 libc::SOL_DCCP,
2868 libc::DCCP_SOCKOPT_SERVER_TIMEWAIT,
2869 hold_timewait as c_int,
2870 )
2871 }
2872 }
2873
2874 /// Get the value of the `DCCP_SOCKOPT_SERVER_TIMEWAIT` option on this socket.
2875 ///
2876 /// For more information see [`set_dccp_server_timewait`]
2877 ///
2878 /// [`set_dccp_server_timewait`]: crate::Socket::set_dccp_server_timewait
2879 #[cfg(all(feature = "all", target_os = "linux"))]
2880 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2881 pub fn dccp_server_timewait(&self) -> io::Result<bool> {
2882 unsafe {
2883 getsockopt(
2884 self.as_raw(),
2885 libc::SOL_DCCP,
2886 libc::DCCP_SOCKOPT_SERVER_TIMEWAIT,
2887 )
2888 }
2889 }
2890
2891 /// Set value for the `DCCP_SOCKOPT_SEND_CSCOV` option on this socket.
2892 ///
2893 /// Both this option and `DCCP_SOCKOPT_RECV_CSCOV` are used for setting the
2894 /// partial checksum coverage. The default is that checksums always cover
2895 /// the entire packet and that only fully covered application data is
2896 /// accepted by the receiver. Hence, when using this feature on the sender,
2897 /// it must be enabled at the receiver too, with suitable choice of CsCov.
2898 #[cfg(all(feature = "all", target_os = "linux"))]
2899 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2900 pub fn set_dccp_send_cscov(&self, level: u32) -> io::Result<()> {
2901 unsafe {
2902 setsockopt(
2903 self.as_raw(),
2904 libc::SOL_DCCP,
2905 libc::DCCP_SOCKOPT_SEND_CSCOV,
2906 level,
2907 )
2908 }
2909 }
2910
2911 /// Get the value of the `DCCP_SOCKOPT_SEND_CSCOV` option on this socket.
2912 ///
2913 /// For more information on this option see [`set_dccp_send_cscov`].
2914 ///
2915 /// [`set_dccp_send_cscov`]: crate::Socket::set_dccp_send_cscov
2916 #[cfg(all(feature = "all", target_os = "linux"))]
2917 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2918 pub fn dccp_send_cscov(&self) -> io::Result<u32> {
2919 unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_SEND_CSCOV) }
2920 }
2921
2922 /// Set the value of the `DCCP_SOCKOPT_RECV_CSCOV` option on this socket.
2923 ///
2924 /// This option is only useful when combined with [`set_dccp_send_cscov`].
2925 ///
2926 /// [`set_dccp_send_cscov`]: crate::Socket::set_dccp_send_cscov
2927 #[cfg(all(feature = "all", target_os = "linux"))]
2928 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2929 pub fn set_dccp_recv_cscov(&self, level: u32) -> io::Result<()> {
2930 unsafe {
2931 setsockopt(
2932 self.as_raw(),
2933 libc::SOL_DCCP,
2934 libc::DCCP_SOCKOPT_RECV_CSCOV,
2935 level,
2936 )
2937 }
2938 }
2939
2940 /// Get the value of the `DCCP_SOCKOPT_RECV_CSCOV` option on this socket.
2941 ///
2942 /// For more information on this option see [`set_dccp_recv_cscov`].
2943 ///
2944 /// [`set_dccp_recv_cscov`]: crate::Socket::set_dccp_recv_cscov
2945 #[cfg(all(feature = "all", target_os = "linux"))]
2946 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2947 pub fn dccp_recv_cscov(&self) -> io::Result<u32> {
2948 unsafe { getsockopt(self.as_raw(), libc::SOL_DCCP, libc::DCCP_SOCKOPT_RECV_CSCOV) }
2949 }
2950
2951 /// Set value for the `DCCP_SOCKOPT_QPOLICY_TXQLEN` option on this socket.
2952 ///
2953 /// This option sets the maximum length of the output queue. A zero value is
2954 /// interpreted as unbounded queue length.
2955 #[cfg(all(feature = "all", target_os = "linux"))]
2956 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2957 pub fn set_dccp_qpolicy_txqlen(&self, length: u32) -> io::Result<()> {
2958 unsafe {
2959 setsockopt(
2960 self.as_raw(),
2961 libc::SOL_DCCP,
2962 libc::DCCP_SOCKOPT_QPOLICY_TXQLEN,
2963 length,
2964 )
2965 }
2966 }
2967
2968 /// Get the value of the `DCCP_SOCKOPT_QPOLICY_TXQLEN` on this socket.
2969 ///
2970 /// For more information on this option see [`set_dccp_qpolicy_txqlen`].
2971 ///
2972 /// [`set_dccp_qpolicy_txqlen`]: crate::Socket::set_dccp_qpolicy_txqlen
2973 #[cfg(all(feature = "all", target_os = "linux"))]
2974 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2975 pub fn dccp_qpolicy_txqlen(&self) -> io::Result<u32> {
2976 unsafe {
2977 getsockopt(
2978 self.as_raw(),
2979 libc::SOL_DCCP,
2980 libc::DCCP_SOCKOPT_QPOLICY_TXQLEN,
2981 )
2982 }
2983 }
2984
2985 /// Get the value of the `DCCP_SOCKOPT_AVAILABLE_CCIDS` option on this socket.
2986 ///
2987 /// Returns the list of CCIDs supported by the endpoint.
2988 ///
2989 /// The parameter `N` is used to get the maximum number of supported
2990 /// endpoints. The [documentation] recommends a minimum of four at the time
2991 /// of writing.
2992 ///
2993 /// [documentation]: https://www.kernel.org/doc/html/latest/networking/dccp.html
2994 #[cfg(all(feature = "all", target_os = "linux"))]
2995 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
2996 pub fn dccp_available_ccids<const N: usize>(&self) -> io::Result<CcidEndpoints<N>> {
2997 let mut endpoints = [0; N];
2998 let mut length = endpoints.len() as libc::socklen_t;
2999 syscall!(getsockopt(
3000 self.as_raw(),
3001 libc::SOL_DCCP,
3002 libc::DCCP_SOCKOPT_AVAILABLE_CCIDS,
3003 endpoints.as_mut_ptr().cast(),
3004 &mut length,
3005 ))?;
3006 Ok(CcidEndpoints { endpoints, length })
3007 }
3008
3009 /// Get the value of the `DCCP_SOCKOPT_GET_CUR_MPS` option on this socket.
3010 ///
3011 /// This option retrieves the current maximum packet size (application
3012 /// payload size) in bytes.
3013 #[cfg(all(feature = "all", target_os = "linux"))]
3014 #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
3015 pub fn dccp_cur_mps(&self) -> io::Result<u32> {
3016 unsafe {
3017 getsockopt(
3018 self.as_raw(),
3019 libc::SOL_DCCP,
3020 libc::DCCP_SOCKOPT_GET_CUR_MPS,
3021 )
3022 }
3023 }
3024}
3025
3026/// See [`Socket::dccp_available_ccids`].
3027#[cfg(all(feature = "all", target_os = "linux"))]
3028#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
3029#[derive(Debug)]
3030pub struct CcidEndpoints<const N: usize> {
3031 endpoints: [u8; N],
3032 length: u32,
3033}
3034
3035#[cfg(all(feature = "all", target_os = "linux"))]
3036#[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))]
3037impl<const N: usize> std::ops::Deref for CcidEndpoints<N> {
3038 type Target = [u8];
3039
3040 fn deref(&self) -> &[u8] {
3041 &self.endpoints[0..self.length as usize]
3042 }
3043}
3044
3045#[cfg_attr(docsrs, doc(cfg(unix)))]
3046impl AsFd for crate::Socket {
3047 fn as_fd(&self) -> BorrowedFd<'_> {
3048 // SAFETY: lifetime is bound by self.
3049 unsafe { BorrowedFd::borrow_raw(self.as_raw()) }
3050 }
3051}
3052
3053#[cfg_attr(docsrs, doc(cfg(unix)))]
3054impl AsRawFd for crate::Socket {
3055 fn as_raw_fd(&self) -> c_int {
3056 self.as_raw()
3057 }
3058}
3059
3060#[cfg_attr(docsrs, doc(cfg(unix)))]
3061impl From<crate::Socket> for OwnedFd {
3062 fn from(sock: crate::Socket) -> OwnedFd {
3063 // SAFETY: sock.into_raw() always returns a valid fd.
3064 unsafe { OwnedFd::from_raw_fd(sock.into_raw()) }
3065 }
3066}
3067
3068#[cfg_attr(docsrs, doc(cfg(unix)))]
3069impl IntoRawFd for crate::Socket {
3070 fn into_raw_fd(self) -> c_int {
3071 self.into_raw()
3072 }
3073}
3074
3075#[cfg_attr(docsrs, doc(cfg(unix)))]
3076impl From<OwnedFd> for crate::Socket {
3077 fn from(fd: OwnedFd) -> crate::Socket {
3078 // SAFETY: `OwnedFd` ensures the fd is valid.
3079 unsafe { crate::Socket::from_raw_fd(fd.into_raw_fd()) }
3080 }
3081}
3082
3083#[cfg_attr(docsrs, doc(cfg(unix)))]
3084impl FromRawFd for crate::Socket {
3085 unsafe fn from_raw_fd(fd: c_int) -> crate::Socket {
3086 crate::Socket::from_raw(fd)
3087 }
3088}
3089
3090#[cfg(feature = "all")]
3091from!(UnixStream, crate::Socket);
3092#[cfg(feature = "all")]
3093from!(UnixListener, crate::Socket);
3094#[cfg(feature = "all")]
3095from!(UnixDatagram, crate::Socket);
3096#[cfg(feature = "all")]
3097from!(crate::Socket, UnixStream);
3098#[cfg(feature = "all")]
3099from!(crate::Socket, UnixListener);
3100#[cfg(feature = "all")]
3101from!(crate::Socket, UnixDatagram);
3102
3103#[test]
3104fn in_addr_convertion() {
3105 let ip: Ipv4Addr = Ipv4Addr::new(a:127, b:0, c:0, d:1);
3106 let raw: in_addr = to_in_addr(&ip);
3107 // NOTE: `in_addr` is packed on NetBSD and it's unsafe to borrow.
3108 let a: u32 = raw.s_addr;
3109 assert_eq!(a, u32::from_ne_bytes([127, 0, 0, 1]));
3110 assert_eq!(from_in_addr(raw), ip);
3111
3112 let ip: Ipv4Addr = Ipv4Addr::new(a:127, b:34, c:4, d:12);
3113 let raw: in_addr = to_in_addr(&ip);
3114 let a: u32 = raw.s_addr;
3115 assert_eq!(a, u32::from_ne_bytes([127, 34, 4, 12]));
3116 assert_eq!(from_in_addr(raw), ip);
3117}
3118
3119#[test]
3120fn in6_addr_convertion() {
3121 let ip: Ipv6Addr = Ipv6Addr::new(a:0x2000, b:1, c:2, d:3, e:4, f:5, g:6, h:7);
3122 let raw: in6_addr = to_in6_addr(&ip);
3123 let want: [u8; 16] = [32, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7];
3124 assert_eq!(raw.s6_addr, want);
3125 assert_eq!(from_in6_addr(raw), ip);
3126}
3127