oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! `net` on macOS: the BSD socket functions of `libSystem`.
//!
//! macOS has neither `SOCK_CLOEXEC` nor `accept4` nor `MSG_NOSIGNAL` (before
//! macOS 14): a new socket is made close-on-exec with `fcntl` and immune to
//! `SIGPIPE` with `SO_NOSIGPIPE`, right after it is created.
//!
//! Constants and layouts are those of `<sys/socket.h>`, `<netinet/in.h>`,
//! `<netinet6/in6.h>` and `<netinet/tcp.h>`.

use core::ffi::{c_int, c_void};
use core::mem::size_of;
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use core::time::Duration;

use crate::io::{IoSlice, IoSliceMut};
use crate::net::{Direction, Family, Opt, Protocol, RawAddr, RecvFlags, SendFlags, Shutdown, Type};
use crate::sys::{cvt, cvt_long};
use crate::{ErrorKind, Result};

pub(crate) type RawSocket = i32;

pub(crate) const AF_UNIX: u16 = 1;
pub(crate) const AF_INET: u16 = 2;
pub(crate) const AF_INET6: u16 = 30;
/// `sockaddr` starts with a length byte, then an 8-bit family.
pub(crate) const SOCKADDR_LEN_BYTE: bool = true;
/// The size of `sun_path`.
pub(crate) const UNIX_PATH_MAX: usize = 104;
pub(crate) const UNIX_ABSTRACT: bool = false;

const SOCK_STREAM: c_int = 1;
const SOCK_DGRAM: c_int = 2;
const SOCK_RAW: c_int = 3;
const SOCK_SEQPACKET: c_int = 5;

const MSG_OOB: c_int = 0x1;
const MSG_PEEK: c_int = 0x2;
const MSG_DONTROUTE: c_int = 0x4;
const MSG_TRUNC: c_int = 0x10;
const MSG_CTRUNC: c_int = 0x20;
const MSG_WAITALL: c_int = 0x40;
const MSG_DONTWAIT: c_int = 0x80;

const F_SETFD: c_int = 2;
const FD_CLOEXEC: c_int = 1;
const F_GETFL: c_int = 3;
const F_SETFL: c_int = 4;
const O_NONBLOCK: c_int = 0x4;
const FIONBIO: u64 = 0x8004667e;

const SOL_SOCKET: c_int = 0xffff;
/// The level of the Unix-domain options (`<sys/un.h>`).
const SOL_LOCAL: c_int = 0;
const LOCAL_PEERCRED: c_int = 0x001;
const LOCAL_PEERPID: c_int = 0x002;
const XUCRED_VERSION: u32 = 0;
const IPPROTO_IP: c_int = 0;
const IPPROTO_TCP: c_int = 6;
const IPPROTO_IPV6: c_int = 41;

const SO_REUSEADDR: c_int = 0x0004;
const SO_KEEPALIVE: c_int = 0x0008;
const SO_BROADCAST: c_int = 0x0020;
const SO_REUSEPORT: c_int = 0x0200;
const SO_SNDBUF: c_int = 0x1001;
const SO_RCVBUF: c_int = 0x1002;
const SO_SNDTIMEO: c_int = 0x1005;
const SO_RCVTIMEO: c_int = 0x1006;
const SO_ERROR: c_int = 0x1007;
const SO_TYPE: c_int = 0x1008;
const SO_NOSIGPIPE: c_int = 0x1022;
/// `SO_LINGER` counts in clock ticks on macOS; this one in seconds.
const SO_LINGER_SEC: c_int = 0x1080;

const TCP_NODELAY: c_int = 1;
/// The idle time before the first probe: Linux's `TCP_KEEPIDLE`.
const TCP_KEEPALIVE: c_int = 0x10;
const TCP_KEEPINTVL: c_int = 0x101;
const TCP_KEEPCNT: c_int = 0x102;
const IP_BOUND_IF: c_int = 25;
const IPV6_BOUND_IF: c_int = 125;
const IP_TTL: c_int = 4;
const IP_MULTICAST_TTL: c_int = 10;
const IP_MULTICAST_LOOP: c_int = 11;
const IP_ADD_MEMBERSHIP: c_int = 12;
const IP_DROP_MEMBERSHIP: c_int = 13;
const IPV6_UNICAST_HOPS: c_int = 4;
const IPV6_MULTICAST_HOPS: c_int = 10;
const IPV6_MULTICAST_LOOP: c_int = 11;
const IPV6_JOIN_GROUP: c_int = 12;
const IPV6_LEAVE_GROUP: c_int = 13;
const IPV6_V6ONLY: c_int = 27;

/// The longest buffer passed to one call: more than `INT_MAX` bytes is an
/// error for some of them.
const MAX_IO: usize = i32::MAX as usize;

// In a module of their own: several have the name of a function here. None
// needs a symbol variant on 64-bit targets (`$UNIX2003` is for 32-bit x86).
mod c {
    use core::ffi::{c_int, c_ulong, c_void};

