oscall 0.1.1

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
//! `net` on Linux and fullrust: the socket system calls, made directly on
//! every architecture (32-bit x86 has had them next to `socketcall` since
//! Linux 4.3).
//!
//! Constants are those of `include/uapi/asm-generic/socket.h`,
//! `linux/in.h`, `linux/in6.h` and `linux/tcp.h`, which every architecture
//! oscall supports shares.

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::syscall;
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 = 10;
/// `sockaddr` starts with a 16-bit family.
pub(crate) const SOCKADDR_LEN_BYTE: bool = false;
/// The size of `sun_path`.
pub(crate) const UNIX_PATH_MAX: usize = 108;
pub(crate) const UNIX_ABSTRACT: bool = true;

const SOCK_STREAM: i32 = 1;
const SOCK_DGRAM: i32 = 2;
const SOCK_RAW: i32 = 3;
const SOCK_SEQPACKET: i32 = 5;
/// `O_CLOEXEC`, which has this value on every supported architecture.
pub(crate) const SOCK_CLOEXEC: i32 = 0o2000000;

const MSG_OOB: i32 = 1;
const MSG_PEEK: i32 = 2;
const MSG_DONTROUTE: i32 = 4;
const MSG_CTRUNC: i32 = 8;
const MSG_TRUNC: i32 = 0x20;
const MSG_DONTWAIT: i32 = 0x40;
const MSG_WAITALL: i32 = 0x100;
const MSG_NOSIGNAL: i32 = 0x4000;
const MSG_CMSG_CLOEXEC: i32 = 0x40000000;

const FIONBIO: u32 = 0x5421;

const SOL_SOCKET: i32 = 1;
const IPPROTO_IP: i32 = 0;
const IPPROTO_TCP: i32 = 6;
const IPPROTO_IPV6: i32 = 41;

const SO_REUSEADDR: i32 = 2;
const SO_TYPE: i32 = 3;
const SO_ERROR: i32 = 4;
const SO_BROADCAST: i32 = 6;
const SO_SNDBUF: i32 = 7;
const SO_RCVBUF: i32 = 8;
const SO_KEEPALIVE: i32 = 9;
const SO_LINGER: i32 = 13;
const SO_REUSEPORT: i32 = 15;
const SO_PEERCRED: i32 = 17;
// The timeouts are a `timeval` of two longs under the old names, and of two
// 64-bit integers under the new ones: the same thing on 64-bit targets,
// where the old names are the ones every kernel and emulator knows.
#[cfg(target_pointer_width = "64")]
const SO_RCVTIMEO: i32 = 20; // SO_RCVTIMEO_OLD
#[cfg(target_pointer_width = "64")]
const SO_SNDTIMEO: i32 = 21; // SO_SNDTIMEO_OLD
#[cfg(target_pointer_width = "32")]
const SO_RCVTIMEO: i32 = 66; // SO_RCVTIMEO_NEW
#[cfg(target_pointer_width = "32")]
const SO_SNDTIMEO: i32 = 67; // SO_SNDTIMEO_NEW

const SO_BINDTOIFINDEX: i32 = 62;

const TCP_NODELAY: i32 = 1;
const TCP_CORK: i32 = 3;
const TCP_KEEPIDLE: i32 = 4;
const TCP_KEEPINTVL: i32 = 5;
const TCP_KEEPCNT: i32 = 6;
const TCP_QUICKACK: i32 = 12;
const TCP_FASTOPEN: i32 = 23;
const IP_TTL: i32 = 2;
const IP_MULTICAST_TTL: i32 = 33;
const IP_MULTICAST_LOOP: i32 = 34;
const IP_ADD_MEMBERSHIP: i32 = 35;
const IP_DROP_MEMBERSHIP: i32 = 36;
const IPV6_UNICAST_HOPS: i32 = 16;
const IPV6_MULTICAST_HOPS: i32 = 18;
const IPV6_MULTICAST_LOOP: i32 = 19;
const IPV6_ADD_MEMBERSHIP: i32 = 20;
const IPV6_DROP_MEMBERSHIP: i32 = 21;
const IPV6_V6ONLY: i32 = 26;

/// # 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) }
}

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

