oscall 0.0.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
999
1000
1001
1002
1003
1004
1005
//! `net` on Windows: Winsock 2 (`ws2_32.dll`).
//!
//! A socket is a `SOCKET` (a `usize`), not a file handle; errors come from
//! `WSAGetLastError`; the library must be started once per process.
//!
//! Constants and layouts are those of `<winsock2.h>`, `<ws2def.h>`,
//! `<ws2ipdef.h>` and `<afunix.h>`.

use core::mem::size_of;
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;

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

pub(crate) type RawSocket = usize;

pub(crate) const AF_UNIX: u16 = 1;
pub(crate) const AF_INET: u16 = 2;
pub(crate) const AF_INET6: u16 = 23;
/// `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 = false;

const INVALID_SOCKET: usize = usize::MAX;
const SOCKET_ERROR: i32 = -1;

const SOCK_STREAM: i32 = 1;
const SOCK_DGRAM: i32 = 2;
const SOCK_RAW: i32 = 3;
const SOCK_SEQPACKET: i32 = 5;
const WSA_FLAG_OVERLAPPED: u32 = 0x01;
const WSA_FLAG_NO_HANDLE_INHERIT: u32 = 0x80;
const HANDLE_FLAG_INHERIT: u32 = 1;

const MSG_OOB: i32 = 0x1;
const MSG_PEEK: i32 = 0x2;
const MSG_DONTROUTE: i32 = 0x4;
const MSG_WAITALL: i32 = 0x8;

const FIONBIO: i32 = 0x8004667e_u32 as i32;

const WSAEINVAL: i32 = 10022;
const WSAEWOULDBLOCK: i32 = 10035;
const WSAEINPROGRESS: i32 = 10036;
const WSAEMSGSIZE: i32 = 10040;

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

const SO_REUSEADDR: i32 = 0x0004;
const SO_KEEPALIVE: i32 = 0x0008;
const SO_BROADCAST: i32 = 0x0020;
const SO_LINGER: i32 = 0x0080;
/// `~SO_REUSEADDR`.
const SO_EXCLUSIVEADDRUSE: i32 = -5;
const SO_SNDBUF: i32 = 0x1001;
const SO_RCVBUF: i32 = 0x1002;
const SO_SNDTIMEO: i32 = 0x1005;
const SO_RCVTIMEO: i32 = 0x1006;
const SO_ERROR: i32 = 0x1007;
const SO_TYPE: i32 = 0x1008;
const SO_PROTOCOL_INFOW: i32 = 0x2005;

const TCP_NODELAY: i32 = 1;
// Windows 10 version 1709 and later (the count: 1703).
const TCP_KEEPIDLE: i32 = 3;
const TCP_KEEPCNT: i32 = 16;
const TCP_KEEPINTVL: i32 = 17;
const IP_UNICAST_IF: i32 = 31;
const IPV6_UNICAST_IF: i32 = 31;
const IP_TTL: i32 = 4;
const IP_MULTICAST_TTL: i32 = 10;
const IP_MULTICAST_LOOP: i32 = 11;
const IP_ADD_MEMBERSHIP: i32 = 12;
const IP_DROP_MEMBERSHIP: i32 = 13;
const IPV6_UNICAST_HOPS: i32 = 4;
const IPV6_MULTICAST_HOPS: i32 = 10;
const IPV6_MULTICAST_LOOP: i32 = 11;
const IPV6_ADD_MEMBERSHIP: i32 = 12;
const IPV6_DROP_MEMBERSHIP: i32 = 13;
const IPV6_V6ONLY: i32 = 27;

/// Buffer lengths are an `int`.
const MAX_IO: usize = i32::MAX as usize;

