net-io 0.8.0

Network IO substrate for Rust: TCP, UDP and local-socket listeners, connection lifecycle, limits, graceful drain, PROXY protocol, and a TLS seam. Protocol-free and dependency-free.
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
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
//! Windows (x86_64, aarch64; MSVC and GNU).
//!
//! Declarations come from the Windows SDK headers (`winsock2.h`, `ws2def.h`,
//! `ws2ipdef.h`, `mstcpip.h`, `handleapi.h`); every constant, struct layout,
//! and function signature is checked against `windows-sys` by the `layout`
//! tests at the bottom of this file. Reference: Microsoft Learn, Winsock
//! functions and `SOL_SOCKET` / `IPPROTO_TCP` / `IPPROTO_IPV6` socket options.
//!
//! Sockets in net-io's blocking driver are non-blocking on Windows and every
//! wait is `WSAPoll` with a wake socket: a socket whose blocking receive or send
//! timed out is documented as being in an indeterminate state (decision D-052).

use std::ffi::c_void;
use std::io::{self, IoSlice};
use std::mem::size_of;
use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket};
use std::os::windows::io::{
    AsRawHandle, AsRawSocket, AsSocket, BorrowedSocket, FromRawHandle, FromRawSocket, OwnedHandle,
    OwnedSocket, RawSocket,
};
use std::sync::Once;
use std::time::Duration;

use super::{Interest, Ready, poll_millis, retry_interrupted};

pub(super) type Socket = usize;

/// Winsock error codes net-io classifies.
pub(crate) mod errno {
    pub const WSAEBADF: i32 = 10009;
    pub const WSAEACCES: i32 = 10013;
    pub const WSAEINVAL: i32 = 10022;
    pub const WSAEMFILE: i32 = 10024;
    pub const WSAENOTSOCK: i32 = 10038;
    pub const WSAEADDRINUSE: i32 = 10048;
    pub const WSAEADDRNOTAVAIL: i32 = 10049;
    pub const WSAENETUNREACH: i32 = 10051;
    pub const WSAENOBUFS: i32 = 10055;
    pub const WSAETIMEDOUT: i32 = 10060;
    pub const WSAECONNREFUSED: i32 = 10061;
    pub const WSAEHOSTUNREACH: i32 = 10065;
    #[cfg(feature = "udp")]
    pub const WSAEMSGSIZE: i32 = 10040;
    /// On a datagram socket: an ICMP "time exceeded" report about an earlier send.
    #[cfg(feature = "udp")]
    pub const WSAENETRESET: i32 = 10052;
}

/// How an `accept` failure is handled (FR-9, FR-10). Socket handles do not come
/// from a small table on Windows, so exhaustion is handled with the pause alone.
pub(crate) fn classify_accept(e: &io::Error) -> super::AcceptFailure {
    use super::AcceptFailure as F;
    use errno::*;
    match e.raw_os_error() {
        Some(WSAEMFILE | WSAENOBUFS) => F::Pressure,
        Some(WSAEBADF | WSAEINVAL | WSAENOTSOCK) => F::ListenerFailed,
        _ => F::PerConnection,
    }
}

/// Maps a bind or connect error to its own variant.
/// A connect that failed for want of a local port (every ephemeral port in use or
/// in TIME_WAIT): it passes once ports come free, so a reconnect may wait for it.
pub(crate) fn out_of_ports(e: &io::Error) -> bool {
    use errno::*;
    matches!(
        e.raw_os_error(),
        Some(WSAEADDRINUSE | WSAENOBUFS | WSAEADDRNOTAVAIL)
    )
}

pub(crate) fn classify_addr_error(e: &io::Error) -> super::AddrFailure {
    use super::AddrFailure as F;
    use errno::*;
    match e.raw_os_error() {
        Some(WSAEADDRINUSE) => F::InUse,
        Some(WSAEADDRNOTAVAIL) => F::NotAvailable,
        Some(WSAEACCES) => F::Permission,
        Some(WSAECONNREFUSED) => F::Refused,
        Some(WSAEHOSTUNREACH) => F::HostUnreachable,
        Some(WSAENETUNREACH) => F::NetworkUnreachable,
        Some(WSAETIMEDOUT) => F::TimedOut,
        _ => F::Other,
    }
}

pub(super) mod c {
    #[cfg(feature = "local")]
    pub const AF_UNIX: i32 = 1;
    pub const AF_INET: i32 = 2;
    pub const AF_INET6: i32 = 23;
    pub const SOCK_STREAM: i32 = 1;
    #[cfg(feature = "udp")]
    pub const SOCK_DGRAM: i32 = 2;
    #[cfg(feature = "udp")]
    pub const IPPROTO_UDP: i32 = 17;
    #[cfg(feature = "udp")]
    pub const SIO_UDP_CONNRESET: u32 = 0x9800_000C;
    #[cfg(feature = "udp")]
    pub const SIO_UDP_NETRESET: u32 = 0x9800_000F;
    pub const IPPROTO_IP: i32 = 0;
    pub const IPPROTO_TCP: i32 = 6;
    pub const IPPROTO_IPV6: i32 = 41;
    pub const SOL_SOCKET: i32 = 0xffff;
    pub const SO_ACCEPTCONN: i32 = 0x2;
    pub const SO_REUSEADDR: i32 = 0x4;
    pub const SO_EXCLUSIVEADDRUSE: i32 = !SO_REUSEADDR;
    pub const SO_KEEPALIVE: i32 = 0x8;
    pub const SO_LINGER: i32 = 0x80;
    pub const SO_SNDBUF: i32 = 0x1001;
    pub const SO_RCVBUF: i32 = 0x1002;
    pub const SO_ERROR: i32 = 0x1007;
    pub const SO_TYPE: i32 = 0x1008;
    pub const TCP_NODELAY: i32 = 0x1;
    pub const TCP_KEEPIDLE: i32 = 3;
    pub const TCP_MAXRT: i32 = 5;
    pub const TCP_FASTOPEN: i32 = 15;
    pub const TCP_KEEPCNT: i32 = 16;
    pub const TCP_KEEPINTVL: i32 = 17;
    pub const IP_TTL: i32 = 4;
    pub const IPV6_UNICAST_HOPS: i32 = 4;
    pub const IPV6_V6ONLY: i32 = 27;
    pub const POLLRDNORM: i16 = 0x100;
    pub const POLLWRNORM: i16 = 0x10;
    pub const WSA_FLAG_OVERLAPPED: u32 = 0x01;
    pub const WSA_FLAG_NO_HANDLE_INHERIT: u32 = 0x80;
    pub const HANDLE_FLAG_INHERIT: u32 = 0x1;
    pub const INVALID_SOCKET: usize = !0;
    pub const SOCKET_ERROR: i32 = -1;
    pub const WSAEINTR: i32 = 10004;
    pub const WSAEWOULDBLOCK: i32 = 10035;
}

#[repr(C)]
#[derive(Clone, Copy)]
struct SockaddrIn {
    sin_family: u16,
    sin_port: u16,
    sin_addr: u32,
    sin_zero: [u8; 8],
}

#[repr(C)]
#[derive(Clone, Copy)]
struct SockaddrIn6 {
    sin6_family: u16,
    sin6_port: u16,
    sin6_flowinfo: u32,
    sin6_addr: [u8; 16],
    sin6_scope_id: u32,
}

#[repr(C)]
#[derive(Clone, Copy)]
struct Linger {
    l_onoff: u16,
    l_linger: u16,
}

#[repr(C)]
#[derive(Clone, Copy)]
struct WsaPollFd {
    fd: Socket,
    events: i16,
    revents: i16,
}

#[repr(C)]
struct WsaData {
    w_version: u16,
    w_high_version: u16,
    i_max_sockets: u16,
    i_max_udp_dg: u16,
    lp_vendor_info: *mut u8,
    sz_description: [u8; 257],
    sz_system_status: [u8; 129],
}

/// `OVERLAPPED`. The kernel writes `internal` and `internal_high`.
#[cfg(any(feature = "reactor", feature = "local"))]
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(super) struct Overlapped {
    pub(super) internal: usize,
    pub(super) internal_high: usize,
    pub(super) offset: u32,
    pub(super) offset_high: u32,
    pub(super) event: usize,
}

/// `WSAPROTOCOL_INFOW`.
#[cfg(any(feature = "reactor", feature = "local"))]
#[repr(C)]
#[derive(Clone, Copy)]
pub(super) struct WsaProtocolInfo {
    pub(super) service_flags1: u32,
    service_flags2: u32,
    service_flags3: u32,
    service_flags4: u32,
    provider_flags: u32,
    provider_id: [u8; 16],
    catalog_entry_id: u32,
    chain_len: i32,
    chain: [u32; 7],
    version: i32,
    address_family: i32,
    max_sockaddr: i32,
    min_sockaddr: i32,
    socket_type: i32,
    pub(super) i_protocol: i32,
    protocol_max_offset: i32,
    network_byte_order: i32,
    security_scheme: i32,
    message_size: u32,
    provider_reserved: u32,
    protocol: [u16; 256],
}

const _: () = assert!(size_of::<SockaddrIn>() == 16);
#[cfg(any(feature = "reactor", feature = "local"))]
const _: () = assert!(size_of::<WsaProtocolInfo>() == 628);
const _: () = assert!(size_of::<SockaddrIn6>() == 28);
const _: () = assert!(size_of::<Linger>() == 4);
const _: () = assert!(size_of::<WsaPollFd>() == 16);
const _: () = assert!(size_of::<WsaData>() == 408);

#[link(name = "ws2_32")]
unsafe extern "system" {
    fn WSAStartup(version: u16, data: *mut WsaData) -> i32;
    fn WSASocketW(
        af: i32,
        ty: i32,
        protocol: i32,
        info: *mut c_void,
        group: u32,
        flags: u32,
    ) -> Socket;
    fn bind(s: Socket, name: *const c_void, len: i32) -> i32;
    fn listen(s: Socket, backlog: i32) -> i32;
    fn connect(s: Socket, name: *const c_void, len: i32) -> i32;
    #[cfg(feature = "local")]
    #[link_name = "accept"]
    fn accept_raw(s: Socket, name: *mut c_void, len: *mut i32) -> Socket;
    fn setsockopt(s: Socket, level: i32, name: i32, value: *const u8, len: i32) -> i32;
    fn getsockopt(s: Socket, level: i32, name: i32, value: *mut u8, len: *mut i32) -> i32;
    fn WSAPoll(fds: *mut WsaPollFd, nfds: u32, timeout: i32) -> i32;
    fn WSAGetLastError() -> i32;
    #[cfg(feature = "local")]
    fn WSADuplicateSocketW(s: Socket, pid: u32, info: *mut WsaProtocolInfo) -> i32;
    #[cfg(feature = "udp")]
    fn recvfrom(
        s: Socket,
        buf: *mut u8,
        len: i32,
        flags: i32,
        from: *mut c_void,
        from_len: *mut i32,
    ) -> i32;
    #[cfg(any(feature = "udp", feature = "local"))]
    fn WSAIoctl(
        s: Socket,
        code: u32,
        in_buf: *const c_void,
        in_len: u32,
        out_buf: *mut c_void,
        out_len: u32,
        returned: *mut u32,
        overlapped: *mut c_void,
        completion: *mut c_void,
    ) -> i32;
}