pub(crate) fn socket_kind(ty: Type) -> i32 {
    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> {
    let ty = socket_kind(ty) | SOCK_CLOEXEC;
    // SAFETY: socket takes three integers.
    let fd = unsafe { syscall!(SOCKET, family(domain), ty, protocol.number()) }?;
    Ok(fd as RawSocket)
}

pub(crate) fn pair(ty: Type) -> Result<(RawSocket, RawSocket)> {
    let mut fds = [0i32; 2];
    let ty = socket_kind(ty) | SOCK_CLOEXEC;
    // SAFETY: socketpair writes two descriptors to `fds`.
    unsafe { syscall!(SOCKETPAIR, AF_UNIX, ty, 0, fds.as_mut_ptr()) }?;
    Ok((fds[0], fds[1]))
}

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

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

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

pub(crate) fn accept(socket: RawSocket, addr: &mut RawAddr) -> Result<RawSocket> {
    let mut len = RawAddr::CAPACITY as u32;
    // SAFETY: the kernel writes at most `len` bytes to `addr`, and the
    // address's real length to `len`. The new socket is always blocking.
    let fd = unsafe {
        syscall!(
            ACCEPT4,
            socket,
            addr.as_mut_ptr(),
            &raw mut len,
            SOCK_CLOEXEC
        )
    }?;
    addr.set_len(len as usize);
    Ok(fd as RawSocket)
}

pub(crate) fn send_flags(flags: SendFlags) -> i32 {
    let mut raw = MSG_NOSIGNAL;
    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
}

pub(crate) fn recv_flags(flags: RecvFlags) -> i32 {
    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),
    };
    // SAFETY: the kernel reads `buf`, and `to_len` bytes at `to` when it is
    // not null. There is no `send` system call on most architectures: it is
    // `sendto` with no address.
    unsafe { syscall!(SENDTO, socket, buf.as_ptr(), buf.len(), raw, to, to_len) }
}

pub(crate) fn recv(
    socket: RawSocket,
    buf: &mut [u8],
    flags: RecvFlags,
    addr: Option<&mut RawAddr>,
) -> Result<usize> {
    let raw = recv_flags(flags);
    let (ptr, len) = (buf.as_mut_ptr(), buf.len());
    match addr {
        Some(addr) => {
            let mut addr_len = RawAddr::CAPACITY as u32;
            let from = addr.as_mut_ptr();
            // SAFETY: the kernel writes at most `len` bytes to `buf`, at
            // most `addr_len` to `addr`, and the address's length.
            let n = unsafe { syscall!(RECVFROM, socket, ptr, len, raw, from, &raw mut addr_len) }?;
            addr.set_len(addr_len as usize);
            Ok(n)
        }
        // SAFETY: the kernel writes at most `len` bytes to `buf`.
        None => unsafe { syscall!(RECVFROM, socket, ptr, len, raw, 0, 0) },
    }
}

/// `struct user_msghdr` (`include/linux/socket.h`): pointers and `size_t`
/// lengths, apart from the length of the address, which is an `int`. The
/// same declaration is right for 32-bit and 64-bit targets.
#[repr(C)]
struct MsgHdr {
    name: *mut u8,
    name_len: i32,
    iov: *mut u8,
    iov_len: usize,
    control: *mut u8,
    control_len: usize,
    flags: u32,
}