/// `WSADATA`: the order of its fields depends on the pointer size.
#[repr(C)]
struct WsaData {
    version: u16,
    high_version: u16,
    #[cfg(target_pointer_width = "64")]
    max_sockets: u16,
    #[cfg(target_pointer_width = "64")]
    max_udp_dg: u16,
    #[cfg(target_pointer_width = "64")]
    vendor_info: *mut u8,
    description: [u8; 257],
    system_status: [u8; 129],
    #[cfg(target_pointer_width = "32")]
    max_sockets: u16,
    #[cfg(target_pointer_width = "32")]
    max_udp_dg: u16,
    #[cfg(target_pointer_width = "32")]
    vendor_info: *mut u8,
}

// In a module of their own: several have the name of a function here.
mod ws2 {
    use core::ffi::c_void;

    use super::WsaData;
    use crate::sys::dll;

    dll!("ws2_32.dll" {
        pub(super) fn WSAStartup(version: u16, data: *mut WsaData) -> i32;
        pub(super) fn WSAGetLastError() -> i32;
        pub(super) fn WSASocketW(
            family: i32,
            ty: i32,
            protocol: i32,
            protocol_info: *const c_void,
            group: u32,
            flags: u32,
        ) -> usize;
        pub(super) fn closesocket(socket: usize) -> i32;
        pub(super) fn bind(socket: usize, addr: *const u8, len: i32) -> i32;
        pub(super) fn connect(socket: usize, addr: *const u8, len: i32) -> i32;
        pub(super) fn listen(socket: usize, backlog: i32) -> i32;
        pub(super) fn accept(socket: usize, addr: *mut u8, len: *mut i32) -> usize;
        pub(super) fn send(socket: usize, buf: *const u8, len: i32, flags: i32) -> i32;
        pub(super) fn recv(socket: usize, buf: *mut u8, len: i32, flags: i32) -> i32;
        pub(super) fn sendto(
            socket: usize,
            buf: *const u8,
            len: i32,
            flags: i32,
            addr: *const u8,
            addr_len: i32,
        ) -> i32;
        pub(super) fn recvfrom(
            socket: usize,
            buf: *mut u8,
            len: i32,
            flags: i32,
            addr: *mut u8,
            addr_len: *mut i32,
        ) -> i32;
        // The buffers are `WSABUF`s, which `IoSlice` and `IoSliceMut` are.
        pub(super) fn WSASend(
            socket: usize,
            bufs: *const c_void,
            count: u32,
            sent: *mut u32,
            flags: u32,
            overlapped: *mut c_void,
            completion: *const c_void,
        ) -> i32;
        pub(super) fn WSASendTo(
            socket: usize,
            bufs: *const c_void,
            count: u32,
            sent: *mut u32,
            flags: u32,
            addr: *const u8,
            addr_len: i32,
            overlapped: *mut c_void,
            completion: *const c_void,
        ) -> i32;
        pub(super) fn WSARecv(
            socket: usize,
            bufs: *mut c_void,
            count: u32,
            received: *mut u32,
            flags: *mut u32,
            overlapped: *mut c_void,
            completion: *const c_void,
        ) -> i32;
        pub(super) fn WSARecvFrom(
            socket: usize,
            bufs: *mut c_void,
            count: u32,
            received: *mut u32,
            flags: *mut u32,
            addr: *mut u8,
            addr_len: *mut i32,
            overlapped: *mut c_void,
            completion: *const c_void,
        ) -> i32;
        pub(super) fn shutdown(socket: usize, how: i32) -> i32;
        pub(super) fn getsockname(socket: usize, addr: *mut u8, len: *mut i32) -> i32;
        pub(super) fn getpeername(socket: usize, addr: *mut u8, len: *mut i32) -> i32;
        pub(super) fn setsockopt(
            socket: usize,
            level: i32,
            name: i32,
            value: *const u8,
            len: i32,
        ) -> i32;
        pub(super) fn getsockopt(
            socket: usize,
            level: i32,
            name: i32,
            value: *mut u8,
            len: *mut i32,
        ) -> i32;
        pub(super) fn ioctlsocket(socket: usize, command: i32, arg: *mut u32) -> i32;
    });

