Coverage Report

Created: 2026-06-30 06:40

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