/// `sendmsg`: the buffers of `iov`, to `addr` if there is one, with the
/// control messages `control` holds.
fn sendmsg(
    socket: RawSocket,
    bufs: &[IoSlice<'_>],
    flags: i32,
    addr: Option<&RawAddr>,
    control: &[u8],
) -> Result<usize> {
    let (name, name_len) = match addr {
        Some(addr) => (addr.as_ptr().cast_mut(), addr.len() as i32),
        None => (core::ptr::null_mut(), 0),
    };
    let msg = MsgHdr {
        name,
        name_len,
        // `IoSlice` is a transparent `iovec`.
        iov: bufs.as_ptr().cast_mut().cast(),
        iov_len: bufs.len(),
        control: if control.is_empty() {
            core::ptr::null_mut()
        } else {
            control.as_ptr().cast_mut()
        },
        control_len: control.len(),
        flags: 0,
    };
    // SAFETY: the kernel only reads what `msg` points to: the address, the
    // `iovec`s and the readable buffers they describe, the control data.
    unsafe { syscall!(SENDMSG, socket, &raw const msg, flags) }
}

/// `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: i32,
    addr: Option<&mut RawAddr>,
    control: &mut [u8],
) -> Result<(usize, i32, usize)> {
    let (control, control_len) = if control.is_empty() {
        (core::ptr::null_mut(), 0)
    } else {
        (control.as_mut_ptr(), control.len())
    };
    let mut addr = addr;
    let (name, name_len) = match addr.as_deref_mut() {
        Some(addr) => (addr.as_mut_ptr(), RawAddr::CAPACITY as i32),
        None => (core::ptr::null_mut(), 0),
    };
    // No buffer at all is passed as one empty buffer: the same thing to the
    // kernel, but qemu-user answers 0 to a `recvmsg` without buffers by
    // itself, and leaves the datagram in the socket.
    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())
    };
    let mut msg = MsgHdr {
        name,
        name_len,
        // `IoSliceMut` is a transparent `iovec`.
        iov,
        iov_len,
        control,
        control_len,
        flags: 0,
    };
    // SAFETY: the kernel 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 { syscall!(RECVMSG, socket, &raw mut msg, flags) }?;
    if let Some(addr) = addr {
        addr.set_len(msg.name_len.max(0) as usize);
    }
    Ok((n, msg.flags as i32, msg.control_len.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, _) = recvmsg(socket, bufs, recv_flags(flags), addr, &mut [])?;
    Ok((n, flags & MSG_TRUNC != 0))
}