    dll!("iphlpapi.dll" {
        pub(super) fn GetAdaptersAddresses(
            family: u32,
            flags: u32,
            reserved: *const c_void,
            addresses: *mut c_void,
            size: *mut u32,
        ) -> u32;
    });

    dll!("kernel32.dll" {
        pub(super) fn SetHandleInformation(handle: *mut c_void, mask: u32, flags: u32) -> i32;
    });
}

/// The calling thread's last Winsock error.
fn last_error() -> Error {
    // SAFETY: WSAGetLastError only reads thread-local state.
    Error::from_raw_os_error(unsafe { ws2::WSAGetLastError() })
}

/// Converts the result of the functions that return 0 or `SOCKET_ERROR`.
fn cvt(ret: i32) -> Result<()> {
    if ret == 0 { Ok(()) } else { Err(last_error()) }
}

/// Starts Winsock, once per process. It is never stopped: sockets may
/// outlive any point where that could be done.
fn startup() -> Result<()> {
    static STARTED: AtomicBool = AtomicBool::new(false);
    if STARTED.load(Ordering::Acquire) {
        return Ok(());
    }
    // SAFETY: WSADATA is plain data, for which zero is a valid value.
    let mut data: WsaData = unsafe { core::mem::zeroed() };
    // Version 2.2. Threads that race here each make the call, which only
    // counts references.
    // SAFETY: WSAStartup fills `data`.
    let code = unsafe { ws2::WSAStartup(0x0202, &raw mut data) };
    if code != 0 {
        // The one function that returns its error.
        return Err(Error::from_raw_os_error(code));
    }
    STARTED.store(true, Ordering::Release);
    Ok(())
}

/// # Safety
///
/// `socket` must be an open socket that nothing uses afterwards.
pub(crate) unsafe fn close(socket: RawSocket) {
    // SAFETY: closing a socket the caller owns.
    unsafe { ws2::closesocket(socket) };
}

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(domain: Family, ty: Type, protocol: Protocol) -> Result<RawSocket> {
    startup()?;
    let ty = match ty {
        Type::Stream => SOCK_STREAM,
        Type::Datagram => SOCK_DGRAM,
        Type::Raw => SOCK_RAW,
        Type::SeqPacket => SOCK_SEQPACKET,
    };
    let flags = WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT;
    // SAFETY: WSASocketW takes integers and an optional structure.
    let socket = unsafe {
        ws2::WSASocketW(
            family(domain),
            ty,
            protocol.number(),
            core::ptr::null(),
            0,
            flags,
        )
    };
    if socket == INVALID_SOCKET {
        return Err(last_error());
    }
    Ok(socket)
}

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

pub(crate) fn connect(socket: RawSocket, addr: &RawAddr) -> Result<()> {
    // SAFETY: `addr` holds `len` initialized bytes.
    cvt(unsafe { ws2::connect(socket, addr.as_ptr(), addr.len() as i32) }).map_err(|err| {
        // Windows alone reports a connection under way as "would block".
        if err.raw_os_error() == WSAEWOULDBLOCK {
            Error::from_raw_os_error(WSAEINPROGRESS)
        } else {
            err
        }
    })
}

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

pub(crate) fn accept(socket: RawSocket, addr: &mut RawAddr) -> Result<RawSocket> {
    let mut len = RawAddr::CAPACITY as i32;
    // SAFETY: the system writes at most `len` bytes to `addr`, and the
    // address's real length to `len`.
    let new = unsafe { ws2::accept(socket, addr.as_mut_ptr(), &raw mut len) };
    if new == INVALID_SOCKET {
        return Err(last_error());
    }
    addr.set_len(len.max(0) as usize);
    // The new socket is inheritable, and nothing can ask for another one.
    // Clearing the flag fails for the sockets of some layered providers,
    // which are not kernel handles and cannot be inherited anyway.
    // SAFETY: the call only changes a flag of the handle.
    unsafe { ws2::SetHandleInformation(new as *mut _, HANDLE_FLAG_INHERIT, 0) };
    // It also has the listener's non-blocking mode, which cannot be read.
    if let Err(err) = set_nonblocking(new, false) {
        // SAFETY: `new` is open and owned here.
        unsafe { close(new) };
        return Err(err);
    }
    Ok(new)
}