#[cfg(feature = "local")]
#[link(name = "bcrypt")]
unsafe extern "system" {
    fn BCryptGenRandom(algorithm: *mut c_void, buffer: *mut u8, len: u32, flags: u32) -> i32;
}

#[cfg(feature = "local")]
const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 2;
#[cfg(feature = "local")]
const FROM_PROTOCOL_INFO: i32 = -1;

#[link(name = "kernel32")]
unsafe extern "system" {
    fn SetHandleInformation(handle: *mut c_void, mask: u32, flags: u32) -> i32;
    fn GetActiveProcessorGroupCount() -> u16;
    fn GetActiveProcessorCount(group: u16) -> u32;
    fn GetCurrentThread() -> *mut c_void;
    fn SetThreadGroupAffinity(
        thread: *mut c_void,
        affinity: *const GroupAffinity,
        previous: *mut GroupAffinity,
    ) -> i32;
    fn CreateEventW(
        attributes: *const c_void,
        manual: i32,
        initial: i32,
        name: *const u16,
    ) -> *mut c_void;
    fn SetEvent(event: *mut c_void) -> i32;
    pub(super) fn CancelIoEx(file: *mut c_void, overlapped: *mut c_void) -> i32;
    fn QueryPerformanceCounter(count: *mut i64) -> i32;
    fn QueryPerformanceFrequency(frequency: *mut i64) -> i32;
}

/// The performance counter in microseconds.
pub(crate) fn monotonic_micros() -> u64 {
    let (mut count, mut freq) = (0i64, 0i64);
    // SAFETY: both calls write one i64 through a live pointer; neither fails on
    // Windows XP and later.
    unsafe {
        QueryPerformanceCounter(&raw mut count);
        QueryPerformanceFrequency(&raw mut freq);
    }
    let (count, freq) = (count.max(0) as u128, freq.max(1) as u128);
    (count * 1_000_000 / freq) as u64
}

/// A borrowed socket handle.
pub(crate) type Sock<'a> = BorrowedSocket<'a>;
/// A raw socket handle.
pub(crate) type RawSock = RawSocket;
/// An owned socket handle.
pub(crate) type OwnedSock = OwnedSocket;

/// Types whose socket handle this layer can borrow.
pub(crate) trait AsSock {
    fn sock(&self) -> Sock<'_>;
}

impl<T: AsSocket> AsSock for T {
    fn sock(&self) -> Sock<'_> {
        self.as_socket()
    }
}

/// A socket number as a borrowed socket.
///
/// # Safety
///
/// `s` is open for as long as the result is used.
#[cfg(feature = "reactor")]
pub(super) unsafe fn borrow(s: Socket) -> Sock<'static> {
    // SAFETY: by this function's contract.
    unsafe { BorrowedSocket::borrow_raw(s as RawSocket) }
}

/// Sets a socket-level option that takes no value.
///
/// # Safety
///
/// None beyond passing a number: a stale socket fails the call.
#[cfg(feature = "reactor")]
pub(super) unsafe fn setsockopt_empty(s: Socket, name: i32) -> io::Result<()> {
    // SAFETY: a null value of length 0 is what these options take.
    cvt(unsafe { setsockopt(s, c::SOL_SOCKET, name, std::ptr::null(), 0) }).map(drop)
}

pub(crate) fn raw_of(sock: Sock<'_>) -> RawSock {
    sock.as_raw_socket()
}

pub(super) fn raw(sock: Sock<'_>) -> Socket {
    // RawSocket is u64; SOCKET is pointer-sized, and both targets here are 64-bit.
    sock.as_raw_socket() as Socket
}

fn last_error() -> io::Error {
    // SAFETY: WSAGetLastError reads this thread's last Winsock error; no arguments.
    io::Error::from_raw_os_error(unsafe { WSAGetLastError() })
}

fn cvt(ret: i32) -> io::Result<i32> {
    if ret == c::SOCKET_ERROR {
        Err(last_error())
    } else {
        Ok(ret)
    }
}

static STARTUP: Once = Once::new();

/// Winsock must be started before the first socket call. `WSAStartup` is
/// reference counted, so this coexists with the standard library's own call.
pub(super) fn startup() {
    STARTUP.call_once(|| {
        // SAFETY: WsaData is plain data; zeroed is a valid starting value that
        // WSAStartup overwrites. Version 2.2 is requested as Microsoft documents.
        let mut data: WsaData = unsafe { std::mem::zeroed() };
        // SAFETY: `data` is a live, correctly sized WSADATA.
        let _ = unsafe { WSAStartup(0x0202, &raw mut data) };
    });
}

fn set_int(sock: Sock<'_>, level: i32, name: i32, value: i32) -> io::Result<()> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::SetOption)?;
    // SAFETY: `sock` is open for the call; `value` is a live i32 and the length
    // passed is its size, as setsockopt requires for integer and DWORD options.
    let ret = unsafe {
        setsockopt(
            raw(sock),
            level,
            name,
            (&raw const value).cast::<u8>(),
            size_of::<i32>() as i32,
        )
    };
    cvt(ret).map(drop)
}

fn get_int(sock: Sock<'_>, level: i32, name: i32) -> io::Result<i32> {
    let mut value: i32 = 0;
    let mut len = size_of::<i32>() as i32;
    // SAFETY: `value` and `len` are live locals; `len` holds the size of `value`.
    let ret = unsafe {
        getsockopt(
            raw(sock),
            level,
            name,
            (&raw mut value).cast::<u8>(),
            &raw mut len,
        )
    };
    cvt(ret).map(|_| value)
}

pub(super) fn encode_addr(addr: SocketAddr, out: &mut [u8; 28]) -> i32 {
    match addr {
        SocketAddr::V4(a) => {
            let sa = SockaddrIn {
                sin_family: c::AF_INET as u16,
                sin_port: a.port().to_be(),
                sin_addr: u32::from_ne_bytes(a.ip().octets()),
                sin_zero: [0; 8],
            };
            // SAFETY: `SockaddrIn` is repr(C), Copy, 16 bytes without padding.
            let bytes: [u8; 16] = unsafe { std::mem::transmute(sa) };
            out[..16].copy_from_slice(&bytes);
            16
        }
        SocketAddr::V6(a) => {
            let sa = SockaddrIn6 {
                sin6_family: c::AF_INET6 as u16,
                sin6_port: a.port().to_be(),
                sin6_flowinfo: a.flowinfo().to_be(),
                sin6_addr: a.ip().octets(),
                sin6_scope_id: a.scope_id(),
            };
            // SAFETY: `SockaddrIn6` is repr(C), Copy, 28 bytes without padding.
            let bytes: [u8; 28] = unsafe { std::mem::transmute(sa) };
            out.copy_from_slice(&bytes);
            28
        }
    }
}

/// Room for any socket address Winsock returns (`SOCKADDR_STORAGE`).
#[cfg(feature = "udp")]
#[repr(C, align(8))]
struct AddrBuf([u8; 128]);

/// Decodes an IPv4 or IPv6 socket address written by Winsock.
#[cfg(feature = "udp")]
fn decode_addr(b: &[u8; 128], len: i32) -> Option<SocketAddr> {
    let family = i32::from(u16::from_ne_bytes([b[0], b[1]]));
    let port = u16::from_be_bytes([b[2], b[3]]);
    if family == c::AF_INET && len >= 16 {
        let ip = std::net::Ipv4Addr::new(b[4], b[5], b[6], b[7]);
        Some(SocketAddr::from((ip, port)))
    } else if family == c::AF_INET6 && len >= 28 {
        let mut octets = [0u8; 16];
        octets.copy_from_slice(&b[8..24]);
        let flow = u32::from_be_bytes([b[4], b[5], b[6], b[7]]);
        let scope = u32::from_ne_bytes([b[24], b[25], b[26], b[27]]);
        Some(SocketAddr::V6(std::net::SocketAddrV6::new(
            std::net::Ipv6Addr::from(octets),
            port,
            flow,
            scope,
        )))
    } else {
        None
    }
}

/// Creates and binds a UDP socket: not inheritable, `SO_EXCLUSIVEADDRUSE` so no
/// other process can bind the port, `IPV6_V6ONLY` as asked, and ICMP "port
/// unreachable" and "time exceeded" reports switched off (`SIO_UDP_CONNRESET`,
/// `SIO_UDP_NETRESET`), which would otherwise fail the next receive of an
/// unconnected socket.
#[cfg(feature = "udp")]
pub(crate) fn udp_bind(addr: SocketAddr, ipv6_only: bool) -> io::Result<std::net::UdpSocket> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Socket)?;
    startup();
    let af = if addr.is_ipv6() {
        c::AF_INET6
    } else {
        c::AF_INET
    };
    // SAFETY: as in `tcp_socket`.
    let s = unsafe {
        WSASocketW(
            af,
            c::SOCK_DGRAM,
            c::IPPROTO_UDP,
            std::ptr::null_mut(),
            0,
            c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
        )
    };
    if s == c::INVALID_SOCKET {
        return Err(last_error());
    }
    // SAFETY: `s` was just created by WSASocketW, is open, and is owned by no one else.
    let owned = unsafe { OwnedSocket::from_raw_socket(s as RawSocket) };
    set_int(owned.as_socket(), c::SOL_SOCKET, c::SO_EXCLUSIVEADDRUSE, 1)?;
    if addr.is_ipv6() {
        set_int(
            owned.as_socket(),
            c::IPPROTO_IPV6,
            c::IPV6_V6ONLY,
            i32::from(ipv6_only),
        )?;
    }
    for code in [c::SIO_UDP_CONNRESET, c::SIO_UDP_NETRESET] {
        let off: i32 = 0;
        let mut returned = 0u32;
        // SAFETY: both codes take a BOOL input and no output; `off` and
        // `returned` are live locals; no overlapped IO.
        cvt(unsafe {
            WSAIoctl(
                raw(owned.as_socket()),
                code,
                (&raw const off).cast::<c_void>(),
                size_of::<i32>() as u32,
                std::ptr::null_mut(),
                0,
                &raw mut returned,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        })?;
    }
    bind_to(owned.as_socket(), addr)?;
    Ok(std::net::UdpSocket::from(owned))
}