/// The size of `cmsg_len` in `struct cmsghdr`, a `size_t`, which is also
/// what control messages are aligned to. Two `int`s follow it: the level
/// and the type.
pub(crate) const CMSG_LEN_BYTES: usize = size_of::<usize>();
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)> {
    // The descriptors received are close-on-exec from the start.
    let flags = recv_flags(flags) | MSG_CMSG_CLOEXEC;
    let (n, flags, len) = recvmsg(socket, bufs, 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:
/// it already is.
pub(crate) fn received_handle(_fd: i32) -> Result<()> {
    Ok(())
}

/// One control message that holds one descriptor: a `struct cmsghdr` (a
/// length that is a `size_t`, the level and the type) and its data, padded
/// to the alignment of the header as `CMSG_SPACE` says.
#[cfg(feature = "alloc")]
#[repr(C)]
struct HandleMessage {
    len: usize,
    level: i32,
    kind: i32,
    fd: i32,
}

/// `CMSG_LEN(sizeof(int))`: the header and the data, without the padding.
#[cfg(feature = "alloc")]
const HANDLE_MESSAGE_LEN: usize = core::mem::offset_of!(HandleMessage, fd) + size_of::<i32>();

#[cfg(feature = "alloc")]
const _: () = assert!(
    size_of::<HandleMessage>() == 2 * size_of::<usize>() + 8
        && HANDLE_MESSAGE_LEN == size_of::<usize>() + 12
);

/// Two connected sockets to pass a descriptor of this process through,
/// as handles: `spawn` gives one to its child.
#[cfg(feature = "alloc")]
pub(crate) fn handle_channel() -> Result<(crate::OwnedHandle, crate::OwnedHandle)> {
    let mut fds = [0i32; 2];
    let ty = SOCK_STREAM | SOCK_CLOEXEC;
    // SAFETY: socketpair writes two descriptors to `fds`.
    unsafe { syscall!(SOCKETPAIR, AF_UNIX, ty, 0, fds.as_mut_ptr()) }?;
    // SAFETY: both descriptors were just created.
    Ok(unsafe {
        (
            crate::OwnedHandle::from_raw(fds[0]),
            crate::OwnedHandle::from_raw(fds[1]),
        )
    })
}

/// Sends the descriptor `fd` over `socket`, with one byte of data.
///
/// # Safety
///
/// Makes one system call and touches nothing but its own stack: it is
/// what a process that may do nothing else calls.
#[cfg(feature = "alloc")]
pub(crate) unsafe fn send_handle(socket: i32, fd: i32) -> Result<()> {
    let byte = 0u8;
    // A `struct iovec`.
    let iov = [(&raw const byte).addr(), 1usize];
    let control = HandleMessage {
        len: HANDLE_MESSAGE_LEN,
        level: SOL_SOCKET,
        kind: SCM_RIGHTS,
        fd,
    };
    let msg = MsgHdr {
        name: core::ptr::null_mut(),
        name_len: 0,
        iov: iov.as_ptr().cast_mut().cast(),
        iov_len: 1,
        control: (&raw const control).cast_mut().cast(),
        control_len: size_of::<HandleMessage>(),
        flags: 0,
    };
    // SAFETY: the kernel reads the structures above, which are on this
    // stack.
    unsafe { syscall!(SENDMSG, socket, &raw const msg, MSG_NOSIGNAL) }.map(drop)
}

/// Receives what `send_handle` sent: the descriptor, or `None` if the
/// other end was closed without sending one.
#[cfg(feature = "alloc")]
pub(crate) fn recv_handle(socket: i32) -> Result<Option<crate::OwnedHandle>> {
    let mut byte = 0u8;
    let mut iov = [(&raw mut byte).addr(), 1usize];
    let mut control = HandleMessage {
        len: 0,
        level: 0,
        kind: 0,
        fd: -1,
    };
    let mut msg = MsgHdr {
        name: core::ptr::null_mut(),
        name_len: 0,
        iov: iov.as_mut_ptr().cast(),
        iov_len: 1,
        control: (&raw mut control).cast(),
        control_len: size_of::<HandleMessage>(),
        flags: 0,
    };
    // SAFETY: the kernel writes one byte of data and at most one control
    // message of the size given, to structures on this stack.
    let received = unsafe { syscall!(RECVMSG, socket, &raw mut msg, MSG_CMSG_CLOEXEC) }?;
    let whole = msg.control_len >= HANDLE_MESSAGE_LEN
        && control.len == HANDLE_MESSAGE_LEN
        && control.level == SOL_SOCKET
        && control.kind == SCM_RIGHTS
        && control.fd >= 0;
    if received == 0 || !whole {
        return Ok(None);
    }
    // SAFETY: the kernel has just created the descriptor for this process.
    Ok(Some(unsafe { crate::OwnedHandle::from_raw(control.fd) }))
}

/// `struct ucred`.
#[repr(C)]
struct Ucred {
    pid: i32,
    uid: u32,
    gid: u32,
}

/// The user, the group and the process of the peer.
pub(crate) fn peer_cred(socket: RawSocket) -> Result<(u32, u32, Option<u32>)> {
    let value = Ucred {
        pid: 0,
        uid: 0,
        gid: 0,
    };
    // SAFETY: SO_PEERCRED yields a `struct ucred`.
    let value = unsafe { getsockopt(socket, SOL_SOCKET, SO_PEERCRED, value) }?;
    // A socket that has no peer, or is not a Unix-domain one, has "no
    // credentials": no process, and the user and group -1.
    if value.pid == 0 && value.uid == u32::MAX {
        return Err(crate::Error::from_raw_os_error(crate::sys::errno::ENOTCONN));
    }
    Ok((
        value.uid,
        value.gid,
        (value.pid > 0).then_some(value.pid as u32),
    ))
}

pub(crate) fn shutdown(socket: RawSocket, how: Shutdown) -> Result<()> {
    let how = match how {
        Shutdown::Read => 0,  // SHUT_RD
        Shutdown::Write => 1, // SHUT_WR
        Shutdown::Both => 2,  // SHUT_RDWR
    };
    // SAFETY: shutdown takes two integers.
    unsafe { syscall!(SHUTDOWN, socket, how) }?;
    Ok(())
}

pub(crate) fn local_addr(socket: RawSocket, addr: &mut RawAddr) -> Result<()> {
    let mut len = RawAddr::CAPACITY as u32;
    // SAFETY: the kernel writes at most `len` bytes to `addr`.
    unsafe { syscall!(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 kernel writes at most `len` bytes to `addr`.
    unsafe { syscall!(GETPEERNAME, socket, addr.as_mut_ptr(), &raw mut len) }?;
    addr.set_len(len as usize);
    Ok(())
}

pub(crate) fn set_nonblocking(socket: RawSocket, nonblocking: bool) -> Result<()> {
    let mut value = nonblocking as i32;
    // SAFETY: FIONBIO reads an int.
    unsafe { syscall!(IOCTL, socket, FIONBIO, &raw mut value) }?;
    Ok(())
}

/// Sets an option whose value is a `T`.
///
/// # Safety
///
/// `T` must be the type the option takes, with no padding.
unsafe fn setsockopt<T>(socket: RawSocket, level: i32, name: i32, value: &T) -> Result<()> {
    // SAFETY: the kernel reads `size_of::<T>()` bytes at `value`.
    unsafe {
        syscall!(
            SETSOCKOPT,
            socket,
            level,
            name,
            value as *const T,
            size_of::<T>()
        )
    }?;
    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: i32, name: i32, mut value: T) -> Result<T> {
    let mut len = size_of::<T>() as u32;
    // SAFETY: the kernel writes at most `len` bytes at `value`.
    unsafe {
        syscall!(
            GETSOCKOPT,
            socket,
            level,
            name,
            &raw mut value,
            &raw mut len
        )
    }?;
    Ok(value)
}

/// The level and name of an integer option.
fn option(opt: Opt) -> (i32, i32) {
    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_KEEPIDLE),
        Opt::KeepAliveInterval => (IPPROTO_TCP, TCP_KEEPINTVL),
        Opt::KeepAliveCount => (IPPROTO_TCP, TCP_KEEPCNT),
        Opt::Ttl => (IPPROTO_IP, IP_TTL),
        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, 0i32) }
}

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

fn ext_option(opt: ExtOpt) -> (i32, i32) {
    match opt {
        ExtOpt::ReusePort => (SOL_SOCKET, SO_REUSEPORT),
        ExtOpt::Cork => (IPPROTO_TCP, TCP_CORK),
        ExtOpt::QuickAck => (IPPROTO_TCP, TCP_QUICKACK),
        ExtOpt::FastOpen => (IPPROTO_TCP, TCP_FASTOPEN),
    }
}

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, 0i32) }
}