fn send_flags(flags: SendFlags) -> i32 {
    let mut raw = 0;
    if flags.contains(SendFlags::OUT_OF_BAND) {
        raw |= MSG_OOB;
    }
    if flags.contains(SendFlags::DONT_ROUTE) {
        raw |= MSG_DONTROUTE;
    }
    raw
}

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;
    }
    raw
}

pub(crate) fn send(
    socket: RawSocket,
    buf: &[u8],
    flags: SendFlags,
    addr: Option<&RawAddr>,
) -> Result<usize> {
    let raw = send_flags(flags);
    let (ptr, len) = (buf.as_ptr(), buf.len().min(MAX_IO) as i32);
    let n = match addr {
        // SAFETY: the system reads `len` bytes of `buf` and the address.
        Some(addr) => unsafe {
            ws2::sendto(socket, ptr, len, raw, addr.as_ptr(), addr.len() as i32)
        },
        // SAFETY: the system reads `len` bytes of `buf`.
        None => unsafe { ws2::send(socket, ptr, len, raw) },
    };
    if n == SOCKET_ERROR {
        return Err(last_error());
    }
    Ok(n as usize)
}

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().min(MAX_IO) as i32);
    let n = match addr {
        Some(addr) => {
            let mut addr_len = RawAddr::CAPACITY as i32;
            let from = addr.as_mut_ptr();
            // SAFETY: the system writes at most `len` bytes to `buf`, at
            // most `addr_len` to `addr`, and the address's length.
            let n = unsafe { ws2::recvfrom(socket, ptr, len, raw, from, &raw mut addr_len) };
            addr.set_len(addr_len.max(0) as usize);
            n
        }
        // SAFETY: the system writes at most `len` bytes to `buf`.
        None => unsafe { ws2::recv(socket, ptr, len, raw) },
    };
    if n == SOCKET_ERROR {
        let err = last_error();
        // A datagram longer than the buffer: the buffer was filled and the
        // rest dropped, which the other systems do not call an error.
        if err.raw_os_error() == WSAEMSGSIZE {
            return Ok(len as usize);
        }
        return Err(err);
    }
    Ok(n as usize)
}