    unsafe extern "C" {
        pub(super) fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
        pub(super) fn socketpair(
            domain: c_int,
            ty: c_int,
            protocol: c_int,
            fds: *mut c_int,
        ) -> c_int;
        pub(super) fn bind(socket: c_int, addr: *const u8, len: u32) -> c_int;
        pub(super) fn connect(socket: c_int, addr: *const u8, len: u32) -> c_int;
        pub(super) fn listen(socket: c_int, backlog: c_int) -> c_int;
        pub(super) fn accept(socket: c_int, addr: *mut u8, len: *mut u32) -> c_int;
        pub(super) fn sendto(
            socket: c_int,
            buf: *const u8,
            len: usize,
            flags: c_int,
            addr: *const u8,
            addr_len: u32,
        ) -> isize;
        pub(super) fn sendmsg(socket: c_int, msg: *const super::MsgHdr, flags: c_int) -> isize;
        pub(super) fn recvmsg(socket: c_int, msg: *mut super::MsgHdr, flags: c_int) -> isize;
        pub(super) fn shutdown(socket: c_int, how: c_int) -> c_int;
        pub(super) fn getsockname(socket: c_int, addr: *mut u8, len: *mut u32) -> c_int;
        pub(super) fn getpeername(socket: c_int, addr: *mut u8, len: *mut u32) -> c_int;
        pub(super) fn setsockopt(
            socket: c_int,
            level: c_int,
            name: c_int,
            value: *const c_void,
            len: u32,
        ) -> c_int;
        pub(super) fn getsockopt(
            socket: c_int,
            level: c_int,
            name: c_int,
            value: *mut c_void,
            len: *mut u32,
        ) -> c_int;
        // Variadic, and declared so: aarch64 passes variadic arguments on
        // the stack.
        pub(super) fn getifaddrs(list: *mut *mut super::IfAddrs) -> c_int;
        pub(super) fn freeifaddrs(list: *mut super::IfAddrs);
        pub(super) fn if_nametoindex(name: *const core::ffi::c_char) -> core::ffi::c_uint;
        pub(super) fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
        pub(super) fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
    }
}

/// # Safety
///
/// `socket` must be an open descriptor that nothing uses afterwards.
pub(crate) unsafe fn close(socket: RawSocket) {
    // SAFETY: the caller's contract is that of `sys::close`.
    unsafe { crate::sys::close(socket) }
}

/// Owns a descriptor until it is known to be fit to return.
struct Guard(RawSocket);

impl Guard {
    fn release(self) -> RawSocket {
        core::mem::ManuallyDrop::new(self).0
    }
}

impl Drop for Guard {
    fn drop(&mut self) {
        // SAFETY: the descriptor is open and owned by the guard.
        unsafe { close(self.0) };
    }
}

fn set_cloexec(socket: RawSocket) -> Result<()> {
    // SAFETY: F_SETFD takes an int.
    cvt(unsafe { c::fcntl(socket, F_SETFD, FD_CLOEXEC) })?;
    Ok(())
}

fn set_nosigpipe(socket: RawSocket) -> Result<()> {
    // SAFETY: SO_NOSIGPIPE is an int.
    unsafe { setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, &(1 as c_int)) }
}

fn family(family: Family) -> c_int {
    (match family {
        Family::Ipv4 => AF_INET,
        Family::Ipv6 => AF_INET6,
        Family::Unix => AF_UNIX,
    }) as c_int
}

fn socket_kind(ty: Type) -> c_int {
    match ty {
        Type::Stream => SOCK_STREAM,
        Type::Datagram => SOCK_DGRAM,
        Type::Raw => SOCK_RAW,
        Type::SeqPacket => SOCK_SEQPACKET,
    }
}

pub(crate) fn socket(domain: Family, ty: Type, protocol: Protocol) -> Result<RawSocket> {
    // SAFETY: socket takes three integers.
    let fd = cvt(unsafe { c::socket(family(domain), socket_kind(ty), protocol.number()) })?;
    let guard = Guard(fd);
    set_cloexec(fd)?;
    set_nosigpipe(fd)?;
    Ok(guard.release())
}

pub(crate) fn pair(ty: Type) -> Result<(RawSocket, RawSocket)> {
    let mut fds = [0 as c_int; 2];
    // SAFETY: socketpair writes two descriptors to `fds`.
    cvt(unsafe { c::socketpair(AF_UNIX as c_int, socket_kind(ty), 0, fds.as_mut_ptr()) })?;
    let (a, b) = (Guard(fds[0]), Guard(fds[1]));
    for fd in fds {
        set_cloexec(fd)?;
        set_nosigpipe(fd)?;
    }
    Ok((a.release(), b.release()))
}

pub(crate) fn bind(socket: RawSocket, addr: &RawAddr) -> Result<()> {
    // SAFETY: `addr` holds `len` initialized bytes.
    cvt(unsafe { c::bind(socket, addr.as_ptr(), addr.len()) })?;
    Ok(())
}

pub(crate) fn connect(socket: RawSocket, addr: &RawAddr) -> Result<()> {
    // SAFETY: `addr` holds `len` initialized bytes.
    cvt(unsafe { c::connect(socket, addr.as_ptr(), addr.len()) })?;
    Ok(())
}

pub(crate) fn listen(socket: RawSocket, backlog: i32) -> Result<()> {
    // SAFETY: listen takes two integers.
    cvt(unsafe { c::listen(socket, backlog) })?;
    Ok(())
}

