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