pub(crate) fn send_vectored(
    socket: RawSocket,
    bufs: &[IoSlice<'_>],
    flags: SendFlags,
    addr: Option<&RawAddr>,
) -> Result<usize> {
    let raw = send_flags(flags) as u32;
    // No buffer at all is an empty message elsewhere; make sure of it here.
    let empty = [IoSlice::new(&[])];
    let bufs = if bufs.is_empty() { &empty[..] } else { bufs };
    let (ptr, count) = (bufs.as_ptr().cast(), bufs.len() as u32);
    let mut sent = 0u32;
    let (none, no_routine) = (core::ptr::null_mut(), core::ptr::null());
    let ret = match addr {
        // SAFETY: the system reads the `WSABUF`s, the buffers they describe
        // and the address, and writes the count to `sent`. With no
        // OVERLAPPED the call is synchronous.
        Some(addr) => unsafe {
            ws2::WSASendTo(
                socket,
                ptr,
                count,
                &raw mut sent,
                raw,
                addr.as_ptr(),
                addr.len() as i32,
                none,
                no_routine,
            )
        },
        // SAFETY: as above, without an address.
        None => unsafe { ws2::WSASend(socket, ptr, count, &raw mut sent, raw, none, no_routine) },
    };
    cvt(ret)?;
    Ok(sent as usize)
}

pub(crate) fn recv_vectored(
    socket: RawSocket,
    bufs: &mut [IoSliceMut<'_>],
    flags: RecvFlags,
    addr: Option<&mut RawAddr>,
) -> Result<(usize, bool)> {
    let mut raw = recv_flags(flags) as u32;
    // No buffer at all receives into an empty one, as elsewhere.
    let mut empty = [IoSliceMut::new(&mut [])];
    let capacity: usize = bufs.iter().map(|buf| buf.len()).sum();
    let (ptr, count) = if bufs.is_empty() {
        (empty.as_mut_ptr().cast(), 1)
    } else {
        (bufs.as_mut_ptr().cast(), bufs.len() as u32)
    };
    let mut received = 0u32;
    let (none, no_routine) = (core::ptr::null_mut(), core::ptr::null());
    let ret = match addr {
        Some(addr) => {
            let mut addr_len = RawAddr::CAPACITY as i32;
            // SAFETY: the system writes to the buffers the `WSABUF`s
            // describe, at most `addr_len` bytes to `addr`, and the three
            // integers. With no OVERLAPPED the call is synchronous.
            let ret = unsafe {
                ws2::WSARecvFrom(
                    socket,
                    ptr,
                    count,
                    &raw mut received,
                    &raw mut raw,
                    addr.as_mut_ptr(),
                    &raw mut addr_len,
                    none,
                    no_routine,
                )
            };
            addr.set_len(addr_len.max(0) as usize);
            ret
        }
        // SAFETY: as above, without an address.
        None => unsafe {
            ws2::WSARecv(
                socket,
                ptr,
                count,
                &raw mut received,
                &raw mut raw,
                none,
                no_routine,
            )
        },
    };
    if let Err(err) = cvt(ret) {
        // A datagram longer than the buffers: they were filled and the rest
        // dropped. This is how Windows tells.
        if err.raw_os_error() == WSAEMSGSIZE {
            return Ok((capacity, true));
        }
        return Err(err);
    }
    Ok((received as usize, false))
}

pub(crate) fn shutdown(socket: RawSocket, how: Shutdown) -> Result<()> {
    let how = match how {
        Shutdown::Read => 0,  // SD_RECEIVE
        Shutdown::Write => 1, // SD_SEND
        Shutdown::Both => 2,  // SD_BOTH
    };
    // SAFETY: shutdown takes two integers.
    cvt(unsafe { ws2::shutdown(socket, how) })
}

pub(crate) fn local_addr(socket: RawSocket, addr: &mut RawAddr) -> Result<()> {
    let mut len = RawAddr::CAPACITY as i32;
    // SAFETY: the system writes at most `len` bytes to `addr`.
    match cvt(unsafe { ws2::getsockname(socket, addr.as_mut_ptr(), &raw mut len) }) {
        Ok(()) => {
            addr.set_len(len.max(0) as usize);
            Ok(())
        }
        // Windows alone refuses to name a socket that is not bound, where
        // the others report the unspecified address of its family.
        Err(err) if err.raw_os_error() == WSAEINVAL => {
            // `WSAPROTOCOL_INFOW`, 628 bytes, as 32-bit words: the socket's
            // family (`iAddressFamily`) is the twentieth.
            let info = [0u32; 157];
            // SAFETY: SO_PROTOCOL_INFOW yields a WSAPROTOCOL_INFOW, which is
            // plain data of this size and alignment.
            let info = unsafe { getsockopt(socket, SOL_SOCKET, SO_PROTOCOL_INFOW, info) };
            match info {
                Ok(info) if addr.set_unspecified(info[19] as u16) => Ok(()),
                _ => Err(err),
            }
        }
        Err(err) => Err(err),
    }
}

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

pub(crate) fn set_nonblocking(socket: RawSocket, nonblocking: bool) -> Result<()> {
    let mut value = nonblocking as u32;
    // SAFETY: FIONBIO reads a u_long.
    cvt(unsafe { ws2::ioctlsocket(socket, FIONBIO, &raw mut value) })
}

/// 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<()> {
    let ptr = (value as *const T).cast::<u8>();
    // SAFETY: the system reads `size_of::<T>()` bytes at `value`.
    cvt(unsafe { ws2::setsockopt(socket, level, name, ptr, size_of::<T>() as i32) })
}

/// Reads an option whose value is a `T`, over the initial `value` (some
/// boolean options write one byte only).
///
/// # 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 i32;
    let ptr = (&raw mut value).cast::<u8>();
    // SAFETY: the system writes at most `len` bytes at `value`.
    cvt(unsafe { ws2::getsockopt(socket, level, name, ptr, &raw mut len) })?;
    Ok(value)
}