pub(crate) fn accept(socket: RawSocket, addr: &mut RawAddr) -> Result<RawSocket> {
    let mut len = RawAddr::CAPACITY as u32;
    // SAFETY: the system writes at most `len` bytes to `addr`, and the
    // address's real length to `len`.
    let fd = cvt(unsafe { c::accept(socket, addr.as_mut_ptr(), &raw mut len) })?;
    let guard = Guard(fd);
    addr.set_len(len as usize);
    set_cloexec(fd)?;
    // The new socket inherits SO_NOSIGPIPE from a listener that has it, as
    // those oscall creates do. For the others it is set here, which the
    // system refuses (EINVAL) if the peer is already gone: nothing can be
    // done then, and the socket is still good for reading what was sent.
    let _ = set_nosigpipe(fd);
    // It also inherits the listener's non-blocking mode.
    // SAFETY: F_GETFL takes no argument.
    let flags = cvt(unsafe { c::fcntl(fd, F_GETFL) })?;
    if flags & O_NONBLOCK != 0 {
        // SAFETY: F_SETFL takes an int.
        cvt(unsafe { c::fcntl(fd, F_SETFL, flags & !O_NONBLOCK) })?;
    }
    Ok(guard.release())
}

fn send_flags(flags: SendFlags) -> c_int {
    let mut raw = 0;
    if flags.contains(SendFlags::OUT_OF_BAND) {
        raw |= MSG_OOB;
    }
    if flags.contains(SendFlags::DONT_ROUTE) {
        raw |= MSG_DONTROUTE;
    }
    if flags.contains(crate::net::unix::SEND_DONT_WAIT) {
        raw |= MSG_DONTWAIT;
    }
    raw
}

fn recv_flags(flags: RecvFlags) -> c_int {
    let mut raw = 0;
    if flags.contains(RecvFlags::PEEK) {
        raw |= MSG_PEEK;
    }
    if flags.contains(RecvFlags::OUT_OF_BAND) {
        raw |= MSG_OOB;
    }
    if flags.contains(RecvFlags::WAIT_ALL) {
        raw |= MSG_WAITALL;
    }
    if flags.contains(crate::net::unix::RECV_DONT_WAIT) {
        raw |= MSG_DONTWAIT;
    }
    raw
}

pub(crate) fn send(
    socket: RawSocket,
    buf: &[u8],
    flags: SendFlags,
    addr: Option<&RawAddr>,
) -> Result<usize> {
    let raw = send_flags(flags);
    let (to, to_len) = match addr {
        Some(addr) => (addr.as_ptr(), addr.len()),
        None => (core::ptr::null(), 0),
    };
    let len = buf.len().min(MAX_IO);
    // SAFETY: the system reads `len` bytes of `buf`, and `to_len` bytes at
    // `to` when it is not null.
    let n = unsafe { c::sendto(socket, buf.as_ptr(), len, raw, to, to_len) };
    Ok(cvt_long(n as i64)? as usize)
}

pub(crate) fn recv(
    socket: RawSocket,
    buf: &mut [u8],
    flags: RecvFlags,
    addr: Option<&mut RawAddr>,
) -> Result<usize> {
    let len = buf.len().min(MAX_IO);
    let mut bufs = [IoSliceMut::new(&mut buf[..len])];
    let (n, _) = recv_discarding(socket, &mut bufs, recv_flags(flags), addr)?;
    Ok(n)
}

/// `struct msghdr` (`<sys/socket.h>`): unlike Linux's, the number of
/// buffers is an `int` and the length of the control data a `socklen_t`.
#[repr(C)]
struct MsgHdr {
    name: *mut u8,
    name_len: u32,
    iov: *mut u8,
    iov_len: c_int,
    control: *mut u8,
    control_len: u32,
    flags: c_int,
}