pub(crate) fn bind_interface(socket: RawSocket, index: u32) -> Result<()> {
    // SAFETY: SO_BINDTOIFINDEX is an int.
    unsafe { setsockopt(socket, SOL_SOCKET, SO_BINDTOIFINDEX, &(index as i32)) }
}

pub(crate) fn bound_interface(socket: RawSocket) -> Result<u32> {
    // SAFETY: SO_BINDTOIFINDEX is an int.
    let index = unsafe { getsockopt(socket, SOL_SOCKET, SO_BINDTOIFINDEX, 0i32) }?;
    Ok(index.max(0) as u32)
}

pub(crate) fn socket_type(socket: RawSocket) -> Result<Type> {
    // SAFETY: SO_TYPE is an int.
    match unsafe { getsockopt(socket, SOL_SOCKET, SO_TYPE, 0i32) }? {
        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: i32,
    seconds: i32,
}

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

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

/// `struct __kernel_sock_timeval`, which is also the `timeval` of 64-bit
/// targets.
#[repr(C)]
struct Timeval {
    sec: i64,
    usec: i64,
}

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

pub(crate) fn set_timeout(
    socket: RawSocket,
    direction: Direction,
    timeout: Option<Duration>,
) -> Result<()> {
    let value = match timeout {
        None => Timeval { sec: 0, usec: 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 i64;
            if usec == 1_000_000 {
                Timeval {
                    sec: sec.saturating_add(1),
                    usec: 0,
                }
            } else {
                Timeval { sec, usec }
            }
        }
    };
    // SAFETY: the option takes this structure (see `SO_RCVTIMEO`).
    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 };
    // SAFETY: the option yields this structure (see `SO_RCVTIMEO`).
    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_ADD_MEMBERSHIP
    } else {
        IPV6_DROP_MEMBERSHIP
    };
    // SAFETY: the option takes a `struct ipv6_mreq`.
    unsafe { setsockopt(socket, IPPROTO_IPV6, name, &value) }
}