/// The level and name of an integer option.
fn option(opt: Opt) -> (i32, i32) {
    match opt {
        // Inverted by its users: see `net::set_reuse_addr`.
        Opt::ReuseAddr => (SOL_SOCKET, SO_EXCLUSIVEADDRUSE),
        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);
    let value = match opt {
        Opt::ReuseAddr => (value == 0) as i32,
        _ => value,
    };
    // SAFETY: these options are a BOOL or a DWORD.
    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 a BOOL or a DWORD.
    let value = unsafe { getsockopt(socket, level, name, 0i32) }?;
    Ok(match opt {
        Opt::ReuseAddr => (value == 0) as i32,
        _ => value,
    })
}

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

fn ext_option(opt: ExtOpt) -> (i32, i32) {
    match opt {
        ExtOpt::ReuseAddr => (SOL_SOCKET, SO_REUSEADDR),
    }
}

pub(crate) fn set_ext_opt(socket: RawSocket, opt: ExtOpt, value: i32) -> Result<()> {
    let (level, name) = ext_option(opt);
    // SAFETY: these options are a BOOL.
    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 a BOOL.
    unsafe { getsockopt(socket, level, name, 0i32) }
}

/// Whether the socket is an IPv6 one, for the option that chooses its
/// interface: there is one for each of the two Internet families.
fn is_v6(socket: RawSocket) -> Result<bool> {
    let mut addr = RawAddr::new();
    local_addr(socket, &mut addr)?;
    match addr.family() {
        AF_INET => Ok(false),
        AF_INET6 => Ok(true),
        _ => Err(ErrorKind::InvalidInput.into()),
    }
}

pub(crate) fn bind_interface(socket: RawSocket, index: u32) -> Result<()> {
    if is_v6(socket)? {
        // SAFETY: IPV6_UNICAST_IF is a DWORD.
        unsafe { setsockopt(socket, IPPROTO_IPV6, IPV6_UNICAST_IF, &index) }
    } else {
        // The IPv4 option alone wants the index in network byte order.
        // SAFETY: IP_UNICAST_IF is a DWORD.
        unsafe { setsockopt(socket, IPPROTO_IP, IP_UNICAST_IF, &index.to_be()) }
    }
}

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()),
    }
}

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

pub(crate) fn set_linger(socket: RawSocket, seconds: Option<u32>) -> Result<()> {
    let value = Linger {
        onoff: seconds.is_some() as u16,
        seconds: seconds.unwrap_or(0).min(u16::MAX as u32) as u16,
    };
    // SAFETY: SO_LINGER takes a 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 LINGER.
    let value = unsafe { getsockopt(socket, SOL_SOCKET, SO_LINGER, value) }?;
    Ok((value.onoff != 0).then_some(value.seconds as u32))
}

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<()> {
    // A DWORD of milliseconds, where zero means no timeout: round up.
    let millis: u32 = match timeout {
        None => 0,
        Some(time) => time.as_nanos().div_ceil(1_000_000).min(u32::MAX as u128) as u32,
    };
    // SAFETY: the option takes a DWORD.
    unsafe { setsockopt(socket, SOL_SOCKET, timeout_name(direction), &millis) }
}

pub(crate) fn timeout(socket: RawSocket, direction: Direction) -> Result<Option<Duration>> {
    // SAFETY: the option yields a DWORD.
    let millis = unsafe { getsockopt(socket, SOL_SOCKET, timeout_name(direction), 0u32) }?;
    Ok((millis != 0).then(|| Duration::from_millis(millis as u64)))
}