/// One datagram: its length, its source, and whether it was cut to fit `buf`
/// (`WSAEMSGSIZE`; the length is then the bytes copied).
#[cfg(feature = "udp")]
pub(crate) fn udp_recv_from(
    sock: Sock<'_>,
    buf: &mut [u8],
) -> io::Result<(usize, SocketAddr, bool)> {
    #[cfg(any(test, net_io_shim))]
    let buf = match super::shim::io(super::shim::Op::Recv, buf.len())? {
        Some(n) => &mut buf[..n],
        None => buf,
    };
    let mut addr = AddrBuf([0; 128]);
    let mut addr_len = 128i32;
    let len = i32::try_from(buf.len()).unwrap_or(i32::MAX);
    // SAFETY: `buf` is writable for `len` bytes and `addr` for `addr_len`; both
    // live for the call; `sock` is open.
    let n = unsafe {
        recvfrom(
            raw(sock),
            buf.as_mut_ptr(),
            len,
            0,
            addr.0.as_mut_ptr().cast::<c_void>(),
            &raw mut addr_len,
        )
    };
    let (n, truncated) = if n == c::SOCKET_ERROR {
        let e = last_error();
        if e.raw_os_error() != Some(errno::WSAEMSGSIZE) {
            return Err(e);
        }
        (len.unsigned_abs() as usize, true)
    } else {
        (n.unsigned_abs() as usize, false)
    };
    match decode_addr(&addr.0, addr_len) {
        Some(from) => Ok((n, from, truncated)),
        None => Err(io::Error::from(io::ErrorKind::InvalidData)),
    }
}

/// A new TCP socket: overlapped (needed for completion ports and for hand-off
/// receivers) and not inheritable by child processes.
pub(crate) fn tcp_socket(v6: bool) -> io::Result<OwnedSocket> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Socket)?;
    startup();
    let af = if v6 { c::AF_INET6 } else { c::AF_INET };
    // SAFETY: WSASocketW with a null protocol-info pointer creates a new socket
    // from the plain integer arguments; it returns INVALID_SOCKET on failure.
    let s = unsafe {
        WSASocketW(
            af,
            c::SOCK_STREAM,
            c::IPPROTO_TCP,
            std::ptr::null_mut(),
            0,
            c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
        )
    };
    if s == c::INVALID_SOCKET {
        return Err(last_error());
    }
    // SAFETY: `s` was just created by WSASocketW, is open, and is owned by no one else.
    Ok(unsafe { OwnedSocket::from_raw_socket(s as RawSocket) })
}

/// Options set on a listening socket before `bind` and `listen`.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ListenParams {
    /// Not applied on Windows (see [`tcp_listener`]).
    #[allow(dead_code)]
    pub reuse_address: bool,
    pub reuse_port: bool,
    pub ipv6_only: bool,
    pub send_buffer: Option<u32>,
    pub receive_buffer: Option<u32>,
    pub backlog: u32,
    pub defer_accept: Option<Duration>,
    pub fast_open: Option<u32>,
    pub incoming_cpu: Option<u32>,
}

/// Creates, configures, binds, and listens, always with `SO_EXCLUSIVEADDRUSE`, so
/// no other socket can bind the same port. `reuse_address` is not applied: on
/// Unix it lets a restart bind while old connections linger, which an exclusive
/// socket on Windows already may (tested with an accepted connection still open),
/// while Windows `SO_REUSEADDR` would let another socket bind over a live listener
/// and take its connections.
pub(crate) fn tcp_listener(addr: SocketAddr, p: &ListenParams) -> io::Result<TcpListener> {
    if p.reuse_port {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "SO_REUSEPORT does not exist on Windows",
        ));
    }
    if p.defer_accept.is_some() || p.incoming_cpu.is_some() {
        return Err(io::Error::from(io::ErrorKind::Unsupported));
    }
    let s = tcp_socket(addr.is_ipv6())?;
    set_int(s.as_socket(), c::SOL_SOCKET, c::SO_EXCLUSIVEADDRUSE, 1)?;
    if addr.is_ipv6() {
        set_int(
            s.as_socket(),
            c::IPPROTO_IPV6,
            c::IPV6_V6ONLY,
            i32::from(p.ipv6_only),
        )?;
    }
    if let Some(n) = p.send_buffer {
        set_int(s.as_socket(), c::SOL_SOCKET, c::SO_SNDBUF, clamp_int(n))?;
    }
    if let Some(n) = p.receive_buffer {
        set_int(s.as_socket(), c::SOL_SOCKET, c::SO_RCVBUF, clamp_int(n))?;
    }
    bind_to(s.as_socket(), addr)?;
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Listen)?;
    // SAFETY: `s` is an open, bound stream socket.
    cvt(unsafe { listen(raw(s.as_socket()), backlog_arg(p.backlog)) })?;
    if p.fast_open.is_some() {
        set_int(s.as_socket(), c::IPPROTO_TCP, c::TCP_FASTOPEN, 1)?;
    }
    let listener = TcpListener::from(s);
    listener.set_nonblocking(true)?;
    Ok(listener)
}

/// Whether a file send was turned down, so the bytes must go by reading and writing.
pub(crate) fn send_file_refused(e: &io::Error) -> bool {
    e.kind() == io::ErrorKind::Unsupported
}

/// Bytes of `file` at `offset`. Windows moves the file's position, which no net-io
/// path relies on.
pub(crate) fn read_file_at(file: &std::fs::File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
    std::os::windows::fs::FileExt::seek_read(file, buf, offset)
}