// Interfaces are listed over a `NETLINK_ROUTE` socket (`linux/netlink.h`,
// `linux/rtnetlink.h`, `linux/if_link.h`, `linux/if_addr.h`): there is no
// system call for it, and the `ioctl`s that predate netlink know nothing of
// IPv6.

const AF_NETLINK: i32 = 16;
const NETLINK_ROUTE: i32 = 0;
const NLMSG_ERROR: u16 = 2;
const NLMSG_DONE: u16 = 3;
const RTM_NEWLINK: u16 = 16;
const RTM_GETLINK: u16 = 18;
const RTM_NEWADDR: u16 = 20;
const RTM_GETADDR: u16 = 22;
/// `NLM_F_REQUEST | NLM_F_DUMP`.
const NLM_REQUEST_DUMP: u16 = 0x301;
const NLM_F_DUMP_INTR: u16 = 0x10;
const IFLA_IFNAME: u16 = 3;
const IFA_ADDRESS: u16 = 1;
const IFA_LOCAL: u16 = 2;
const IFF_UP: u32 = 1;
const IFF_LOOPBACK: u32 = 8;
/// `sizeof(struct nlmsghdr)`: the length, the type and the flags (16 bits
/// each), the sequence number and the port.
const NLMSG_HEADER: usize = 16;
/// `sizeof(struct ifinfomsg)` and `sizeof(struct ifaddrmsg)`.
const IFINFOMSG: usize = 16;
const IFADDRMSG: usize = 8;

/// Room for the largest message of a dump: the kernel builds them in
/// buffers of at most 32 KiB.
#[repr(C, align(4))]
struct NetlinkBuf([u8; 32768]);

fn u16_at(bytes: &[u8], at: usize) -> u16 {
    u16::from_ne_bytes([bytes[at], bytes[at + 1]])
}

fn u32_at(bytes: &[u8], at: usize) -> u32 {
    u32::from_ne_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]])
}

/// Asks the kernel for the dump `request` (`RTM_GET*`, whose own header is
/// `body` zero bytes) and calls `each` with the type and the payload of
/// every message of the answer.
fn netlink_dump(request: u16, body: usize, each: &mut dyn FnMut(u16, &[u8])) -> Result<()> {
    const SEQUENCE: u32 = 1;
    // SAFETY: socket takes three integers.
    let fd = unsafe { syscall!(SOCKET, AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE) }?;
    // SAFETY: the descriptor was just created and nothing else owns it.
    let socket = unsafe { crate::net::OwnedSocket::from_raw(fd as RawSocket) };
    let fd = socket.as_raw();

    // The header, then the request's own, all zeros: every family, every
    // interface. The port is 0: the kernel names the socket itself.
    let mut message = [0u8; NLMSG_HEADER + IFINFOMSG];
    let len = NLMSG_HEADER + body;
    message[0..4].copy_from_slice(&(len as u32).to_ne_bytes());
    message[4..6].copy_from_slice(&request.to_ne_bytes());
    message[6..8].copy_from_slice(&NLM_REQUEST_DUMP.to_ne_bytes());
    message[8..12].copy_from_slice(&SEQUENCE.to_ne_bytes());
    // SAFETY: the kernel reads `len` bytes of `message`; with no address a
    // netlink socket sends to the kernel.
    unsafe { syscall!(SENDTO, fd, message.as_ptr(), len, 0, 0, 0) }?;

    let mut buf = NetlinkBuf([0; 32768]);
    let mut interrupted = false;
    loop {
        let mut from = RawAddr::new();
        let (n, flags, _) = recvmsg(
            fd,
            &mut [IoSliceMut::new(&mut buf.0)],
            0,
            Some(&mut from),
            &mut [],
        )?;
        if flags & MSG_TRUNC != 0 {
            return Err(ErrorKind::BufferTooSmall.into());
        }
        // `struct sockaddr_nl`: the family, padding, then the port of the
        // sender, which is 0 for the kernel. Anything else is not the
        // answer.
        let from = from.bytes();
        if from.len() < 8 || u32_at(from, 4) != 0 {
            continue;
        }
        if n == 0 {
            // The kernel closes a dump with a message, not with an end.
            return Err(crate::Error::from_raw_os_error(crate::sys::errno::EIO));
        }
        let mut rest = &buf.0[..n];
        while rest.len() >= NLMSG_HEADER {
            let len = u32_at(rest, 0) as usize;
            if len < NLMSG_HEADER || len > rest.len() {
                return Err(crate::Error::from_raw_os_error(crate::sys::errno::EIO));
            }
            let (ty, flags, sequence) = (u16_at(rest, 4), u16_at(rest, 6), u32_at(rest, 8));
            let payload = &rest[NLMSG_HEADER..len];
            // Messages are aligned to four bytes.
            rest = &rest[len.next_multiple_of(4).min(rest.len())..];
            // Not an answer to this request.
            if sequence != SEQUENCE {
                continue;
            }
            if flags & NLM_F_DUMP_INTR != 0 {
                interrupted = true;
            }
            match ty {
                NLMSG_DONE => {
                    return if interrupted {
                        Err(ErrorKind::Interrupted.into())
                    } else {
                        Ok(())
                    };
                }
                // `struct nlmsgerr` starts with the error, negated.
                NLMSG_ERROR if payload.len() >= 4 => {
                    let code = u32_at(payload, 0) as i32;
                    if code != 0 {
                        return Err(crate::Error::from_raw_os_error(code.wrapping_neg()));
                    }
                }
                _ => each(ty, payload),
            }
        }
    }
}

