Coverage Report

Created: 2025-08-29 06:13

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