pub(crate) fn membership_v4(
    socket: RawSocket,
    join: bool,
    group: [u8; 4],
    interface: [u8; 4],
) -> Result<()> {
    // `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 an IP_MREQ.
    unsafe { setsockopt(socket, IPPROTO_IP, name, &value) }
}

/// `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 an IPV6_MREQ.
    unsafe { setsockopt(socket, IPPROTO_IPV6, name, &value) }
}

#[cfg(feature = "alloc")]
const ERROR_BUFFER_OVERFLOW: u32 = 111;
const ERROR_NO_DATA: u32 = 232;
/// `GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
/// GAA_FLAG_SKIP_DNS_SERVER`: the unicast addresses are all that is read.
const GAA_FLAGS: u32 = 2 | 4 | 8;
const IF_TYPE_SOFTWARE_LOOPBACK: u32 = 24;
/// `IfOperStatusUp`.
const OPER_STATUS_UP: i32 = 1;

/// The start of `IP_ADAPTER_ADDRESSES_LH` (`<iptypes.h>`), as far as it is
/// read. The first two fields are a union with a 64-bit integer, which
/// only matters for the alignment of the whole.
#[repr(C)]
struct Adapter {
    length: u32,
    if_index: u32,
    next: *const Adapter,
    adapter_name: *const u8,
    first_unicast: *const Unicast,
    first_anycast: *const u8,
    first_multicast: *const u8,
    first_dns_server: *const u8,
    dns_suffix: *const u16,
    description: *const u16,
    friendly_name: *const u16,
    physical_address: [u8; 8],
    physical_address_len: u32,
    flags: u32,
    mtu: u32,
    if_type: u32,
    oper_status: i32,
    ipv6_if_index: u32,
}

/// `SOCKET_ADDRESS`: a structure of its own, with its own padding.
#[repr(C)]
struct SocketAddress {
    sockaddr: *const u8,
    len: i32,
}

/// `IP_ADAPTER_UNICAST_ADDRESS_LH`.
#[repr(C)]
struct Unicast {
    length: u32,
    flags: u32,
    next: *const Unicast,
    address: SocketAddress,
    prefix_origin: i32,
    suffix_origin: i32,
    dad_state: i32,
    valid_lifetime: u32,
    preferred_lifetime: u32,
    lease_lifetime: u32,
    on_link_prefix_length: u8,
}

/// The size of the buffer on the stack, in 64-bit words: 32 KiB, twice
/// what Microsoft suggests to start with.
const ADAPTERS_WORDS: usize = 4096;

/// Asks for the adapters into `buf`. `Ok(true)` if it holds the list,
/// `Ok(false)` if there is no adapter; `size` is the room needed when the
/// call fails with `ERROR_BUFFER_OVERFLOW`.
fn get_adapters(buf: &mut [u64], size: &mut u32) -> Result<bool> {
    *size = (buf.len() * 8).min(u32::MAX as usize) as u32;
    // SAFETY: the system writes at most `size` bytes to `buf`, which is
    // aligned for the structures it writes.
    let code = unsafe {
        ws2::GetAdaptersAddresses(
            0, // AF_UNSPEC
            GAA_FLAGS,
            core::ptr::null(),
            buf.as_mut_ptr().cast(),
            size,
        )
    };
    match code {
        0 => Ok(true),
        ERROR_NO_DATA => Ok(false),
        // The one function here that returns its error.
        code => Err(Error::from_raw_os_error(code as i32)),
    }
}