/// The value of the attribute `wanted` among `attrs`: `struct rtattr`s (a
/// length that includes the four bytes of the header, and a type), each
/// aligned to four bytes.
fn attribute(mut attrs: &[u8], wanted: u16) -> Option<&[u8]> {
    while attrs.len() >= 4 {
        let len = u16_at(attrs, 0) as usize;
        if len < 4 || len > attrs.len() {
            return None;
        }
        // The two high bits of the type are flags.
        if u16_at(attrs, 2) & 0x3fff == wanted {
            return Some(&attrs[4..len]);
        }
        attrs = &attrs[len.next_multiple_of(4).min(attrs.len())..];
    }
    None
}

pub(crate) fn interfaces(f: &mut crate::net::InterfaceVisitor<'_>) -> Result<()> {
    netlink_dump(RTM_GETLINK, IFINFOMSG, &mut |ty, payload| {
        // `struct ifinfomsg`: the index is its second word and the flags
        // its third.
        if ty != RTM_NEWLINK || payload.len() < IFINFOMSG {
            return;
        }
        let (index, flags) = (u32_at(payload, 4), u32_at(payload, 8));
        let name = attribute(&payload[IFINFOMSG..], IFLA_IFNAME).unwrap_or(&[]);
        // The name is a C string.
        let end = name.iter().position(|&c| c == 0).unwrap_or(name.len());
        f(
            index,
            &name[..end],
            flags & IFF_UP != 0,
            flags & IFF_LOOPBACK != 0,
        );
    })
}

pub(crate) fn interface_addrs(f: &mut crate::net::AddrVisitor<'_>) -> Result<()> {
    netlink_dump(RTM_GETADDR, IFADDRMSG, &mut |ty, payload| {
        // `struct ifaddrmsg`: the family, the prefix length, flags and
        // scope (a byte each), then the index.
        if ty != RTM_NEWADDR || payload.len() < IFADDRMSG {
            return;
        }
        let (family, prefix, index) = (payload[0], payload[1], u32_at(payload, 4));
        let attrs = &payload[IFADDRMSG..];
        // The interface's own address is `IFA_LOCAL` where there is one
        // (IPv4, where `IFA_ADDRESS` is the peer's on a point-to-point
        // link) and `IFA_ADDRESS` otherwise (IPv6).
        let Some(addr) = attribute(attrs, IFA_LOCAL).or_else(|| attribute(attrs, IFA_ADDRESS))
        else {
            return;
        };
        if family as u16 == AF_INET
            && let Ok(addr) = <[u8; 4]>::try_from(addr)
        {
            f(index, IpAddr::V4(Ipv4Addr::from(addr)), prefix);
        } else if family as u16 == AF_INET6
            && let Ok(addr) = <[u8; 16]>::try_from(addr)
        {
            f(index, IpAddr::V6(Ipv6Addr::from(addr)), prefix);
        }
    })
}