/// `sendmsg`: the buffers of `iov`, to `addr` if there is one, with the
/// control messages `control` holds.
fn sendmsg(
    socket: RawSocket,
    bufs: &[IoSlice<'_>],
    flags: c_int,
    addr: Option<&RawAddr>,
    control: &[u8],
) -> Result<usize> {
    let (name, name_len) = match addr {
        Some(addr) => (addr.as_ptr().cast_mut(), addr.len()),
        None => (core::ptr::null_mut(), 0),
    };
    // macOS refuses a message with no buffer at all (EMSGSIZE), which is an
    // empty message elsewhere: give it one empty buffer.
    let empty = [IoSlice::new(&[])];
    let bufs = if bufs.is_empty() { &empty[..] } else { bufs };
    let msg = MsgHdr {
        name,
        name_len,
        // `IoSlice` is a transparent `iovec`.
        iov: bufs.as_ptr().cast_mut().cast(),
        iov_len: bufs.len().min(MAX_IO) as c_int,
        control: if control.is_empty() {
            core::ptr::null_mut()
        } else {
            control.as_ptr().cast_mut()
        },
        control_len: control.len() as u32,
        flags: 0,
    };
    // SAFETY: the system only reads what `msg` points to: the address, the
    // `iovec`s and the readable buffers they describe, the control data.
    let n = unsafe { c::sendmsg(socket, &raw const msg, flags) };
    Ok(cvt_long(n as i64)? as usize)
}

/// `recvmsg`. Returns the number of bytes received, the flags of the
/// message (`MSG_TRUNC`, `MSG_CTRUNC`) and the length of the control data
/// written to `control`.
fn recvmsg(
    socket: RawSocket,
    bufs: &mut [IoSliceMut<'_>],
    flags: c_int,
    addr: Option<&mut RawAddr>,
    control: &mut [u8],
) -> Result<(usize, c_int, usize)> {
    let (control, control_len) = if control.is_empty() {
        (core::ptr::null_mut(), 0)
    } else {
        (control.as_mut_ptr(), control.len().min(MAX_IO))
    };
    let mut addr = addr;
    let (name, name_len) = match addr.as_deref_mut() {
        Some(addr) => (addr.as_mut_ptr(), RawAddr::CAPACITY as u32),
        None => (core::ptr::null_mut(), 0),
    };
    // As in `sendmsg`: no buffer at all is one empty buffer.
    let mut empty = [IoSliceMut::new(&mut [])];
    let (iov, iov_len) = if bufs.is_empty() {
        (empty.as_mut_ptr().cast(), 1)
    } else {
        (bufs.as_mut_ptr().cast(), bufs.len().min(MAX_IO) as c_int)
    };
    let mut msg = MsgHdr {
        name,
        name_len,
        // `IoSliceMut` is a transparent `iovec`.
        iov,
        iov_len,
        control,
        control_len: control_len as u32,
        flags: 0,
    };
    // SAFETY: the system writes to the writable buffers the `iovec`s
    // describe, at most `name_len` bytes to the address (which `addr`
    // borrows mutably) and `control_len` to `control`, and updates `msg`.
    let n = unsafe { c::recvmsg(socket, &raw mut msg, flags) };
    let n = cvt_long(n as i64)? as usize;
    if let Some(addr) = addr {
        addr.set_len(msg.name_len as usize);
    }
    Ok((n, msg.flags, (msg.control_len as usize).min(control_len)))
}

pub(crate) fn send_vectored(
    socket: RawSocket,
    bufs: &[IoSlice<'_>],
    flags: SendFlags,
    addr: Option<&RawAddr>,
) -> Result<usize> {
    sendmsg(socket, bufs, send_flags(flags), addr, &[])
}

pub(crate) fn recv_vectored(
    socket: RawSocket,
    bufs: &mut [IoSliceMut<'_>],
    flags: RecvFlags,
    addr: Option<&mut RawAddr>,
) -> Result<(usize, bool)> {
    let (n, flags) = recv_discarding(socket, bufs, recv_flags(flags), addr)?;
    Ok((n, flags & MSG_TRUNC != 0))
}

/// Room for the control data of any message a Unix-domain socket delivers:
/// the system cannot queue a control message longer than this
/// (`MCLBYTES`).
const CONTROL_SIZE: usize = 2048;

/// Control data: `cmsghdr`s, aligned as the system wants them.
#[repr(C, align(4))]
struct Control([u8; CONTROL_SIZE]);

/// Receives for a caller that asked for no handles, and closes those that
/// come all the same. Returns the number of bytes and the message's flags.
///
/// When a message carries descriptors (`SCM_RIGHTS`), macOS creates them in
/// the receiving process before it looks at whether the caller gave room
/// for their numbers, or any room at all: a plain `recvfrom` would leave
/// them open, out of reach, as many as the peer cares to send. So every
/// receive takes the control data, and closes what it did not ask for.
fn recv_discarding(
    socket: RawSocket,
    bufs: &mut [IoSliceMut<'_>],
    flags: c_int,
    addr: Option<&mut RawAddr>,
) -> Result<(usize, c_int)> {
    // Peeking creates no descriptor (the control data it reports has zeros
    // in their place): there is nothing to take.
    if flags & MSG_PEEK != 0 {
        let (n, flags, _) = recvmsg(socket, bufs, flags, addr, &mut [])?;
        return Ok((n, flags));
    }
    let mut control = Control([0; CONTROL_SIZE]);
    let (n, flags, len) = recvmsg(socket, bufs, flags, addr, &mut control.0)?;
    close_rights(&control.0[..len]);
    Ok((n, flags))
}

/// Closes the descriptors that control data just received carries.
fn close_rights(control: &[u8]) {
    /// `sizeof(struct cmsghdr)`: a `socklen_t` and two `int`s.
    const HEADER: usize = 12;
    let int_at = |bytes: &[u8], at: usize| {
        i32::from_ne_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]])
    };
    let mut at = 0;
    while control.len() - at >= HEADER {
        let message = &control[at..];
        let len = int_at(message, 0) as u32 as usize;
        if len < HEADER {
            break;
        }
        if int_at(message, 4) == SOL_SOCKET && int_at(message, 8) == SCM_RIGHTS {
            for fd in message[HEADER..len.min(message.len())].as_chunks::<4>().0 {
                let fd = i32::from_ne_bytes(*fd);
                if fd >= 0 {
                    // SAFETY: the system just created this descriptor for
                    // the process, and nothing else knows of it.
                    unsafe { close(fd) };
                }
            }
        }
        // Messages are aligned to four bytes (`__DARWIN_ALIGN32`).
        at = match at.checked_add(len.next_multiple_of(4)) {
            Some(next) if next <= control.len() => next,
            _ => break,
        };
    }
}

/// The size of `cmsg_len` in `struct cmsghdr`, a `socklen_t`, which is also
/// what control messages are aligned to (`__DARWIN_ALIGN32`), on 64-bit
/// targets too. Two `int`s follow it: the level and the type.
pub(crate) const CMSG_LEN_BYTES: usize = 4;
pub(crate) const CMSG_SOL_SOCKET: i32 = SOL_SOCKET;
pub(crate) const SCM_RIGHTS: i32 = 1;

pub(crate) fn send_control(
    socket: RawSocket,
    bufs: &[IoSlice<'_>],
    flags: SendFlags,
    control: &[u8],
) -> Result<usize> {
    sendmsg(socket, bufs, send_flags(flags), None, control)
}

/// Receives with control data. Returns the number of bytes received,
/// whether the data and the control data were truncated, and the length of
/// the control data.
pub(crate) fn recv_control(
    socket: RawSocket,
    bufs: &mut [IoSliceMut<'_>],
    flags: RecvFlags,
    control: &mut [u8],
) -> Result<(usize, bool, bool, usize)> {
    let (n, flags, len) = recvmsg(socket, bufs, recv_flags(flags), None, control)?;
    Ok((n, flags & MSG_TRUNC != 0, flags & MSG_CTRUNC != 0, len))
}

/// Makes a descriptor that `recv_control` received private to the process:
/// macOS has no `MSG_CMSG_CLOEXEC`.
pub(crate) fn received_handle(fd: i32) -> Result<()> {
    set_cloexec(fd)
}

/// `struct xucred` (`<sys/ucred.h>`), 76 bytes.
#[repr(C)]
struct Xucred {
    version: u32,
    uid: u32,
    ngroups: i16,
    pad: i16,
    groups: [u32; 16],
}

/// The user, the group and the process of the peer.
pub(crate) fn peer_cred(socket: RawSocket) -> Result<(u32, u32, Option<u32>)> {
    let mut cred = Xucred {
        version: 0,
        uid: 0,
        ngroups: 0,
        pad: 0,
        groups: [0; 16],
    };
    let mut len = size_of::<Xucred>() as u32;
    let ptr = (&raw mut cred).cast::<c_void>();
    // SAFETY: the system writes at most `len` bytes at `cred`, plain data.
    cvt(unsafe { c::getsockopt(socket, SOL_LOCAL, LOCAL_PEERCRED, ptr, &raw mut len) })?;
    // `SOL_LOCAL` is 0, which is `IPPROTO_IP` to an Internet socket: what
    // is not an `xucred` of the one version there is, is not credentials.
    if len as usize != size_of::<Xucred>() || cred.version != XUCRED_VERSION || cred.ngroups < 1 {
        return Err(ErrorKind::InvalidInput.into());
    }
    // The process is another option, which the socket of a peer that is
    // gone may not answer.
    // SAFETY: LOCAL_PEERPID yields a `pid_t`.
    let pid = unsafe { getsockopt(socket, SOL_LOCAL, LOCAL_PEERPID, 0 as c_int) };
    let pid = pid.ok().filter(|&pid| pid > 0).map(|pid| pid as u32);
    // The first group is the effective one, as `getpeereid` has it.
    Ok((cred.uid, cred.groups[0], pid))
}

pub(crate) fn shutdown(socket: RawSocket, how: Shutdown) -> Result<()> {
    const SHUT_RD: c_int = 0;
    const SHUT_WR: c_int = 1;
    const SHUT_RDWR: c_int = 2;
    let raw = match how {
        Shutdown::Read => SHUT_RD,
        Shutdown::Write => SHUT_WR,
        Shutdown::Both => SHUT_RDWR,
    };
    // SAFETY: shutdown takes two integers.
    let Err(err) = cvt(unsafe { c::shutdown(socket, raw) }) else {
        return Ok(());
    };
    // Once the peer has closed its side, macOS answers ENOTCONN to a request
    // that includes the read half, and does nothing: not even shutting down
    // the write half. Other systems take the read half as closed already.
    if err.raw_os_error() != crate::sys::errno::ENOTCONN {
        return Err(err);
    }
    match how {
        Shutdown::Write => Err(err),
        // The write half is still to do, and tells whether the socket is
        // connected at all.
        Shutdown::Both => {
            // SAFETY: as above.
            cvt(unsafe { c::shutdown(socket, SHUT_WR) })?;
            Ok(())
        }
        // Nothing is left to do if the socket is connected, which having a
        // peer tells.
        Shutdown::Read => {
            let mut addr = RawAddr::new();
            peer_addr(socket, &mut addr).map_err(|_| err)
        }
    }
}

pub(crate) fn local_addr(socket: RawSocket, addr: &mut RawAddr) -> Result<()> {
    let mut len = RawAddr::CAPACITY as u32;
    // SAFETY: the system writes at most `len` bytes to `addr`.
    cvt(unsafe { c::getsockname(socket, addr.as_mut_ptr(), &raw mut len) })?;
    addr.set_len(len as usize);
    Ok(())
}

pub(crate) fn peer_addr(socket: RawSocket, addr: &mut RawAddr) -> Result<()> {
    let mut len = RawAddr::CAPACITY as u32;
    // SAFETY: the system writes at most `len` bytes to `addr`.
    cvt(unsafe { c::getpeername(socket, addr.as_mut_ptr(), &raw mut len) }).map_err(|err| {
        // A socket whose connection failed or was torn down gets EINVAL
        // ("the socket has been shut down") where the other systems, and
        // macOS before any connection, say that it is not connected.
        if err.raw_os_error() == crate::sys::errno::EINVAL {
            crate::Error::from_raw_os_error(crate::sys::errno::ENOTCONN)
        } else {
            err
        }
    })?;
    addr.set_len(len as usize);
    Ok(())
}

pub(crate) fn set_nonblocking(socket: RawSocket, nonblocking: bool) -> Result<()> {
    let mut value = nonblocking as c_int;
    // SAFETY: FIONBIO reads an int through the pointer.
    cvt(unsafe { c::ioctl(socket, FIONBIO, &raw mut value) })?;
    Ok(())
}

/// Sets an option whose value is a `T`.
///
/// # Safety
///
/// `T` must be the type the option takes.
unsafe fn setsockopt<T>(socket: RawSocket, level: c_int, name: c_int, value: &T) -> Result<()> {
    let ptr = (value as *const T).cast::<c_void>();
    // SAFETY: the system reads `size_of::<T>()` bytes at `value`.
    cvt(unsafe { c::setsockopt(socket, level, name, ptr, size_of::<T>() as u32) })?;
    Ok(())
}

/// Reads an option whose value is a `T`, over the initial `value`.
///
/// # Safety
///
/// `T` must be the type the option yields, valid for any bit pattern.
unsafe fn getsockopt<T>(socket: RawSocket, level: c_int, name: c_int, mut value: T) -> Result<T> {
    let mut len = size_of::<T>() as u32;
    let ptr = (&raw mut value).cast::<c_void>();
    // SAFETY: the system writes at most `len` bytes at `value`.
    cvt(unsafe { c::getsockopt(socket, level, name, ptr, &raw mut len) })?;
    Ok(value)
}

/// The level and name of an integer option.
fn option(opt: Opt) -> (c_int, c_int) {
    match opt {
        Opt::ReuseAddr => (SOL_SOCKET, SO_REUSEADDR),
        Opt::KeepAlive => (SOL_SOCKET, SO_KEEPALIVE),
        Opt::Broadcast => (SOL_SOCKET, SO_BROADCAST),
        Opt::SendBuffer => (SOL_SOCKET, SO_SNDBUF),
        Opt::RecvBuffer => (SOL_SOCKET, SO_RCVBUF),
        Opt::Error => (SOL_SOCKET, SO_ERROR),
        Opt::NoDelay => (IPPROTO_TCP, TCP_NODELAY),
        Opt::KeepAliveIdle => (IPPROTO_TCP, TCP_KEEPALIVE),
        Opt::KeepAliveInterval => (IPPROTO_TCP, TCP_KEEPINTVL),
        Opt::KeepAliveCount => (IPPROTO_TCP, TCP_KEEPCNT),
        Opt::Ttl => (IPPROTO_IP, IP_TTL),
        // The two IPv4 multicast options were a `u_char` in BSD; macOS takes
        // and returns an int as well.
        Opt::MulticastTtlV4 => (IPPROTO_IP, IP_MULTICAST_TTL),
        Opt::MulticastLoopV4 => (IPPROTO_IP, IP_MULTICAST_LOOP),
        Opt::HopLimit => (IPPROTO_IPV6, IPV6_UNICAST_HOPS),
        Opt::MulticastHopsV6 => (IPPROTO_IPV6, IPV6_MULTICAST_HOPS),
        Opt::MulticastLoopV6 => (IPPROTO_IPV6, IPV6_MULTICAST_LOOP),
        Opt::OnlyV6 => (IPPROTO_IPV6, IPV6_V6ONLY),
    }
}

pub(crate) fn set_opt(socket: RawSocket, opt: Opt, value: i32) -> Result<()> {
    let (level, name) = option(opt);
    // SAFETY: these options are an int.
    unsafe { setsockopt(socket, level, name, &value) }
}

pub(crate) fn get_opt(socket: RawSocket, opt: Opt) -> Result<i32> {
    let (level, name) = option(opt);
    // SAFETY: these options are an int.
    unsafe { getsockopt(socket, level, name, 0 as c_int) }
}

/// The integer options of the extension modules.
#[derive(Clone, Copy)]
pub(crate) enum ExtOpt {
    ReusePort,
}

fn ext_option(opt: ExtOpt) -> (c_int, c_int) {
    match opt {
        ExtOpt::ReusePort => (SOL_SOCKET, SO_REUSEPORT),
    }
}

pub(crate) fn set_ext_opt(socket: RawSocket, opt: ExtOpt, value: i32) -> Result<()> {
    let (level, name) = ext_option(opt);
    // SAFETY: these options are an int.
    unsafe { setsockopt(socket, level, name, &value) }
}

pub(crate) fn get_ext_opt(socket: RawSocket, opt: ExtOpt) -> Result<i32> {
    let (level, name) = ext_option(opt);
    // SAFETY: these options are an int.
    unsafe { getsockopt(socket, level, name, 0 as c_int) }
}

/// The level and name of the option that binds a socket to an interface:
/// there is one for each of the two Internet families.
fn bound_if_option(socket: RawSocket) -> Result<(c_int, c_int)> {
    let mut addr = RawAddr::new();
    local_addr(socket, &mut addr)?;
    match addr.family() {
        AF_INET => Ok((IPPROTO_IP, IP_BOUND_IF)),
        AF_INET6 => Ok((IPPROTO_IPV6, IPV6_BOUND_IF)),
        _ => Err(ErrorKind::InvalidInput.into()),
    }
}

pub(crate) fn bind_interface(socket: RawSocket, index: u32) -> Result<()> {
    let (level, name) = bound_if_option(socket)?;
    // SAFETY: the two options are an unsigned int.
    unsafe { setsockopt(socket, level, name, &index) }
}

pub(crate) fn bound_interface(socket: RawSocket) -> Result<u32> {
    let (level, name) = bound_if_option(socket)?;
    // SAFETY: the two options are an unsigned int.
    unsafe { getsockopt(socket, level, name, 0u32) }
}

pub(crate) fn socket_type(socket: RawSocket) -> Result<Type> {
    // SAFETY: SO_TYPE is an int.
    match unsafe { getsockopt(socket, SOL_SOCKET, SO_TYPE, 0 as c_int) }? {
        SOCK_STREAM => Ok(Type::Stream),
        SOCK_DGRAM => Ok(Type::Datagram),
        SOCK_RAW => Ok(Type::Raw),
        SOCK_SEQPACKET => Ok(Type::SeqPacket),
        _ => Err(ErrorKind::Unsupported.into()),
    }
}

/// `struct linger`.
#[repr(C)]
struct Linger {
    onoff: c_int,
    seconds: c_int,
}

pub(crate) fn set_linger(socket: RawSocket, seconds: Option<u32>) -> Result<()> {
    let value = Linger {
        onoff: seconds.is_some() as c_int,
        seconds: seconds.unwrap_or(0).min(i32::MAX as u32) as c_int,
    };
    // SAFETY: SO_LINGER_SEC takes a `struct linger`.
    unsafe { setsockopt(socket, SOL_SOCKET, SO_LINGER_SEC, &value) }
}

pub(crate) fn linger(socket: RawSocket) -> Result<Option<u32>> {
    let value = Linger {
        onoff: 0,
        seconds: 0,
    };
    // SAFETY: SO_LINGER_SEC yields a `struct linger`.
    let value = unsafe { getsockopt(socket, SOL_SOCKET, SO_LINGER_SEC, value) }?;
    Ok((value.onoff != 0).then_some(value.seconds.max(0) as u32))
}

/// `struct timeval`: a 64-bit `time_t` and a 32-bit `suseconds_t` (the
/// padding after it is spelled out so that no byte is left uninitialized).
#[repr(C)]
struct Timeval {
    sec: i64,
    usec: i32,
    pad: i32,
}

fn timeout_name(direction: Direction) -> c_int {
    match direction {
        Direction::Send => SO_SNDTIMEO,
        Direction::Recv => SO_RCVTIMEO,
    }
}

pub(crate) fn set_timeout(
    socket: RawSocket,
    direction: Direction,
    timeout: Option<Duration>,
) -> Result<()> {
    let (sec, usec) = match timeout {
        None => (0, 0),
        Some(time) => {
            let sec = time.as_secs().min(i64::MAX as u64) as i64;
            // Rounded up to the microsecond: zero would mean no timeout.
            let usec = time.subsec_nanos().div_ceil(1000) as i32;
            if usec == 1_000_000 {
                (sec.saturating_add(1), 0)
            } else {
                (sec, usec)
            }
        }
    };
    let value = Timeval { sec, usec, pad: 0 };
    // SAFETY: the option takes a `struct timeval`.
    unsafe { setsockopt(socket, SOL_SOCKET, timeout_name(direction), &value) }
}

pub(crate) fn timeout(socket: RawSocket, direction: Direction) -> Result<Option<Duration>> {
    let value = Timeval {
        sec: 0,
        usec: 0,
        pad: 0,
    };
    // SAFETY: the option yields a `struct timeval`.
    let value = unsafe { getsockopt(socket, SOL_SOCKET, timeout_name(direction), value) }?;
    if value.sec <= 0 && value.usec <= 0 {
        return Ok(None);
    }
    let micros = value.usec.clamp(0, 999_999) as u32;
    Ok(Some(Duration::new(value.sec.max(0) as u64, micros * 1000)))
}

pub(crate) fn membership_v4(
    socket: RawSocket,
    join: bool,
    group: [u8; 4],
    interface: [u8; 4],
) -> Result<()> {
    // `struct ip_mreq`: the group, then the address of the interface.
    let value = [group, interface];
    let name = if join {
        IP_ADD_MEMBERSHIP
    } else {
        IP_DROP_MEMBERSHIP
    };
    // SAFETY: the option takes a `struct ip_mreq`.
    unsafe { setsockopt(socket, IPPROTO_IP, name, &value) }
}

/// `struct ipv6_mreq`.
#[repr(C)]
struct Ipv6Mreq {
    group: [u8; 16],
    interface: u32,
}

pub(crate) fn membership_v6(
    socket: RawSocket,
    join: bool,
    group: [u8; 16],
    interface: u32,
) -> Result<()> {
    let value = Ipv6Mreq { group, interface };
    let name = if join {
        IPV6_JOIN_GROUP
    } else {
        IPV6_LEAVE_GROUP
    };
    // SAFETY: the option takes a `struct ipv6_mreq`.
    unsafe { setsockopt(socket, IPPROTO_IPV6, name, &value) }
}

const AF_LINK: u8 = 18;
const IFF_UP: u32 = 0x1;
const IFF_LOOPBACK: u32 = 0x8;

/// `struct ifaddrs` (`<ifaddrs.h>`): one address of one interface.
#[repr(C)]
struct IfAddrs {
    next: *mut IfAddrs,
    name: *const core::ffi::c_char,
    flags: u32,
    addr: *const u8,
    netmask: *const u8,
    dstaddr: *const u8,
    data: *mut c_void,
}

/// The list `getifaddrs` allocated, freed when dropped.
struct IfList(*mut IfAddrs);

impl Drop for IfList {
    fn drop(&mut self) {
        // SAFETY: the list came from `getifaddrs` and is freed once.
        unsafe { c::freeifaddrs(self.0) };
    }
}

/// The bytes of a `sockaddr` of the list, as long as it says it is (its
/// first byte): the system cuts the netmasks short.
///
/// # Safety
///
/// `addr` must be null or point to a `sockaddr` that lives as long as the
/// list.
unsafe fn sockaddr_bytes<'a>(addr: *const u8) -> &'a [u8] {
    if addr.is_null() {
        return &[];
    }
    // SAFETY: a `sockaddr` starts with its own length, and is that long.
    unsafe { core::slice::from_raw_parts(addr, *addr as usize) }
}

/// What `if_addrs` calls with each entry: its name, its flags, its address
/// and its netmask.
type EntryVisitor<'a> = dyn FnMut(&core::ffi::CStr, u32, &[u8], &[u8]) + 'a;

/// Calls `each` with every entry of the system's list (`getifaddrs`).
fn if_addrs(each: &mut EntryVisitor<'_>) -> Result<()> {
    let mut list = core::ptr::null_mut();
    // SAFETY: getifaddrs writes the head of a list it allocates.
    cvt(unsafe { c::getifaddrs(&raw mut list) })?;
    let list = IfList(list);
    let mut entry = list.0.cast_const();
    while !entry.is_null() {
        // SAFETY: the entries are valid until the list is freed, which the
        // guard does after the loop, or when `each` unwinds.
        let (name, flags, addr, netmask, next) = unsafe {
            let entry = &*entry;
            (
                core::ffi::CStr::from_ptr(entry.name),
                entry.flags,
                sockaddr_bytes(entry.addr),
                sockaddr_bytes(entry.netmask),
                entry.next.cast_const(),
            )
        };
        each(name, flags, addr, netmask);
        entry = next;
    }
    Ok(())
}

pub(crate) fn interfaces(f: &mut crate::net::InterfaceVisitor<'_>) -> Result<()> {
    if_addrs(&mut |name, flags, addr, _| {
        // Every interface has one link-level entry, a `sockaddr_dl`: its
        // length, its family and, in 16 bits, the index.
        if addr.len() >= 4 && addr[1] == AF_LINK {
            let index = u16::from_ne_bytes([addr[2], addr[3]]) as u32;
            f(
                index,
                name.to_bytes(),
                flags & IFF_UP != 0,
                flags & IFF_LOOPBACK != 0,
            );
        }
    })
}

/// The length of the prefix a netmask stands for: its leading one bits.
/// The bytes the system cut off are zeros.
fn prefix_len(mask: &[u8]) -> u8 {
    let mut len = 0;
    for &byte in mask {
        len += byte.leading_ones() as u8;
        if byte != 0xff {
            break;
        }
    }
    len
}

pub(crate) fn interface_addrs(f: &mut crate::net::AddrVisitor<'_>) -> Result<()> {
    if_addrs(&mut |name, _, addr, mask| {
        if addr.len() < 2 {
            return;
        }
        // `sockaddr_in` has its address at 4, `sockaddr_in6` at 8.
        let (ip, prefix) = if addr[1] as u16 == AF_INET && addr.len() >= 8 {
            let ip = Ipv4Addr::new(addr[4], addr[5], addr[6], addr[7]);
            let mask = mask.get(4..mask.len().min(8)).unwrap_or(&[]);
            (IpAddr::V4(ip), prefix_len(mask))
        } else if addr[1] as u16 == AF_INET6 && addr.len() >= 24 {
            let mut ip = [0; 16];
            ip.copy_from_slice(&addr[8..24]);
            // The kernel keeps the index of the interface in the second
            // word of a link-local address, and has let it show here: the
            // address itself has zeros there.
            if ip[0] == 0xfe && ip[1] & 0xc0 == 0x80 {
                ip[2] = 0;
                ip[3] = 0;
            }
            let mask = mask.get(8..mask.len().min(24)).unwrap_or(&[]);
            (IpAddr::V6(Ipv6Addr::from(ip)), prefix_len(mask))
        } else {
            return;
        };
        // SAFETY: `name` is a C string.
        let index = unsafe { c::if_nametoindex(name.as_ptr()) };
        // 0: the interface went away since the list was made.
        if index != 0 {
            f(index, ip, prefix);
        }
    })
}