/// Calls `each` with every adapter of the system (`GetAdaptersAddresses`).
fn adapters(each: &mut dyn FnMut(&Adapter)) -> Result<()> {
    /// # Safety
    ///
    /// `buf` must hold the list `GetAdaptersAddresses` just wrote.
    unsafe fn walk(buf: &[u64], each: &mut dyn FnMut(&Adapter)) {
        let mut adapter = buf.as_ptr().cast::<Adapter>();
        while !adapter.is_null() {
            // SAFETY: the system wrote a list of adapters whose links
            // point into `buf`, which is borrowed for the whole walk.
            let current = unsafe { &*adapter };
            each(current);
            adapter = current.next;
        }
    }

    let mut stack = [0u64; ADAPTERS_WORDS];
    let mut size = 0;
    match get_adapters(&mut stack, &mut size) {
        Ok(true) => {
            // SAFETY: the call just filled `stack`.
            unsafe { walk(&stack, each) };
            Ok(())
        }
        Ok(false) => Ok(()),
        // A machine with more adapters than fit on the stack.
        #[cfg(feature = "alloc")]
        Err(err) if err.raw_os_error() == ERROR_BUFFER_OVERFLOW as i32 => {
            // Some room to spare: the list may have grown since.
            let words = (size as usize).div_ceil(8) + 512;
            let mut heap = alloc::vec::Vec::new();
            if heap.try_reserve_exact(words).is_err() {
                return Err(ErrorKind::OutOfMemory.into());
            }
            heap.resize(words, 0u64);
            if get_adapters(&mut heap, &mut size)? {
                // SAFETY: the call just filled `heap`.
                unsafe { walk(&heap, each) };
            }
            Ok(())
        }
        Err(err) => Err(err),
    }
}

pub(crate) fn interfaces(f: &mut crate::net::InterfaceVisitor<'_>) -> Result<()> {
    adapters(&mut |adapter| {
        // The name users know, as UTF-8: at most 256 UTF-16 units.
        let mut name = [0u8; 1024];
        let mut len = 0;
        if !adapter.friendly_name.is_null() {
            let units = (0..512)
                // SAFETY: the name is a NUL-terminated string in the
                // buffer, and reading stops at its NUL.
                .map(|at| unsafe { adapter.friendly_name.add(at).read_unaligned() })
                .take_while(|&unit| unit != 0);
            for ch in char::decode_utf16(units) {
                let ch = ch.unwrap_or(char::REPLACEMENT_CHARACTER);
                if len + ch.len_utf8() > name.len() {
                    break;
                }
                len += ch.encode_utf8(&mut name[len..]).len();
            }
        }
        // The IPv4 index is 0 on an adapter without IPv4; when both
        // exist they are the same.
        let index = if adapter.if_index != 0 {
            adapter.if_index
        } else {
            adapter.ipv6_if_index
        };
        f(
            index,
            &name[..len],
            adapter.oper_status == OPER_STATUS_UP,
            adapter.if_type == IF_TYPE_SOFTWARE_LOOPBACK,
        );
    })
}

pub(crate) fn interface_addrs(f: &mut crate::net::AddrVisitor<'_>) -> Result<()> {
    adapters(&mut |adapter| {
        let mut unicast = adapter.first_unicast;
        while !unicast.is_null() {
            // SAFETY: the list of addresses is in the same buffer as the
            // adapter, which is borrowed.
            let current = unsafe { &*unicast };
            unicast = current.next;
            let len = current.address.len.max(0) as usize;
            if current.address.sockaddr.is_null() || len < 2 {
                continue;
            }
            // SAFETY: the address is `len` bytes in the same buffer.
            let addr = unsafe { core::slice::from_raw_parts(current.address.sockaddr, len) };
            let family = u16::from_ne_bytes([addr[0], addr[1]]);
            // `sockaddr_in` has its address at 4, `sockaddr_in6` at 8.
            if family == AF_INET && len >= 8 {
                let ip = Ipv4Addr::new(addr[4], addr[5], addr[6], addr[7]);
                f(
                    adapter.if_index,
                    IpAddr::V4(ip),
                    current.on_link_prefix_length,
                );
            } else if family == AF_INET6 && len >= 24 {
                let mut ip = [0; 16];
                ip.copy_from_slice(&addr[8..24]);
                let index = if adapter.ipv6_if_index != 0 {
                    adapter.ipv6_if_index
                } else {
                    adapter.if_index
                };
                f(
                    index,
                    IpAddr::V6(Ipv6Addr::from(ip)),
                    current.on_link_prefix_length,
                );
            }
        }
    })
}