Coverage Report

Created: 2026-08-14 06:10

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