/// Writes all of `buf` to `file` at `offset`. Windows moves the file's position.
pub(crate) fn write_file_at(
    file: &std::fs::File,
    mut buf: &[u8],
    mut offset: u64,
) -> io::Result<()> {
    while !buf.is_empty() {
        match std::os::windows::fs::FileExt::seek_write(file, buf, offset) {
            Ok(0) => return Err(io::Error::from(io::ErrorKind::WriteZero)),
            Ok(n) => {
                buf = &buf[n..];
                offset += n as u64;
            }
            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

/// Whether this OS can pin a thread.
pub(crate) const CAN_PIN: bool = true;

/// `GROUP_AFFINITY`.
#[repr(C)]
struct GroupAffinity {
    mask: usize,
    group: u16,
    reserved: [u16; 3],
}

/// Pins the calling thread to the `cpu`th processor, counting across processor groups.
pub(crate) fn pin_current_thread(cpu: usize) -> io::Result<()> {
    let mut left = cpu;
    // SAFETY: takes no pointers.
    let groups = unsafe { GetActiveProcessorGroupCount() };
    for group in 0..groups {
        // SAFETY: takes no pointers.
        let in_group = unsafe { GetActiveProcessorCount(group) } as usize;
        if left < in_group {
            let affinity = GroupAffinity {
                mask: 1usize << left,
                group,
                reserved: [0; 3],
            };
            // SAFETY: the pseudo handle needs no closing; `affinity` lives for the call,
            // and the previous-affinity pointer may be null.
            let ok = unsafe {
                SetThreadGroupAffinity(
                    GetCurrentThread(),
                    &raw const affinity,
                    std::ptr::null_mut(),
                )
            };
            if ok == 0 {
                return Err(io::Error::last_os_error());
            }
            return Ok(());
        }
        left -= in_group;
    }
    Err(io::Error::from(io::ErrorKind::InvalidInput))
}

/// `TCP_MAXRT`: how long sent bytes may stay unacknowledged, in whole seconds.
pub(crate) fn set_user_timeout(sock: Sock<'_>, timeout: Duration) -> io::Result<()> {
    set_int(sock, c::IPPROTO_TCP, c::TCP_MAXRT, secs(timeout).max(1))
}

/// Binds `sock` to `addr`.
pub(crate) fn bind_to(sock: Sock<'_>, addr: SocketAddr) -> io::Result<()> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Bind)?;
    let mut buf = [0u8; 28];
    let len = encode_addr(addr, &mut buf);
    // SAFETY: `buf` holds a valid SOCKADDR of `len` bytes and lives for the call.
    cvt(unsafe { bind(raw(sock), buf.as_ptr().cast::<c_void>(), len) }).map(drop)
}

/// Starts a non-blocking connect. `Ok(true)` when it is in progress.
pub(crate) fn connect_start(sock: Sock<'_>, addr: SocketAddr) -> io::Result<bool> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Connect)?;
    let mut buf = [0u8; 28];
    let len = encode_addr(addr, &mut buf);
    // SAFETY: as in `bind_to`; the socket is non-blocking, so connect returns at once.
    let ret = unsafe { connect(raw(sock), buf.as_ptr().cast::<c_void>(), len) };
    if ret == 0 {
        return Ok(false);
    }
    let err = last_error();
    if err.raw_os_error() == Some(c::WSAEWOULDBLOCK) {
        Ok(true)
    } else {
        Err(err)
    }
}

/// The pending error of a socket (`SO_ERROR`).
pub(crate) fn take_error(sock: Sock<'_>) -> io::Result<Option<io::Error>> {
    let code = get_int(sock, c::SOL_SOCKET, c::SO_ERROR)?;
    Ok((code != 0).then(|| io::Error::from_raw_os_error(code)))
}

/// Whether `sock` is a listening stream socket.
pub(crate) fn is_listening_stream(sock: Sock<'_>) -> io::Result<bool> {
    let listening = get_int(sock, c::SOL_SOCKET, c::SO_ACCEPTCONN)? != 0;
    let stream = get_int(sock, c::SOL_SOCKET, c::SO_TYPE)? == c::SOCK_STREAM;
    Ok(listening && stream)
}

/// Identifies a socket handed to this process: a listening TCP stream socket
/// and the address it is bound to.
pub(crate) fn listener_kind(sock: Sock<'_>) -> Result<super::SockKind, super::KindError> {
    use super::{KindError, SockKind};
    let ty = match get_int(sock, c::SOL_SOCKET, c::SO_TYPE) {
        Ok(t) => t,
        Err(e) if e.raw_os_error() == Some(errno::WSAENOTSOCK) => {
            return Err(KindError::NotASocket);
        }
        Err(e) => return Err(KindError::Os(e)),
    };
    if ty != c::SOCK_STREAM {
        return Err(KindError::WrongKind);
    }
    if get_int(sock, c::SOL_SOCKET, c::SO_ACCEPTCONN).map_err(KindError::Os)? == 0 {
        return Err(KindError::NotListening);
    }
    // SAFETY: the socket is open for the call; `ManuallyDrop` keeps this
    // temporary `TcpListener` from closing a socket it does not own.
    let view =
        std::mem::ManuallyDrop::new(unsafe { TcpListener::from_raw_socket(sock.as_raw_socket()) });
    match view.local_addr() {
        Ok(a) => Ok(SockKind::Tcp(a)),
        Err(e) if e.kind() == io::ErrorKind::InvalidInput => Err(KindError::WrongKind),
        Err(e) => Err(KindError::Os(e)),
    }
}

/// Accepts one connection and makes it non-inheritable. An accepted socket takes
/// its inheritance from how the listener was created, not from the listener
/// handle's flag: from a listener created with `WSA_FLAG_NO_HANDLE_INHERIT` (std's,
/// net-io's, and one made from a hand-off description of either) it is never
/// inheritable, so the call below changes nothing. From a listener someone else
/// created inheritable (through `TcpListener::from_std`), it is inheritable until
/// the call below, a window of microseconds in which a process started elsewhere
/// with handle inheritance can get it. Closing that window needs `AcceptEx` into a
/// socket made non-inheritable first, on its own overlapped path (D-016 keeps
/// listeners off the completion ports).
pub(crate) fn accept(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Accept)?;
    let (stream, peer) = listener.accept()?;
    // SAFETY: the handle is the accepted socket, open for the call; clearing
    // HANDLE_FLAG_INHERIT is SetHandleInformation's documented use.
    let ok = unsafe {
        SetHandleInformation(
            stream.as_raw_socket() as *mut c_void,
            c::HANDLE_FLAG_INHERIT,
            0,
        )
    };
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    stream.set_nonblocking(true)?;
    Ok((stream, peer))
}

/// Configures a dialed stream for net-io's Windows IO model: non-blocking,
/// every wait in `WSAPoll` (already non-blocking from the connect).
pub(crate) fn prepare_dialed(_stream: &TcpStream) -> io::Result<()> {
    Ok(())
}

/// Whether reads wait in `WSAPoll` first (Windows) or block in `recv` (Unix).
pub(crate) const WAIT_BEFORE_RECV: bool = true;

/// One receive on a non-blocking socket: `WouldBlock` when nothing is there.
pub(crate) fn recv(stream: &super::Stream, buf: &mut [u8]) -> io::Result<usize> {
    retry_interrupted(|| {
        #[cfg(any(test, net_io_shim))]
        let buf = match super::shim::io(super::shim::Op::Recv, buf.len())? {
            Some(n) => &mut buf[..n],
            None => &mut *buf,
        };
        stream.read(buf)
    })
}

/// Not used on Windows: waits carry the timeout instead.
pub(crate) fn set_recv_timeout(
    _stream: &super::Stream,
    _timeout: Option<Duration>,
) -> io::Result<()> {
    Ok(())
}

/// One send on a non-blocking socket: `WouldBlock` when the buffer is full.
pub(crate) fn send(stream: &super::Stream, buf: &[u8]) -> io::Result<usize> {
    retry_interrupted(|| {
        #[cfg(any(test, net_io_shim))]
        let buf = match super::shim::io(super::shim::Op::Send, buf.len())? {
            Some(n) => &buf[..n],
            None => buf,
        };
        stream.write(buf)
    })
}

/// The largest number of slices passed to one vectored send.
pub(crate) const MAX_SLICES: usize = 64;

/// One vectored send on a non-blocking socket (`WSASend` through std).
pub(crate) fn send_vectored(stream: &super::Stream, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
    let bufs = &bufs[..bufs.len().min(MAX_SLICES)];
    retry_interrupted(|| {
        #[cfg(any(test, net_io_shim))]
        if let Some(n) = super::shim::io(super::shim::Op::Send, bufs.iter().map(|b| b.len()).sum())?
        {
            let first = bufs
                .iter()
                .find(|b| !b.is_empty())
                .map_or(&[][..], |b| &b[..]);
            return stream.write(&first[..n.min(first.len())]);
        }
        stream.write_vectored(bufs)
    })
}

/// The longest AF_UNIX path, terminator included.
#[cfg(feature = "local")]
pub(crate) const UNIX_PATH_MAX: usize = 108;

#[cfg(feature = "local")]
const SIO_AF_UNIX_GETPEERPID: u32 = 0x5800_0100;

/// A `sockaddr_un`, and its length.
#[cfg(feature = "local")]
fn unix_addr(path: &[u8]) -> io::Result<([u8; 2 + UNIX_PATH_MAX], i32)> {
    if path.is_empty() || path.len() >= UNIX_PATH_MAX || path.contains(&0) {
        return Err(io::Error::from(io::ErrorKind::InvalidInput));
    }
    let mut addr = [0u8; 2 + UNIX_PATH_MAX];
    addr[..2].copy_from_slice(&1u16.to_ne_bytes());
    addr[2..2 + path.len()].copy_from_slice(path);
    Ok((addr, (2 + path.len() + 1) as i32))
}

/// A new AF_UNIX stream socket.
#[cfg(feature = "local")]
pub(crate) fn unix_socket() -> io::Result<OwnedSocket> {
    startup();
    // SAFETY: a null protocol-info pointer creates a socket from the plain integers.
    let s = unsafe {
        WSASocketW(
            c::AF_UNIX,
            c::SOCK_STREAM,
            0,
            std::ptr::null_mut(),
            0,
            c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
        )
    };
    if s == c::INVALID_SOCKET {
        return Err(last_error());
    }
    // SAFETY: `s` was just created, is open, and is owned by no one else.
    Ok(unsafe { OwnedSocket::from_raw_socket(s as RawSocket) })
}

/// Binds and listens; the path names a new socket file.
#[cfg(feature = "local")]
pub(crate) fn unix_bind(sock: Sock<'_>, path: &[u8], backlog: u32) -> io::Result<()> {
    let (addr, len) = unix_addr(path)?;
    // SAFETY: `addr` holds a valid SOCKADDR_UN of `len` bytes and lives for the call.
    cvt(unsafe { bind(raw(sock), addr.as_ptr().cast(), len) })?;
    // SAFETY: `sock` is an open, bound stream socket.
    cvt(unsafe { listen(raw(sock), backlog_arg(backlog)) })?;
    Ok(())
}

/// Connects to the socket at `path`.
#[cfg(feature = "local")]
pub(crate) fn unix_connect(sock: Sock<'_>, path: &[u8]) -> io::Result<()> {
    let (addr, len) = unix_addr(path)?;
    // SAFETY: as in `unix_bind`.
    cvt(unsafe { connect(raw(sock), addr.as_ptr().cast(), len) }).map(drop)
}

/// One accept on a non-blocking AF_UNIX listener. std's `accept` cannot decode the
/// peer's address, so this asks for none. The listener comes from `unix_socket`,
/// so the accepted socket is never inheritable (see [`accept`]); the flag is
/// cleared anyway, for a listener adopted from elsewhere.
#[cfg(feature = "local")]
pub(crate) fn unix_accept(listener: Sock<'_>) -> io::Result<OwnedSocket> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Accept)?;
    // SAFETY: `listener` is open; no address is asked for.
    let s = unsafe { accept_raw(raw(listener), std::ptr::null_mut(), std::ptr::null_mut()) };
    if s == c::INVALID_SOCKET {
        return Err(last_error());
    }
    // SAFETY: `s` was just accepted, is open, and is owned by no one else.
    let owned = unsafe { OwnedSocket::from_raw_socket(s as RawSocket) };
    // SAFETY: the handle is open; clearing the flag is the call's documented use.
    let ok = unsafe { SetHandleInformation(s as *mut c_void, c::HANDLE_FLAG_INHERIT, 0) };
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(owned)
}

#[cfg(feature = "local")]
const IO_REPARSE_TAG_AF_UNIX: u32 = 0x8000_0023;
#[cfg(feature = "local")]
const FILE_ATTRIBUTE_TAG_INFO: i32 = 9;
#[cfg(feature = "local")]
const FILE_READ_ATTRIBUTES: u32 = 0x80;
#[cfg(feature = "local")]
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
#[cfg(feature = "local")]
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;

/// `FILE_ATTRIBUTE_TAG_INFO`.
#[cfg(feature = "local")]
#[repr(C)]
#[derive(Default)]
struct FileAttributeTagInfo {
    attributes: u32,
    tag: u32,
}

#[cfg(feature = "local")]
#[link(name = "kernel32")]
unsafe extern "system" {
    fn GetFileInformationByHandleEx(
        file: *mut c_void,
        class: i32,
        info: *mut c_void,
        len: u32,
    ) -> i32;
}

/// Whether `path` is an AF_UNIX socket file: a reparse point with the tag
/// `IO_REPARSE_TAG_AF_UNIX`, and not any other kind (a cloud placeholder, an app
/// alias, a deduplicated file). The file itself is opened, not what it points to.
#[cfg(feature = "local")]
pub(crate) fn is_unix_socket_file(path: &std::path::Path) -> io::Result<bool> {
    use std::os::windows::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .access_mode(FILE_READ_ATTRIBUTES)
        .share_mode(7)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
        .open(path)?;
    let mut info = FileAttributeTagInfo::default();
    // SAFETY: the handle is open; `info` is writable for the length given.
    let ok = unsafe {
        GetFileInformationByHandleEx(
            file.as_raw_handle(),
            FILE_ATTRIBUTE_TAG_INFO,
            (&raw mut info).cast(),
            size_of::<FileAttributeTagInfo>() as u32,
        )
    };
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(info.tag == IO_REPARSE_TAG_AF_UNIX)
}

/// The process at the other end of an AF_UNIX connection.
#[cfg(feature = "local")]
pub(crate) fn unix_peer_pid(sock: Sock<'_>) -> io::Result<u32> {
    let (mut pid, mut returned) = (0u32, 0u32);
    // SAFETY: `pid` is writable for the stated length; no overlapped operation.
    cvt(unsafe {
        WSAIoctl(
            raw(sock),
            SIO_AF_UNIX_GETPEERPID,
            std::ptr::null(),
            0,
            (&raw mut pid).cast(),
            size_of::<u32>() as u32,
            &raw mut returned,
            std::ptr::null_mut(),
            std::ptr::null_mut(),
        )
    })?;
    Ok(pid)
}

/// How many bytes describe a socket for another process (`WSAPROTOCOL_INFOW`).
#[cfg(feature = "local")]
pub(crate) const SHARED_SOCKET: usize = size_of::<WsaProtocolInfo>();

/// Describes `sock` for the process `pid`; the description works there alone.
#[cfg(feature = "local")]
pub(crate) fn share_socket(sock: Sock<'_>, pid: u32) -> io::Result<[u8; SHARED_SOCKET]> {
    let mut out = [0u8; SHARED_SOCKET];
    let mut info = std::mem::MaybeUninit::<WsaProtocolInfo>::zeroed();
    // SAFETY: `info` is writable for its size, and `sock` is open for the call.
    cvt(unsafe { WSADuplicateSocketW(raw(sock), pid, info.as_mut_ptr()) })?;
    // SAFETY: the call filled it, and every field is plain data.
    let bytes = unsafe { std::slice::from_raw_parts(info.as_ptr().cast::<u8>(), SHARED_SOCKET) };
    out.copy_from_slice(bytes);
    Ok(out)
}

/// Held while a socket made from a description is checked and claimed, so two
/// hand-offs that name one handle (a description used twice, in one frame or two)
/// cannot both see it unclaimed.
#[cfg(feature = "local")]
static CLAIMING: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// The socket a description from [`share_socket`] names, not inheritable.
/// `AlreadyExists` when it names a socket this process already owns, through an
/// earlier description or any other way: that one keeps its single owner, and
/// nothing is closed.
///
/// Windows makes the socket in this process when the sender describes it, and the
/// description names it by its handle value here, so a forged one can name any
/// socket the process holds; `WSASocketW` then returns that socket. A fresh
/// duplicate is inheritable (the sender's flag), while every socket net-io or std
/// makes is not, and adoption clears the flag: a socket that is not inheritable is
/// already owned here and is left alone. The flag is the claim. It belongs to the
/// handle, so when the owner closes the socket and Windows gives the value to a
/// new duplicate, that one is inheritable again and is taken: nothing about a
/// value outlives its socket. The check and the clear run under one lock.
#[cfg(feature = "local")]
pub(crate) fn socket_from_shared(blob: &[u8; SHARED_SOCKET]) -> io::Result<OwnedSocket> {
    startup();
    let mut info = std::mem::MaybeUninit::<WsaProtocolInfo>::uninit();
    // SAFETY: `info` has room for the bytes, and any bytes are a valid WsaProtocolInfo.
    unsafe {
        std::ptr::copy_nonoverlapping(blob.as_ptr(), info.as_mut_ptr().cast::<u8>(), SHARED_SOCKET);
    }
    let claiming = CLAIMING
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    // SAFETY: the structure is live for the call; the kernel checks what it holds.
    let s = unsafe {
        WSASocketW(
            FROM_PROTOCOL_INFO,
            FROM_PROTOCOL_INFO,
            FROM_PROTOCOL_INFO,
            info.as_mut_ptr().cast(),
            0,
            c::WSA_FLAG_OVERLAPPED | c::WSA_FLAG_NO_HANDLE_INHERIT,
        )
    };
    if s == c::INVALID_SOCKET {
        return Err(last_error());
    }
    let mut flags = 0u32;
    // SAFETY: `flags` is written during the call; a value that is not an open
    // handle fails it. Nothing here takes ownership of `s` yet.
    if unsafe { GetHandleInformation(s as *mut c_void, &raw mut flags) } == 0 {
        return Err(io::Error::last_os_error());
    }
    if flags & c::HANDLE_FLAG_INHERIT == 0 {
        return Err(io::Error::from(io::ErrorKind::AlreadyExists));
    }
    // SAFETY: `s` is open and inheritable, so the sender's duplicate made it and
    // nothing else in the process owns it; the lock keeps another adoption from
    // reaching this point with the same handle before the flag is cleared.
    let sock = unsafe { OwnedSocket::from_raw_socket(s as RawSocket) };
    // The flag passed above does not reach a socket made from a description (the
    // sender's duplicate is inheritable), so it is cleared here: this is the claim.
    // SAFETY: the handle is open; clearing the flag is the call's documented use.
    if unsafe { SetHandleInformation(s as *mut c_void, c::HANDLE_FLAG_INHERIT, 0) } == 0 {
        let e = io::Error::last_os_error();
        drop(sock);
        return Err(e);
    }
    drop(claiming);
    Ok(sock)
}

#[cfg(any(test, feature = "local"))]
#[link(name = "kernel32")]
unsafe extern "system" {
    fn GetHandleInformation(handle: *mut c_void, flags: *mut u32) -> i32;
}

/// Whether a process this one starts with handle inheritance would get `sock`.
#[cfg(test)]
pub(crate) fn is_inheritable(sock: Sock<'_>) -> io::Result<bool> {
    let mut flags = 0u32;
    // SAFETY: the socket is open for the call; `flags` is written during it.
    if unsafe { GetHandleInformation(raw(sock) as *mut c_void, &raw mut flags) } == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(flags & c::HANDLE_FLAG_INHERIT != 0)
}

/// Bytes from the OS's preferred random source.
#[cfg(feature = "local")]
pub(crate) fn random_bytes(out: &mut [u8]) -> io::Result<()> {
    // SAFETY: `out` is writable for its length; a null algorithm with this flag means
    // the system's preferred source.
    let status = unsafe {
        BCryptGenRandom(
            std::ptr::null_mut(),
            out.as_mut_ptr(),
            u32::try_from(out.len()).unwrap_or(u32::MAX),
            BCRYPT_USE_SYSTEM_PREFERRED_RNG,
        )
    };
    if status != 0 {
        return Err(io::Error::other("BCryptGenRandom failed"));
    }
    Ok(())
}

/// Waits until any of `socks` (at most 64) can write or has failed; bit `i` of the
/// result stands for `socks[i]`, and 0 means the timeout passed. `WSAPoll` reports a
/// refused connect through `POLLERR` and `POLLHUP`, which every call watches.
pub(crate) fn wait_writable(socks: &[Sock<'_>], timeout: Duration) -> io::Result<u64> {
    let mut fds: Vec<WsaPollFd> = socks
        .iter()
        .map(|s| WsaPollFd {
            fd: raw(*s),
            events: c::POLLWRNORM,
            revents: 0,
        })
        .collect();
    let ms = poll_millis(Some(timeout));
    // SAFETY: `fds` is a live slice of initialized WSAPOLLFD structs whose sockets are
    // open for the call (borrowed in `socks`).
    retry_interrupted(|| cvt(unsafe { WSAPoll(fds.as_mut_ptr(), fds.len() as u32, ms) }))?;
    Ok(fds
        .iter()
        .enumerate()
        .filter(|(_, f)| f.revents != 0)
        .fold(0, |mask, (i, _)| mask | (1 << i)))
}

/// Waits until `sock` is ready for `interest`, `wake` fires, or `timeout` passes.
pub(crate) fn wait(
    sock: Sock<'_>,
    interest: Interest,
    wake: Option<&Wake>,
    timeout: Option<Duration>,
) -> io::Result<Ready> {
    #[cfg(any(test, net_io_shim))]
    super::shim::check(super::shim::Op::Wait)?;
    let events = match interest {
        Interest::Read => c::POLLRDNORM,
        Interest::Write => c::POLLWRNORM,
    };
    let mut fds = [
        WsaPollFd {
            fd: raw(sock),
            events,
            revents: 0,
        },
        WsaPollFd {
            fd: wake.map_or(c::INVALID_SOCKET, |w| w.socket.as_raw_socket() as Socket),
            events: c::POLLRDNORM,
            revents: 0,
        },
    ];
    let nfds: u32 = if wake.is_some() { 2 } else { 1 };
    let ms = poll_millis(timeout);
    // SAFETY: `fds` is a live array of `nfds` initialized WSAPOLLFD structs whose
    // sockets are open for the call.
    let n = match retry_interrupted(|| cvt(unsafe { WSAPoll(fds.as_mut_ptr(), nfds, ms) })) {
        Ok(n) => n,
        // A kill's `CancelIoEx` ended the wait; the kill flag says why.
        Err(e) if e.raw_os_error() == Some(c::WSAEINTR) => return Ok(Ready::Woken),
        Err(e) => return Err(e),
    };
    if n == 0 {
        return Ok(Ready::TimedOut);
    }
    if fds[1].revents != 0 {
        if let Some(w) = wake {
            w.drain();
        }
        return Ok(Ready::Woken);
    }
    Ok(Ready::Socket)
}

/// Waits on the wake channel alone (or until `timeout`). `true` when woken.
pub(crate) fn wait_wake(wake: &Wake, timeout: Option<Duration>) -> io::Result<bool> {
    let mut fds = [WsaPollFd {
        fd: wake.socket.as_raw_socket() as Socket,
        events: c::POLLRDNORM,
        revents: 0,
    }];
    let ms = poll_millis(timeout);
    // SAFETY: `fds` holds one initialized WSAPOLLFD whose socket `wake` owns for the call.
    let n = retry_interrupted(|| cvt(unsafe { WSAPoll(fds.as_mut_ptr(), 1, ms) }))?;
    if n > 0 {
        wake.drain();
    }
    Ok(n > 0)
}

/// Not used on Windows: `shutdown` does not wake a blocked receive there (spike S-2),
/// and net-io's Windows waits use wake sockets instead.
///
/// # Safety
///
/// `raw` must be an open socket for the call.
pub(crate) unsafe fn shutdown_read_raw(raw: RawSock) {
    // Not found is the usual answer: only a pipe's or a reactor's IO is overlapped.
    // SAFETY: `raw` is open, by this function's contract; null means all operations.
    let _ = unsafe { CancelIoEx(raw as usize as *mut c_void, std::ptr::null_mut()) };
}

fn clamp_int(n: u32) -> i32 {
    i32::try_from(n).unwrap_or(i32::MAX)
}

/// The `listen` backlog for `n` pending connections. Windows takes a plain number
/// as at most 200; a backlog past that is asked for as `SOMAXCONN_HINT(n)` (the
/// negative of `n`), which Windows holds to 200 to 65,535 (D-175).
fn backlog_arg(n: u32) -> i32 {
    const PLAIN_MAX: u32 = 200;
    const HINT_MAX: u32 = 65_535;
    if n <= PLAIN_MAX {
        clamp_int(n)
    } else {
        -clamp_int(n.min(HINT_MAX))
    }
}

/// Linger: `None` = off, `Some(0)` = abortive, `Some(d)` = wait up to `d` seconds.
pub(crate) fn set_linger(sock: Sock<'_>, linger: Option<Duration>) -> io::Result<()> {
    let value = Linger {
        l_onoff: u16::from(linger.is_some()),
        // Whole seconds, rounded up: a sub-second linger truncated to 0 would reset
        // the connection, the opposite of what was asked. Zero stays the reset.
        l_linger: linger.map_or(0, |d| {
            let secs = d.as_secs() + u64::from(d.subsec_nanos() > 0);
            u16::try_from(secs).unwrap_or(u16::MAX)
        }),
    };
    // SAFETY: `value` is a live repr(C) LINGER and the length is its size.
    let ret = unsafe {
        setsockopt(
            raw(sock),
            c::SOL_SOCKET,
            c::SO_LINGER,
            (&raw const value).cast::<u8>(),
            size_of::<Linger>() as i32,
        )
    };
    cvt(ret).map(drop)
}

/// The linger setting.
pub(crate) fn linger(sock: Sock<'_>) -> io::Result<Option<Duration>> {
    let mut value = Linger {
        l_onoff: 0,
        l_linger: 0,
    };
    let mut len = size_of::<Linger>() as i32;
    // SAFETY: `value` and `len` are live locals; `len` holds the struct's size.
    let ret = unsafe {
        getsockopt(
            raw(sock),
            c::SOL_SOCKET,
            c::SO_LINGER,
            (&raw mut value).cast::<u8>(),
            &raw mut len,
        )
    };
    cvt(ret)?;
    Ok((value.l_onoff != 0).then(|| Duration::from_secs(u64::from(value.l_linger))))
}

/// Keepalive (Windows 10 1709+ for idle and interval, 1703+ for count).
pub(crate) fn set_keepalive(
    sock: Sock<'_>,
    keepalive: Option<(Duration, Duration, u32)>,
) -> io::Result<()> {
    match keepalive {
        None => set_int(sock, c::SOL_SOCKET, c::SO_KEEPALIVE, 0),
        Some((idle, interval, count)) => {
            set_int(sock, c::SOL_SOCKET, c::SO_KEEPALIVE, 1)?;
            set_int(sock, c::IPPROTO_TCP, c::TCP_KEEPIDLE, secs(idle))?;
            set_int(sock, c::IPPROTO_TCP, c::TCP_KEEPINTVL, secs(interval))?;
            set_int(sock, c::IPPROTO_TCP, c::TCP_KEEPCNT, clamp_int(count))
        }
    }
}

/// The keepalive setting.
pub(crate) fn keepalive(sock: Sock<'_>) -> io::Result<Option<(Duration, Duration, u32)>> {
    if get_int(sock, c::SOL_SOCKET, c::SO_KEEPALIVE)? == 0 {
        return Ok(None);
    }
    let idle = get_int(sock, c::IPPROTO_TCP, c::TCP_KEEPIDLE)?;
    let interval = get_int(sock, c::IPPROTO_TCP, c::TCP_KEEPINTVL)?;
    let count = get_int(sock, c::IPPROTO_TCP, c::TCP_KEEPCNT)?;
    Ok(Some((
        Duration::from_secs(u64::try_from(idle).unwrap_or(0)),
        Duration::from_secs(u64::try_from(interval).unwrap_or(0)),
        u32::try_from(count).unwrap_or(0),
    )))
}

fn secs(d: Duration) -> i32 {
    i32::try_from(d.as_secs().max(1)).unwrap_or(i32::MAX)
}

/// Sets `SO_SNDBUF` and returns the effective value.
pub(crate) fn set_send_buffer(sock: Sock<'_>, bytes: u32) -> io::Result<u32> {
    set_int(sock, c::SOL_SOCKET, c::SO_SNDBUF, clamp_int(bytes))?;
    send_buffer(sock)
}

/// The effective `SO_SNDBUF`.
pub(crate) fn send_buffer(sock: Sock<'_>) -> io::Result<u32> {
    Ok(u32::try_from(get_int(sock, c::SOL_SOCKET, c::SO_SNDBUF)?).unwrap_or(0))
}

/// Sets `SO_RCVBUF` and returns the effective value.
pub(crate) fn set_receive_buffer(sock: Sock<'_>, bytes: u32) -> io::Result<u32> {
    set_int(sock, c::SOL_SOCKET, c::SO_RCVBUF, clamp_int(bytes))?;
    receive_buffer(sock)
}

/// The effective `SO_RCVBUF`.
pub(crate) fn receive_buffer(sock: Sock<'_>) -> io::Result<u32> {
    Ok(u32::try_from(get_int(sock, c::SOL_SOCKET, c::SO_RCVBUF)?).unwrap_or(0))
}

/// `TCP_NODELAY`.
pub(crate) fn set_nodelay(sock: Sock<'_>, on: bool) -> io::Result<()> {
    set_int(sock, c::IPPROTO_TCP, c::TCP_NODELAY, i32::from(on))
}

/// `TCP_NODELAY`.
pub(crate) fn nodelay(sock: Sock<'_>) -> io::Result<bool> {
    Ok(get_int(sock, c::IPPROTO_TCP, c::TCP_NODELAY)? != 0)
}

/// `IP_TTL` or `IPV6_UNICAST_HOPS`.
pub(crate) fn set_ttl(sock: Sock<'_>, v6: bool, hops: u8) -> io::Result<()> {
    if v6 {
        set_int(sock, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS, i32::from(hops))
    } else {
        set_int(sock, c::IPPROTO_IP, c::IP_TTL, i32::from(hops))
    }
}

/// `IP_TTL` or `IPV6_UNICAST_HOPS`.
pub(crate) fn ttl(sock: Sock<'_>, v6: bool) -> io::Result<u8> {
    let v = if v6 {
        get_int(sock, c::IPPROTO_IPV6, c::IPV6_UNICAST_HOPS)?
    } else {
        get_int(sock, c::IPPROTO_IP, c::IP_TTL)?
    };
    Ok(u8::try_from(v).unwrap_or(u8::MAX))
}

/// Socket handles are not drawn from a small per-process table on Windows.
pub(crate) fn descriptor_limit() -> Option<u64> {
    None
}

/// A wake-up channel: a loopback UDP socket connected to itself, and an event for
/// the waits that cannot take a socket (named pipes).
#[derive(Debug)]
pub(crate) struct Wake {
    socket: UdpSocket,
    event: OwnedHandle,
    thread: std::sync::OnceLock<std::thread::Thread>,
}

impl Wake {
    pub(crate) fn new() -> io::Result<Wake> {
        let socket = UdpSocket::bind("127.0.0.1:0")?;
        socket.connect(socket.local_addr()?)?;
        socket.set_nonblocking(true)?;
        // SAFETY: no attributes, no name; an auto-reset event, not signaled.
        let raw = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
        if raw.is_null() {
            return Err(io::Error::last_os_error());
        }
        Ok(Wake {
            socket,
            // SAFETY: `raw` was just returned, is open, and has no other owner.
            event: unsafe { OwnedHandle::from_raw_handle(raw) },
            thread: std::sync::OnceLock::new(),
        })
    }

    /// Also unpark this thread on every wake (a worker parked without a socket).
    pub(crate) fn bind_thread(&self, thread: std::thread::Thread) {
        let _ = self.thread.set(thread);
    }

    /// Ends the current or next wait that includes this channel. Never blocks.
    pub(crate) fn wake(&self) {
        let _ = self.socket.send(&[1]);
        // SAFETY: the event is open while `self` lives.
        let _ = unsafe { SetEvent(self.event.as_raw_handle()) };
        if let Some(t) = self.thread.get() {
            t.unpark();
        }
    }

    fn drain(&self) {
        let mut buf = [0u8; 64];
        while self.socket.recv(&mut buf).is_ok() {}
    }

    /// The event a wait on a pipe includes.
    #[cfg(feature = "local")]
    pub(super) fn event_raw(&self) -> *mut c_void {
        self.event.as_raw_handle()
    }

    /// Consumes a wake seen through the event.
    #[cfg(feature = "local")]
    pub(super) fn take(&self) {
        self.drain();
    }
}

/// Signature checks for the layout tests: an extern declaration here and the
/// `windows-sys` one are both cast to an `extern "system"` function pointer, and
/// every argument and the result reduced to what the calling convention sees (an
/// integer of a size and signedness, or a pointer). Pointer types differ between
/// the two only in what they point to, which the convention does not see.
#[cfg(test)]
pub(super) mod abi {
    use std::mem::size_of;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub(crate) enum Shape {
        Int { bytes: usize, signed: bool },
        Ptr,
    }

    pub(crate) trait Arg {
        const SHAPE: Shape;
    }

    macro_rules! ints {
        ($($t:ty => $signed:expr),*) => {
            $(impl Arg for $t {
                const SHAPE: Shape = Shape::Int { bytes: size_of::<$t>(), signed: $signed };
            })*
        };
    }
    ints!(i8 => true, i16 => true, i32 => true, i64 => true, isize => true,
          u8 => false, u16 => false, u32 => false, u64 => false, usize => false);

    impl<T> Arg for *mut T {
        const SHAPE: Shape = Shape::Ptr;
    }

    impl<T> Arg for *const T {
        const SHAPE: Shape = Shape::Ptr;
    }

    /// `WSAIoctl`'s completion routine: a nullable function pointer.
    impl Arg for windows_sys::Win32::Networking::WinSock::LPWSAOVERLAPPED_COMPLETION_ROUTINE {
        const SHAPE: Shape = Shape::Ptr;
    }

    pub(crate) trait Sig {
        fn shape() -> Vec<Shape>;
    }

    macro_rules! sigs {
        ($($a:ident)*) => {
            impl<R: Arg, $($a: Arg),*> Sig for unsafe extern "system" fn($($a),*) -> R {
                fn shape() -> Vec<Shape> {
                    vec![$(<$a as Arg>::SHAPE,)* R::SHAPE]
                }
            }
        };
    }
    sigs!();
    sigs!(A);
    sigs!(A B);
    sigs!(A B C);
    sigs!(A B C D);
    sigs!(A B C D E);
    sigs!(A B C D E F);
    sigs!(A B C D E F G);
    sigs!(A B C D E F G H);
    sigs!(A B C D E F G H I);

    pub(crate) fn shape<F: Sig>(_: F) -> Vec<Shape> {
        F::shape()
    }

    /// Asserts that `$ours` and `$theirs`, each cast to a function pointer with as
    /// many arguments as there are `_`, have the same shape.
    macro_rules! same_abi {
        ($ours:path, $theirs:path, $($arg:tt)*) => {
            assert_eq!(
                $crate::sys::windows::abi::shape(
                    $ours as unsafe extern "system" fn($($arg)*) -> _
                ),
                $crate::sys::windows::abi::shape(
                    $theirs as unsafe extern "system" fn($($arg)*) -> _
                ),
                "{}",
                stringify!($ours)
            )
        };
    }
    pub(crate) use same_abi;

    /// The shapes tell arity, size, signedness, and pointers apart.
    #[test]
    fn test_shapes_tell_signatures_apart() {
        extern "system" fn a(_: i32, _: *mut u8) -> i32 {
            0
        }
        extern "system" fn b(_: u32, _: *const u16) -> i32 {
            0
        }
        extern "system" fn c(_: i64, _: usize) -> i32 {
            0
        }
        extern "system" fn d(_: i32, _: *const u32) -> i32 {
            0
        }
        extern "system" fn e(_: i32) -> i32 {
            0
        }
        let a = shape(a as unsafe extern "system" fn(_, _) -> _);
        let b = shape(b as unsafe extern "system" fn(_, _) -> _);
        let c = shape(c as unsafe extern "system" fn(_, _) -> _);
        let d = shape(d as unsafe extern "system" fn(_, _) -> _);
        let e = shape(e as unsafe extern "system" fn(_) -> _);
        assert_ne!(a, b, "signedness");
        assert_ne!(a, c, "size and pointer");
        assert_ne!(a, e, "arity");
        assert_eq!(a, d, "what a pointer points to is not seen");
    }
}

#[cfg(test)]
mod layout {
    //! Cross-checks the declarations above against `windows-sys` (a dev-dependency).
    use super::*;
    use windows_sys::Win32::Foundation as wf;
    use windows_sys::Win32::Networking::WinSock as ws;

    #[test]
    fn test_layout_constants_match_windows_sys() {
        assert_eq!(c::AF_INET as i64, ws::AF_INET as i64);
        assert_eq!(c::AF_INET6 as i64, ws::AF_INET6 as i64);
        assert_eq!(c::SOCK_STREAM as i64, ws::SOCK_STREAM as i64);
        assert_eq!(c::IPPROTO_IP as i64, ws::IPPROTO_IP as i64);
        assert_eq!(c::IPPROTO_TCP as i64, ws::IPPROTO_TCP as i64);
        assert_eq!(c::IPPROTO_IPV6 as i64, ws::IPPROTO_IPV6 as i64);
        assert_eq!(c::SOL_SOCKET as i64, ws::SOL_SOCKET as i64);
        assert_eq!(c::SO_ACCEPTCONN as i64, ws::SO_ACCEPTCONN as i64);
        assert_eq!(c::SO_REUSEADDR as i64, ws::SO_REUSEADDR as i64);
        assert_eq!(
            c::SO_EXCLUSIVEADDRUSE as i64,
            ws::SO_EXCLUSIVEADDRUSE as i64
        );
        assert_eq!(c::SO_KEEPALIVE as i64, ws::SO_KEEPALIVE as i64);
        assert_eq!(c::SO_LINGER as i64, ws::SO_LINGER as i64);
        assert_eq!(c::SO_SNDBUF as i64, ws::SO_SNDBUF as i64);
        assert_eq!(c::SO_RCVBUF as i64, ws::SO_RCVBUF as i64);
        assert_eq!(c::SO_ERROR as i64, ws::SO_ERROR as i64);
        assert_eq!(c::SO_TYPE as i64, ws::SO_TYPE as i64);
        assert_eq!(c::TCP_NODELAY as i64, ws::TCP_NODELAY as i64);
        assert_eq!(c::TCP_KEEPIDLE as i64, ws::TCP_KEEPIDLE as i64);
        assert_eq!(c::TCP_KEEPCNT as i64, ws::TCP_KEEPCNT as i64);
        assert_eq!(c::TCP_KEEPINTVL as i64, ws::TCP_KEEPINTVL as i64);
        assert_eq!(c::IP_TTL as i64, ws::IP_TTL as i64);
        assert_eq!(c::IPV6_UNICAST_HOPS as i64, ws::IPV6_UNICAST_HOPS as i64);
        assert_eq!(c::IPV6_V6ONLY as i64, ws::IPV6_V6ONLY as i64);
        assert_eq!(c::POLLRDNORM as i64, ws::POLLRDNORM as i64);
        assert_eq!(c::POLLWRNORM as i64, ws::POLLWRNORM as i64);
        assert_eq!(
            c::WSA_FLAG_OVERLAPPED as i64,
            ws::WSA_FLAG_OVERLAPPED as i64
        );
        assert_eq!(
            c::WSA_FLAG_NO_HANDLE_INHERIT as i64,
            ws::WSA_FLAG_NO_HANDLE_INHERIT as i64
        );
        assert_eq!(
            c::HANDLE_FLAG_INHERIT as i64,
            wf::HANDLE_FLAG_INHERIT as i64
        );
        assert_eq!(c::INVALID_SOCKET, ws::INVALID_SOCKET);
        assert_eq!(c::SOCKET_ERROR as i64, ws::SOCKET_ERROR as i64);
        assert_eq!(c::WSAEWOULDBLOCK as i64, ws::WSAEWOULDBLOCK as i64);
    }

    #[test]
    fn test_layout_errno_match_windows_sys() {
        use errno::*;
        assert_eq!(WSAEBADF as i64, ws::WSAEBADF as i64);
        assert_eq!(WSAEACCES as i64, ws::WSAEACCES as i64);
        assert_eq!(WSAEINVAL as i64, ws::WSAEINVAL as i64);
        assert_eq!(WSAEMFILE as i64, ws::WSAEMFILE as i64);
        assert_eq!(WSAENOTSOCK as i64, ws::WSAENOTSOCK as i64);
        assert_eq!(WSAEADDRINUSE as i64, ws::WSAEADDRINUSE as i64);
        assert_eq!(WSAEADDRNOTAVAIL as i64, ws::WSAEADDRNOTAVAIL as i64);
        assert_eq!(WSAENETUNREACH as i64, ws::WSAENETUNREACH as i64);
        assert_eq!(WSAENOBUFS as i64, ws::WSAENOBUFS as i64);
        assert_eq!(WSAETIMEDOUT as i64, ws::WSAETIMEDOUT as i64);
        assert_eq!(WSAECONNREFUSED as i64, ws::WSAECONNREFUSED as i64);
        assert_eq!(WSAEHOSTUNREACH as i64, ws::WSAEHOSTUNREACH as i64);
    }

    #[test]
    fn test_layout_structs_match_windows_sys() {
        assert_eq!(size_of::<SockaddrIn>(), size_of::<ws::SOCKADDR_IN>());
        assert_eq!(size_of::<SockaddrIn6>(), size_of::<ws::SOCKADDR_IN6>());
        assert_eq!(size_of::<Linger>(), size_of::<ws::LINGER>());
        assert_eq!(size_of::<WsaPollFd>(), size_of::<ws::WSAPOLLFD>());
        assert_eq!(size_of::<WsaData>(), size_of::<ws::WSADATA>());
        assert_eq!(
            std::mem::offset_of!(WsaPollFd, revents),
            std::mem::offset_of!(ws::WSAPOLLFD, revents)
        );
        assert_eq!(
            std::mem::offset_of!(WsaData, lp_vendor_info),
            std::mem::offset_of!(ws::WSADATA, lpVendorInfo)
        );
        assert_eq!(
            std::mem::offset_of!(SockaddrIn6, sin6_scope_id),
            std::mem::offset_of!(ws::SOCKADDR_IN6, Anonymous)
        );
    }

    #[cfg(feature = "local")]
    #[test]
    fn test_layout_socket_files_match_windows_sys() {
        use windows_sys::Win32::Storage::FileSystem as fs;
        assert_eq!(FILE_ATTRIBUTE_TAG_INFO, fs::FileAttributeTagInfo);
        assert_eq!(FILE_READ_ATTRIBUTES, fs::FILE_READ_ATTRIBUTES);
        assert_eq!(
            FILE_FLAG_OPEN_REPARSE_POINT,
            fs::FILE_FLAG_OPEN_REPARSE_POINT
        );
        assert_eq!(FILE_FLAG_BACKUP_SEMANTICS, fs::FILE_FLAG_BACKUP_SEMANTICS);
        assert_eq!(
            size_of::<FileAttributeTagInfo>(),
            size_of::<fs::FILE_ATTRIBUTE_TAG_INFO>()
        );
        assert_eq!(
            std::mem::offset_of!(FileAttributeTagInfo, tag),
            std::mem::offset_of!(fs::FILE_ATTRIBUTE_TAG_INFO, ReparseTag)
        );
        // `IO_REPARSE_TAG_AF_UNIX` is not in the enabled windows-sys features: a
        // socket file made here carries it.
        let path = std::env::temp_dir().join(format!("nio-tag-{}.sock", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let sock = unix_socket().unwrap();
        unix_bind(sock.as_socket(), path.to_str().unwrap().as_bytes(), 1).unwrap();
        assert!(is_unix_socket_file(&path).unwrap());
        drop(sock);
        std::fs::remove_file(&path).unwrap();
        std::fs::write(&path, b"x").unwrap();
        assert!(!is_unix_socket_file(&path).unwrap());
        std::fs::remove_file(&path).unwrap();
    }

    /// Accepted sockets are never inheritable when the listener was created
    /// without inheritance, even before `accept` clears the flag.
    #[test]
    fn test_accepted_sockets_start_non_inheritable() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let _client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
        let (stream, _) = listener.accept().unwrap();
        assert!(!is_inheritable(stream.as_socket()).unwrap());
    }

    #[cfg(feature = "local")]
    #[test]
    fn test_accepted_unix_sockets_start_non_inheritable() {
        let path = std::env::temp_dir().join(format!("nio-inh-{}.sock", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let bytes = path.to_str().unwrap().as_bytes();
        let listener = unix_socket().unwrap();
        unix_bind(listener.as_socket(), bytes, 1).unwrap();
        let client = unix_socket().unwrap();
        unix_connect(client.as_socket(), bytes).unwrap();
        // SAFETY: the listener is open; no address is asked for.
        let s = unsafe {
            accept_raw(
                raw(listener.as_socket()),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        assert_ne!(s, c::INVALID_SOCKET);
        // SAFETY: `s` was just accepted and is owned by no one else.
        let accepted = unsafe { OwnedSocket::from_raw_socket(s as RawSocket) };
        assert!(!is_inheritable(accepted.as_socket()).unwrap());
        drop((accepted, client, listener));
        let _ = std::fs::remove_file(&path);
    }

    #[cfg(feature = "udp")]
    #[test]
    fn test_layout_udp_matches_windows_sys() {
        assert_eq!(c::SOCK_DGRAM as i64, ws::SOCK_DGRAM as i64);
        assert_eq!(c::IPPROTO_UDP as i64, ws::IPPROTO_UDP as i64);
        assert_eq!(c::SIO_UDP_CONNRESET as i64, ws::SIO_UDP_CONNRESET as i64);
        assert_eq!(c::SIO_UDP_NETRESET as i64, ws::SIO_UDP_NETRESET as i64);
        assert_eq!(errno::WSAEMSGSIZE as i64, ws::WSAEMSGSIZE as i64);
        assert_eq!(errno::WSAENETRESET as i64, ws::WSAENETRESET as i64);
        assert!(size_of::<AddrBuf>() >= size_of::<ws::SOCKADDR_STORAGE>());
    }

    #[cfg(feature = "udp")]
    #[test]
    fn test_udp_recv_reports_truncation_and_source() {
        let a = udp_bind("127.0.0.1:0".parse().unwrap(), true).unwrap();
        let b = udp_bind("[::1]:0".parse().unwrap(), true).unwrap();
        let src = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
        src.send_to(&[1u8; 100], a.local_addr().unwrap()).unwrap();
        let mut small = [0u8; 10];
        let (n, from, truncated) = udp_recv_from(a.as_socket(), &mut small).unwrap();
        assert!(truncated);
        assert_eq!(n, 10);
        assert_eq!(from, src.local_addr().unwrap());
        let src6 = std::net::UdpSocket::bind("[::1]:0").unwrap();
        src6.send_to(&[], b.local_addr().unwrap()).unwrap();
        let (n, from, truncated) = udp_recv_from(b.as_socket(), &mut small).unwrap();
        assert_eq!((n, truncated), (0, false));
        assert_eq!(from, src6.local_addr().unwrap());
    }

    /// Every function declared in this file against its `windows-sys` declaration.
    #[test]
    fn test_layout_signatures_match_windows_sys() {
        use super::abi::same_abi;
        use windows_sys::Win32::System::{IO as io_sys, Performance as perf, Threading as th};
        same_abi!(WSAStartup, ws::WSAStartup, _, _);
        same_abi!(WSASocketW, ws::WSASocketW, _, _, _, _, _, _);
        same_abi!(bind, ws::bind, _, _, _);
        same_abi!(listen, ws::listen, _, _);
        same_abi!(connect, ws::connect, _, _, _);
        same_abi!(setsockopt, ws::setsockopt, _, _, _, _, _);
        same_abi!(getsockopt, ws::getsockopt, _, _, _, _, _);
        same_abi!(WSAPoll, ws::WSAPoll, _, _, _);
        same_abi!(WSAGetLastError, ws::WSAGetLastError,);
        same_abi!(SetHandleInformation, wf::SetHandleInformation, _, _, _);
        same_abi!(GetHandleInformation, wf::GetHandleInformation, _, _);
        same_abi!(
            GetActiveProcessorGroupCount,
            th::GetActiveProcessorGroupCount,
        );
        same_abi!(GetActiveProcessorCount, th::GetActiveProcessorCount, _);
        same_abi!(GetCurrentThread, th::GetCurrentThread,);
        same_abi!(SetThreadGroupAffinity, th::SetThreadGroupAffinity, _, _, _);
        same_abi!(CreateEventW, th::CreateEventW, _, _, _, _);
        same_abi!(SetEvent, th::SetEvent, _);
        same_abi!(CancelIoEx, io_sys::CancelIoEx, _, _);
        same_abi!(QueryPerformanceCounter, perf::QueryPerformanceCounter, _);
        same_abi!(
            QueryPerformanceFrequency,
            perf::QueryPerformanceFrequency,
            _
        );
        #[cfg(feature = "udp")]
        same_abi!(recvfrom, ws::recvfrom, _, _, _, _, _, _);
        #[cfg(any(feature = "udp", feature = "local"))]
        same_abi!(WSAIoctl, ws::WSAIoctl, _, _, _, _, _, _, _, _, _);
        #[cfg(feature = "local")]
        {
            use windows_sys::Win32::Security::Cryptography as crypt;
            use windows_sys::Win32::Storage::FileSystem as fs;
            same_abi!(accept_raw, ws::accept, _, _, _);
            same_abi!(WSADuplicateSocketW, ws::WSADuplicateSocketW, _, _, _);
            same_abi!(BCryptGenRandom, crypt::BCryptGenRandom, _, _, _, _);
            same_abi!(
                GetFileInformationByHandleEx,
                fs::GetFileInformationByHandleEx,
                _,
                _,
                _,
                _
            );
        }
    }

    /// Constants and layouts the tests above do not reach.
    #[test]
    fn test_layout_remaining_constants_and_offsets_match_windows_sys() {
        use std::mem::offset_of;
        use windows_sys::Win32::System::SystemInformation as si;
        assert_eq!(c::TCP_MAXRT as i64, ws::TCP_MAXRT as i64);
        assert_eq!(c::TCP_FASTOPEN as i64, ws::TCP_FASTOPEN as i64);
        assert_eq!(c::WSAEINTR as i64, ws::WSAEINTR as i64);
        assert_eq!(size_of::<GroupAffinity>(), size_of::<si::GROUP_AFFINITY>());
        assert_eq!(
            offset_of!(GroupAffinity, group),
            offset_of!(si::GROUP_AFFINITY, Group)
        );
        #[cfg(feature = "local")]
        {
            use windows_sys::Win32::Security::Cryptography as crypt;
            assert_eq!(c::AF_UNIX as i64, ws::AF_UNIX as i64);
            assert_eq!(
                SIO_AF_UNIX_GETPEERPID as i64,
                ws::SIO_AF_UNIX_GETPEERPID as i64
            );
            assert_eq!(FROM_PROTOCOL_INFO as i64, ws::FROM_PROTOCOL_INFO as i64);
            assert_eq!(
                BCRYPT_USE_SYSTEM_PREFERRED_RNG as i64,
                crypt::BCRYPT_USE_SYSTEM_PREFERRED_RNG as i64
            );
            let path = size_of::<ws::SOCKADDR_UN>() - offset_of!(ws::SOCKADDR_UN, sun_path);
            assert_eq!(UNIX_PATH_MAX, path);
        }
        #[cfg(any(feature = "reactor", feature = "local"))]
        {
            use windows_sys::Win32::System::IO as io_sys;
            assert_eq!(size_of::<Overlapped>(), size_of::<io_sys::OVERLAPPED>());
            assert_eq!(
                offset_of!(Overlapped, internal_high),
                offset_of!(io_sys::OVERLAPPED, InternalHigh)
            );
            assert_eq!(
                offset_of!(Overlapped, offset),
                offset_of!(io_sys::OVERLAPPED, Anonymous)
            );
            assert_eq!(
                offset_of!(Overlapped, event),
                offset_of!(io_sys::OVERLAPPED, hEvent)
            );
            type Info = ws::WSAPROTOCOL_INFOW;
            assert_eq!(size_of::<WsaProtocolInfo>(), size_of::<Info>());
            for (ours, theirs) in [
                (
                    offset_of!(WsaProtocolInfo, provider_id),
                    offset_of!(Info, ProviderId),
                ),
                (
                    offset_of!(WsaProtocolInfo, catalog_entry_id),
                    offset_of!(Info, dwCatalogEntryId),
                ),
                (
                    offset_of!(WsaProtocolInfo, chain_len),
                    offset_of!(Info, ProtocolChain),
                ),
                (
                    offset_of!(WsaProtocolInfo, version),
                    offset_of!(Info, iVersion),
                ),
                (
                    offset_of!(WsaProtocolInfo, address_family),
                    offset_of!(Info, iAddressFamily),
                ),
                (
                    offset_of!(WsaProtocolInfo, socket_type),
                    offset_of!(Info, iSocketType),
                ),
                (
                    offset_of!(WsaProtocolInfo, i_protocol),
                    offset_of!(Info, iProtocol),
                ),
                (
                    offset_of!(WsaProtocolInfo, message_size),
                    offset_of!(Info, dwMessageSize),
                ),
                (
                    offset_of!(WsaProtocolInfo, provider_reserved),
                    offset_of!(Info, dwProviderReserved),
                ),
                (
                    offset_of!(WsaProtocolInfo, protocol),
                    offset_of!(Info, szProtocol),
                ),
            ] {
                assert_eq!(ours, theirs);
            }
        }
    }

    #[test]
    fn test_wake_ends_wait() {
        let l = TcpListener::bind("127.0.0.1:0").unwrap();
        let w = Wake::new().unwrap();
        w.wake();
        assert_eq!(
            wait(
                l.as_socket(),
                Interest::Read,
                Some(&w),
                Some(Duration::from_secs(5))
            )
            .unwrap(),
            Ready::Woken
        );
        assert_eq!(
            wait(
                l.as_socket(),
                Interest::Read,
                Some(&w),
                Some(Duration::from_millis(10))
            )
            .unwrap(),
            Ready::TimedOut
        );
    }

    /// A backlog past 200 holds that many pending connections: a plain number is
    /// capped at 200 on Windows, and the 201st connect waited 21 s for a SYN-ACK
    /// (D-175, found by ws-net under load).
    #[test]
    fn test_backlog_past_two_hundred_is_kept() {
        let l =
            crate::TcpListener::bind_with("127.0.0.1:0", crate::ListenOptions::new().backlog(1024))
                .unwrap();
        let at = l.local_addr().unwrap();
        let mut held = Vec::new();
        for _ in 0..300 {
            let s = std::net::TcpStream::connect_timeout(&at, Duration::from_secs(2));
            held.push(s.expect("queued without an accept"));
        }
        assert_eq!(held.len(), 300);
    }

    #[test]
    fn test_listener_exclusive_by_default() {
        let p = ListenParams {
            reuse_address: false,
            reuse_port: false,
            ipv6_only: true,
            send_buffer: None,
            receive_buffer: None,
            backlog: 16,
            defer_accept: None,
            fast_open: None,
            incoming_cpu: None,
        };
        let l = tcp_listener("127.0.0.1:0".parse().unwrap(), &p).unwrap();
        assert!(is_listening_stream(l.as_socket()).unwrap());
        assert_eq!(
            get_int(l.as_socket(), c::SOL_SOCKET, c::SO_EXCLUSIVEADDRUSE).unwrap(),
            1
        );
        let second = tcp_listener(l.local_addr().unwrap(), &p);
        assert!(second.is_err());
    }

    /// `reuse_address` asks for Unix semantics; on Windows it keeps the port
    /// exclusive, so another socket asking for `SO_REUSEADDR` cannot bind over it.
    #[test]
    fn test_reuse_address_keeps_the_port_exclusive() {
        let p = ListenParams {
            reuse_address: true,
            reuse_port: false,
            ipv6_only: true,
            send_buffer: None,
            receive_buffer: None,
            backlog: 16,
            defer_accept: None,
            fast_open: None,
            incoming_cpu: None,
        };
        let l = tcp_listener("127.0.0.1:0".parse().unwrap(), &p).unwrap();
        assert_eq!(
            get_int(l.as_socket(), c::SOL_SOCKET, c::SO_EXCLUSIVEADDRUSE).unwrap(),
            1
        );
        let at = l.local_addr().unwrap();
        let s = tcp_socket(false).unwrap();
        set_int(s.as_socket(), c::SOL_SOCKET, c::SO_REUSEADDR, 1).unwrap();
        assert!(
            bind_to(s.as_socket(), at).is_err(),
            "bound over the listener"
        );
        // A restart binds again at once, with an accepted connection still open.
        let _client = TcpStream::connect(at).unwrap();
        let (accepted, _) = l.accept().unwrap();
        drop(l);
        let again = tcp_listener(at, &p).expect("the port is free again");
        drop((again, accepted));
    }

    #[test]
    fn test_linger_and_keepalive_round_trip() {
        let l = TcpListener::bind("127.0.0.1:0").unwrap();
        let s = TcpStream::connect(l.local_addr().unwrap()).unwrap();
        set_linger(s.as_socket(), Some(Duration::ZERO)).unwrap();
        assert_eq!(linger(s.as_socket()).unwrap(), Some(Duration::ZERO));
        set_keepalive(
            s.as_socket(),
            Some((Duration::from_secs(30), Duration::from_secs(5), 4)),
        )
        .unwrap();
        assert_eq!(
            keepalive(s.as_socket()).unwrap(),
            Some((Duration::from_secs(30), Duration::from_secs(5), 4))
        );
        set_ttl(s.as_socket(), false, 33).unwrap();
        assert_eq!(ttl(s.as_socket(), false).unwrap(), 33);
    }
}