oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
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
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
//! Sockets: TCP, UDP and Unix-domain, their addresses and their options.
//!
//! A socket is an [`OwnedSocket`], closed when dropped. Every function takes
//! the socket by reference (`&impl AsSocket`) and maps onto one system call:
//! there is no buffering and no retry. Internet addresses are
//! [`core::net::SocketAddr`]; Unix-domain addresses are [`UnixAddr`]; an
//! [`Address`] is either.
//!
//! ```no_run
//! use oscall::net::{self, Address, Family, Protocol, RecvFlags, SendFlags, Type};
//!
//! # fn main() -> oscall::Result<()> {
//! let listener = net::socket(Family::Ipv4, Type::Stream, Protocol::Default)?;
//! net::set_reuse_addr(&listener, true)?;
//! let any: core::net::SocketAddr = "127.0.0.1:0".parse().unwrap();
//! net::bind(&listener, &any.into())?;
//! net::listen(&listener, 16)?;
//!
//! let client = net::socket(Family::Ipv4, Type::Stream, Protocol::Default)?;
//! net::connect(&client, &net::local_addr(&listener)?)?;
//! let (server, _peer) = net::accept(&listener)?;
//!
//! net::send(&client, b"ping", SendFlags::empty())?;
//! let mut buf = [0; 4];
//! net::recv(&server, &mut buf, RecvFlags::WAIT_ALL)?;
//! # Ok(())
//! # }
//! ```
//!
//! # What is the same everywhere
//!
//! - **Sockets are private to the process**: close-on-exec on Linux and
//!   macOS, non-inheritable on Windows. This is atomic with the creation on
//!   Linux and Windows; macOS has no way to do it atomically, and neither has
//!   Windows for [`accept`]: there the flag is set right after the call.
//! - **No `SIGPIPE`**: sending to a peer that closed the connection fails
//!   with [`BrokenPipe`](crate::ErrorKind::BrokenPipe) or
//!   [`ConnectionReset`](crate::ErrorKind::ConnectionReset) and never raises
//!   a signal (`MSG_NOSIGNAL` on Linux, `SO_NOSIGPIPE` on macOS).
//! - **No handle arrives unasked**: the handles a peer sends over a
//!   Unix-domain socket are given to [`unix::recv_with_handles`] alone.
//!   Every other receive drops them (macOS would create them in the
//!   process and leave them open, out of reach: oscall takes them there,
//!   and closes them).
//! - **A socket returned by [`accept`] is in blocking mode**, whatever the
//!   mode of the listener (macOS and Windows would inherit it).
//! - **A non-blocking [`connect`] that has not completed** fails with
//!   [`InProgress`](crate::ErrorKind::InProgress) (Windows alone would say
//!   `WouldBlock`).
//! - **A datagram longer than the buffer is cut**: [`recv`] returns the
//!   length of the buffer and the rest of the datagram is lost (Windows alone
//!   would fail with `WSAEMSGSIZE`).
//!
//! # What differs and could not be hidden
//!
//! - A blocking call that runs into a timeout set with [`set_recv_timeout`]
//!   or [`set_send_timeout`] fails with
//!   [`WouldBlock`](crate::ErrorKind::WouldBlock) on Linux and macOS and with
//!   [`TimedOut`](crate::ErrorKind::TimedOut) on Windows.
//! - The default of some options ([`only_v6`], [`reuse_addr`]) and the exact
//!   buffer sizes the system grants differ; each option says so.
//! - Unix-domain sockets on Windows are stream sockets only.
//!
//! # Not here
//!
//! - **Name resolution** (DNS, `/etc/hosts`): on Linux it is not a service
//!   of the operating system but of the C library, and oscall has none.
//!   Addresses are numeric.
//! - Ancillary data other than handles, which [`unix`] passes between
//!   processes.
//! - Readiness polling: see [`event`](crate::event), which builds on
//!   [`set_nonblocking`], [`take_error`] and the raw socket.
//!
//! # Names
//!
//! [`resolve`] finds the addresses of a host name and [`reverse`] the name
//! of an address, by asking the resolver of the system; what that resolver
//! consults is the one thing the systems do not share, and [`resolve`]
//! says what each does. Linux has no resolver of its own: oscall's is
//! there, built on [`dns`], a DNS client that is the same on every system
//! and can be given its servers by the program.
//!
//! # WebAssembly
//!
//! WASI preview 1 cannot create, bind or connect a socket: a program only
//! gets the sockets its host opened for it. [`accept`], [`recv`], [`send`]
//! (and their vectored forms), [`shutdown`], [`set_nonblocking`] and
//! [`socket_type`] work on those;
//! everything else fails with
//! [`Unsupported`](crate::ErrorKind::Unsupported). Without WASI every
//! function fails that way.

use core::fmt;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use core::time::Duration;

use crate::io::{IoSlice, IoSliceMut};
use crate::macros::flags;
use crate::path::AsPath;
use crate::{Error, ErrorKind, Result, sys};

// ---------------------------------------------------------------------------
// Ownership
// ---------------------------------------------------------------------------

/// The operating system's own socket type: a file descriptor (`i32`) on
/// Linux, macOS and WASI, a `SOCKET` (`usize`) on Windows.
pub type RawSocket = sys::net::RawSocket;

/// An owned socket. It is closed when dropped.
///
/// On Linux, macOS and WASI a socket is a handle like any other, and
/// converts to and from [`OwnedHandle`](crate::OwnedHandle). On Windows it is
/// a different kind of object, closed with `closesocket`.
#[repr(transparent)]
pub struct OwnedSocket(RawSocket);

/// A socket borrowed from its owner.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BorrowedSocket<'a>(RawSocket, PhantomData<&'a OwnedSocket>);

impl OwnedSocket {
    /// Takes ownership of a raw socket.
    ///
    /// # Safety
    ///
    /// `raw` must be an open socket that nothing else will close.
    #[inline]
    pub const unsafe fn from_raw(raw: RawSocket) -> Self {
        Self(raw)
    }

    /// The raw socket, still owned by `self`.
    #[inline]
    pub const fn as_raw(&self) -> RawSocket {
        self.0
    }

    /// Releases ownership: the caller is now responsible for closing it.
    #[inline]
    pub fn into_raw(self) -> RawSocket {
        ManuallyDrop::new(self).0
    }
}

impl Drop for OwnedSocket {
    fn drop(&mut self) {
        // SAFETY: the socket is open and owned by `self`. Like `std`, a
        // failure to close is ignored: there is nothing to do about it.
        unsafe { sys::net::close(self.0) };
    }
}

impl<'a> BorrowedSocket<'a> {
    /// Borrows a raw socket.
    ///
    /// # Safety
    ///
    /// `raw` must stay open for the lifetime `'a`.
    #[inline]
    pub const unsafe fn borrow_raw(raw: RawSocket) -> Self {
        Self(raw, PhantomData)
    }

    /// The raw socket.
    #[inline]
    pub const fn as_raw(self) -> RawSocket {
        self.0
    }
}

/// Types that hold a socket.
pub trait AsSocket {
    /// Borrows the socket.
    fn as_socket(&self) -> BorrowedSocket<'_>;
}

impl AsSocket for OwnedSocket {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        BorrowedSocket(self.0, PhantomData)
    }
}

impl AsSocket for BorrowedSocket<'_> {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        *self
    }
}

impl<T: AsSocket + ?Sized> AsSocket for &T {
    #[inline]
    fn as_socket(&self) -> BorrowedSocket<'_> {
        T::as_socket(self)
    }
}

impl fmt::Debug for OwnedSocket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("OwnedSocket").field(&self.0).finish()
    }
}

impl fmt::Debug for BorrowedSocket<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("BorrowedSocket").field(&self.0).finish()
    }
}

#[inline]
fn raw<S: AsSocket + ?Sized>(socket: &S) -> RawSocket {
    socket.as_socket().0
}

// Where a socket is a file descriptor, it is a handle too.
#[cfg(not(windows))]
mod handle_impls {
    use super::*;
    use crate::{AsHandle, BorrowedHandle, OwnedHandle};

    impl From<OwnedHandle> for OwnedSocket {
        fn from(handle: OwnedHandle) -> Self {
            Self(handle.into_raw())
        }
    }

    impl From<OwnedSocket> for OwnedHandle {
        fn from(socket: OwnedSocket) -> Self {
            // SAFETY: the socket is an open descriptor whose ownership moves.
            unsafe { Self::from_raw(socket.into_raw()) }
        }
    }

    impl<'a> From<BorrowedHandle<'a>> for BorrowedSocket<'a> {
        fn from(handle: BorrowedHandle<'a>) -> Self {
            Self(handle.as_raw(), PhantomData)
        }
    }

    impl<'a> From<BorrowedSocket<'a>> for BorrowedHandle<'a> {
        fn from(socket: BorrowedSocket<'a>) -> Self {
            // SAFETY: the descriptor stays open for 'a.
            unsafe { Self::borrow_raw(socket.0) }
        }
    }

    impl AsHandle for OwnedSocket {
        fn as_handle(&self) -> BorrowedHandle<'_> {
            self.as_socket().into()
        }
    }

    impl AsHandle for BorrowedSocket<'_> {
        fn as_handle(&self) -> BorrowedHandle<'_> {
            (*self).into()
        }
    }
}

// Conversions with std's own types. fullrust is not `cfg(unix)` but has
// `std::os::fd` like Linux.
#[cfg(all(feature = "std", any(unix, target_os = "fullrust", target_os = "wasi")))]
mod std_impls {
    use std::net::{TcpListener, TcpStream, UdpSocket};
    use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd};

    use super::*;

    impl From<OwnedFd> for OwnedSocket {
        fn from(fd: OwnedFd) -> Self {
            Self(fd.into_raw_fd())
        }
    }

    impl From<OwnedSocket> for OwnedFd {
        fn from(socket: OwnedSocket) -> Self {
            // SAFETY: the socket is an open descriptor whose ownership moves.
            unsafe { Self::from_raw_fd(socket.into_raw()) }
        }
    }

    impl<'a> From<BorrowedFd<'a>> for BorrowedSocket<'a> {
        fn from(fd: BorrowedFd<'a>) -> Self {
            Self(fd.as_raw_fd(), PhantomData)
        }
    }

    impl<'a> From<BorrowedSocket<'a>> for BorrowedFd<'a> {
        fn from(socket: BorrowedSocket<'a>) -> Self {
            // SAFETY: the descriptor stays open for 'a.
            unsafe { Self::borrow_raw(socket.0) }
        }
    }

    impl AsFd for OwnedSocket {
        fn as_fd(&self) -> BorrowedFd<'_> {
            self.as_socket().into()
        }
    }

    impl AsFd for BorrowedSocket<'_> {
        fn as_fd(&self) -> BorrowedFd<'_> {
            (*self).into()
        }
    }

    macro_rules! std_socket {
        ($($ty:ty),*) => {$(
            impl From<$ty> for OwnedSocket {
                fn from(socket: $ty) -> Self {
                    OwnedFd::from(socket).into()
                }
            }

            impl From<OwnedSocket> for $ty {
                fn from(socket: OwnedSocket) -> Self {
                    OwnedFd::from(socket).into()
                }
            }
        )*};
    }
    std_socket!(TcpStream, TcpListener, UdpSocket);
}

#[cfg(all(feature = "std", windows))]
mod std_impls {
    use std::net::{TcpListener, TcpStream, UdpSocket};
    use std::os::windows::io as stdio;
    use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket};

    use super::*;

    impl From<stdio::OwnedSocket> for OwnedSocket {
        fn from(socket: stdio::OwnedSocket) -> Self {
            Self(socket.into_raw_socket() as RawSocket)
        }
    }

    impl From<OwnedSocket> for stdio::OwnedSocket {
        fn from(socket: OwnedSocket) -> Self {
            // SAFETY: the socket is open and its ownership moves.
            unsafe { Self::from_raw_socket(socket.into_raw() as stdio::RawSocket) }
        }
    }

    impl<'a> From<stdio::BorrowedSocket<'a>> for BorrowedSocket<'a> {
        fn from(socket: stdio::BorrowedSocket<'a>) -> Self {
            Self(socket.as_raw_socket() as RawSocket, PhantomData)
        }
    }

    impl<'a> From<BorrowedSocket<'a>> for stdio::BorrowedSocket<'a> {
        fn from(socket: BorrowedSocket<'a>) -> Self {
            // SAFETY: the socket stays open for 'a.
            unsafe { Self::borrow_raw(socket.0 as stdio::RawSocket) }
        }
    }

    impl stdio::AsSocket for OwnedSocket {
        fn as_socket(&self) -> stdio::BorrowedSocket<'_> {
            AsSocket::as_socket(self).into()
        }
    }

    impl stdio::AsSocket for BorrowedSocket<'_> {
        fn as_socket(&self) -> stdio::BorrowedSocket<'_> {
            (*self).into()
        }
    }

    macro_rules! std_socket {
        ($($ty:ty),*) => {$(
            impl From<$ty> for OwnedSocket {
                fn from(socket: $ty) -> Self {
                    stdio::OwnedSocket::from(socket).into()
                }
            }

            impl From<OwnedSocket> for $ty {
                fn from(socket: OwnedSocket) -> Self {
                    stdio::OwnedSocket::from(socket).into()
                }
            }
        )*};
    }
    std_socket!(TcpStream, TcpListener, UdpSocket);
}

// ---------------------------------------------------------------------------
// Addresses
// ---------------------------------------------------------------------------

/// The size of `sun_path` on the most generous system.
const UNIX_BUF: usize = 108;

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum UnixKind {
    Unnamed,
    Path,
    #[allow(dead_code)] // only made where the system has abstract names
    Abstract,
}

/// The address of a Unix-domain socket: a path in the filesystem, or no name
/// at all (a socket that was never bound, or one of a pair).
///
/// Linux has a third kind, names that are not in the filesystem: see
/// [`linux::abstract_addr`].
///
/// The system limits the length of the path: at most 107 bytes on Linux and
/// Windows, 103 on macOS. A relative path is often the way to stay below it.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct UnixAddr {
    kind: UnixKind,
    len: u8,
    // Zero beyond `len`, so that the derived comparisons hold.
    bytes: [u8; UNIX_BUF],
}

impl UnixAddr {
    /// The address of the socket bound, or to bind, at `path`.
    ///
    /// Fails with `InvalidInput` if the path is empty, contains a NUL or is
    /// longer than the system allows. On Windows the path is UTF-8, as
    /// everywhere in oscall.
    pub fn new<P: AsPath + ?Sized>(path: &P) -> Result<Self> {
        let path = path.as_path_bytes();
        // The system wants room for a terminating NUL.
        if path.is_empty() || path.len() >= sys::net::UNIX_PATH_MAX || path.contains(&0) {
            return Err(ErrorKind::InvalidInput.into());
        }
        Ok(Self::from_parts(UnixKind::Path, path))
    }

    /// The address of a socket that has no name.
    ///
    /// It is what the system reports for an unbound socket; it cannot be
    /// bound or connected to.
    pub const fn unnamed() -> Self {
        Self {
            kind: UnixKind::Unnamed,
            len: 0,
            bytes: [0; UNIX_BUF],
        }
    }

    fn from_parts(kind: UnixKind, name: &[u8]) -> Self {
        let mut bytes = [0; UNIX_BUF];
        bytes[..name.len()].copy_from_slice(name);
        Self {
            kind,
            len: name.len() as u8,
            bytes,
        }
    }

    /// The path, if this is the address of a socket bound to one.
    pub fn path_bytes(&self) -> Option<&[u8]> {
        match self.kind {
            UnixKind::Path => Some(&self.bytes[..self.len as usize]),
            _ => None,
        }
    }

    /// Whether this is the address of a socket with no name.
    pub fn is_unnamed(&self) -> bool {
        self.kind == UnixKind::Unnamed
    }
}

impl fmt::Debug for UnixAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = &self.bytes[..self.len as usize];
        match self.kind {
            UnixKind::Unnamed => f.write_str("(unnamed)"),
            UnixKind::Path => write!(f, "\"{}\" (path)", name.escape_ascii()),
            UnixKind::Abstract => write!(f, "\"{}\" (abstract)", name.escape_ascii()),
        }
    }
}

/// The address of a socket of any family.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Address {
    /// An IPv4 or IPv6 address and a port.
    Ip(SocketAddr),
    /// A Unix-domain address.
    Unix(UnixAddr),
}

impl Address {
    /// The Internet address, if it is one.
    pub fn as_ip(&self) -> Option<SocketAddr> {
        match self {
            Self::Ip(addr) => Some(*addr),
            _ => None,
        }
    }

    /// The Unix-domain address, if it is one.
    pub fn as_unix(&self) -> Option<&UnixAddr> {
        match self {
            Self::Unix(addr) => Some(addr),
            _ => None,
        }
    }

    /// The family of socket this address is for.
    pub fn family(&self) -> Family {
        match self {
            Self::Ip(SocketAddr::V4(_)) => Family::Ipv4,
            Self::Ip(SocketAddr::V6(_)) => Family::Ipv6,
            Self::Unix(_) => Family::Unix,
        }
    }
}

impl From<SocketAddr> for Address {
    fn from(addr: SocketAddr) -> Self {
        Self::Ip(addr)
    }
}

impl From<SocketAddrV4> for Address {
    fn from(addr: SocketAddrV4) -> Self {
        Self::Ip(addr.into())
    }
}

impl From<SocketAddrV6> for Address {
    fn from(addr: SocketAddrV6) -> Self {
        Self::Ip(addr.into())
    }
}

impl From<UnixAddr> for Address {
    fn from(addr: UnixAddr) -> Self {
        Self::Unix(addr)
    }
}

/// What a call reports when the system gave no address.
const NO_ADDRESS: Address = Address::Unix(UnixAddr::unnamed());

/// A socket address in the system's own layout (`sockaddr_storage`, cut to
/// what the three families need), and its length.
///
/// The three families have the same layout on every system, apart from the
/// first two bytes: a 16-bit family, or on macOS a length byte and an 8-bit
/// family. The backends say which, and the value of each family.
#[repr(C, align(8))]
pub(crate) struct RawAddr {
    bytes: [u8; RawAddr::CAPACITY],
    len: u32,
}

const SIZE_V4: usize = 16;
const SIZE_V6: usize = 28;

#[allow(dead_code)] // the WebAssembly backends never look inside
impl RawAddr {
    pub(crate) const CAPACITY: usize = 128;

    /// Where the length is, for the calls that are given a pointer to it.
    #[allow(dead_code)] // io_uring alone
    pub(crate) const LEN_OFFSET: usize = core::mem::offset_of!(Self, len);

    /// An empty buffer for the system to fill, then [`set_len`](Self::set_len).
    pub(crate) const fn new() -> Self {
        Self {
            bytes: [0; Self::CAPACITY],
            len: 0,
        }
    }

    /// The address: `len()` initialized bytes, aligned for any `sockaddr`.
    pub(crate) const fn as_ptr(&self) -> *const u8 {
        self.bytes.as_ptr()
    }

    /// Room for `CAPACITY` bytes, aligned for any `sockaddr`.
    pub(crate) const fn as_mut_ptr(&mut self) -> *mut u8 {
        self.bytes.as_mut_ptr()
    }

    pub(crate) const fn len(&self) -> u32 {
        self.len
    }

    /// The address, as the system wrote it.
    pub(crate) fn bytes(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }

    /// The family of the address the system wrote, a system value; 0 if it
    /// wrote none.
    pub(crate) fn family(&self) -> u16 {
        if self.len < 2 {
            0
        } else if sys::net::SOCKADDR_LEN_BYTE {
            self.bytes[1] as u16
        } else {
            u16::from_ne_bytes([self.bytes[0], self.bytes[1]])
        }
    }

    /// Records the length the system returned. It may be more than it wrote
    /// (a truncated address): the excess is ignored.
    pub(crate) fn set_len(&mut self, len: usize) {
        self.len = len.min(Self::CAPACITY) as u32;
    }

    /// Makes this the unspecified address of `family`, a system value: all
    /// zeros, the address of a socket that is not bound. `false` if the
    /// family is not one of the three.
    pub(crate) fn set_unspecified(&mut self, family: u16) -> bool {
        let len = match family {
            sys::net::AF_INET => SIZE_V4,
            sys::net::AF_INET6 => SIZE_V6,
            sys::net::AF_UNIX => 2,
            _ => return false,
        };
        self.bytes = [0; Self::CAPACITY];
        if sys::net::SOCKADDR_LEN_BYTE {
            self.bytes[0] = len as u8;
            self.bytes[1] = family as u8;
        } else {
            self.bytes[..2].copy_from_slice(&family.to_ne_bytes());
        }
        self.len = len as u32;
        true
    }

    pub(crate) fn encode(addr: &Address) -> Result<Self> {
        let mut raw = Self::new();
        let b = &mut raw.bytes;
        let (family, len) = match addr {
            Address::Ip(SocketAddr::V4(a)) => {
                b[2..4].copy_from_slice(&a.port().to_be_bytes());
                b[4..8].copy_from_slice(&a.ip().octets());
                (sys::net::AF_INET, SIZE_V4)
            }
            Address::Ip(SocketAddr::V6(a)) => {
                b[2..4].copy_from_slice(&a.port().to_be_bytes());
                // Like std, the flow information is passed through as the
                // system stores it.
                b[4..8].copy_from_slice(&a.flowinfo().to_ne_bytes());
                b[8..24].copy_from_slice(&a.ip().octets());
                b[24..28].copy_from_slice(&a.scope_id().to_ne_bytes());
                (sys::net::AF_INET6, SIZE_V6)
            }
            Address::Unix(a) => {
                let name = &a.bytes[..a.len as usize];
                let len = match a.kind {
                    UnixKind::Unnamed => return Err(ErrorKind::InvalidInput.into()),
                    UnixKind::Path => {
                        b[2..2 + name.len()].copy_from_slice(name);
                        // With the terminating NUL.
                        2 + name.len() + 1
                    }
                    UnixKind::Abstract => {
                        // A leading NUL, and no terminator: the length alone
                        // delimits the name.
                        b[3..3 + name.len()].copy_from_slice(name);
                        3 + name.len()
                    }
                };
                (sys::net::AF_UNIX, len)
            }
        };
        if sys::net::SOCKADDR_LEN_BYTE {
            b[0] = len as u8;
            b[1] = family as u8;
        } else {
            b[..2].copy_from_slice(&family.to_ne_bytes());
        }
        raw.len = len as u32;
        Ok(raw)
    }

    /// `None` if the system wrote no address, or one of another family.
    pub(crate) fn decode(&self) -> Option<Address> {
        let len = self.len as usize;
        let b = &self.bytes;
        if len < 2 {
            return None;
        }
        let family = if sys::net::SOCKADDR_LEN_BYTE {
            b[1] as u16
        } else {
            u16::from_ne_bytes([b[0], b[1]])
        };
        let port = u16::from_be_bytes([b[2], b[3]]);
        if family == sys::net::AF_INET && len >= SIZE_V4 {
            let ip = Ipv4Addr::new(b[4], b[5], b[6], b[7]);
            Some(SocketAddrV4::new(ip, port).into())
        } else if family == sys::net::AF_INET6 && len >= SIZE_V6 {
            let flowinfo = u32::from_ne_bytes([b[4], b[5], b[6], b[7]]);
            let mut ip = [0; 16];
            ip.copy_from_slice(&b[8..24]);
            let scope_id = u32::from_ne_bytes([b[24], b[25], b[26], b[27]]);
            Some(SocketAddrV6::new(Ipv6Addr::from(ip), port, flowinfo, scope_id).into())
        } else if family == sys::net::AF_UNIX {
            let name = &b[2..len.min(2 + UNIX_BUF)];
            let addr = match name.first() {
                None => UnixAddr::unnamed(),
                Some(0) if sys::net::UNIX_ABSTRACT && name.len() > 1 => {
                    UnixAddr::from_parts(UnixKind::Abstract, &name[1..])
                }
                // macOS and Windows report an unnamed socket as an empty
                // path rather than as a short address.
                Some(0) => UnixAddr::unnamed(),
                Some(_) => {
                    let end = name.iter().position(|&c| c == 0).unwrap_or(name.len());
                    UnixAddr::from_parts(UnixKind::Path, &name[..end])
                }
            };
            Some(addr.into())
        } else {
            None
        }
    }
}

// ---------------------------------------------------------------------------
// Names
// ---------------------------------------------------------------------------

pub mod dns;

/// Which addresses of a name are wanted.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum IpVersion {
    /// Those of IPv6 and those of IPv4.
    #[default]
    Any,
    /// Those of IPv4 only.
    V4,
    /// Those of IPv6 only.
    V6,
}

/// Finds the addresses of `host` the way the system is set up to, writes
/// them to `addrs` with `port`, and returns how many were written.
/// Addresses that do not fit in `addrs` are left out: the first ones are
/// the ones to try first.
///
/// The call blocks, for as long as the system's resolver takes: seconds
/// when servers do not answer.
///
/// # What is the same everywhere
///
/// - A `host` that is an address already (`192.0.2.1`, `2001:db8::1`; no
///   interface after a `%`) is returned as it is, and nothing is asked.
/// - Otherwise `host` must be a name in ASCII: labels of letters, digits,
///   `-` and `_`, 63 characters at most each, with dots between them and
///   maybe one at the end, 253 characters in all. Anything else fails with
///   [`InvalidInput`](ErrorKind::InvalidInput) before the system is
///   asked: a name in another script is to be converted to its `xn--`
///   form by the caller, since the systems differ in doing it.
/// - `localhost` is this machine.
/// - A name that does not exist, or has no address of the kind asked for,
///   fails with [`NotFound`](ErrorKind::NotFound). When the resolver could
///   not find out, because nothing answered in time, it fails with
///   [`TimedOut`](ErrorKind::TimedOut).
/// - Each address comes once, whatever kinds of socket it could serve.
///
/// # What differs and could not be hidden
///
/// The resolver is the system's, and *what it consults* is the system's
/// business:
///
/// - **macOS**: `getaddrinfo`. The system's resolver knows `/etc/hosts`,
///   the name servers of each network interface and of each VPN,
///   multicast DNS (`.local`), and keeps a cache.
/// - **Windows**: `GetAddrInfoW`. The DNS client service knows the
///   `hosts` file, the name servers of each interface, its cache, and
///   falls back on multicast DNS, LLMNR and NetBIOS for short names.
/// - **Linux**: there is no resolver in the system, only in its C
///   library, which oscall does not use. oscall's own does what a C
///   library does by default: `/etc/hosts`, then the name servers of
///   `/etc/resolv.conf` ([`dns::Config`], which says exactly what is
///   done with them), asked every time. It does not read
///   `/etc/nsswitch.conf` and so knows none of the other sources that
///   file can name (multicast DNS, LDAP, the machines of
///   `systemd-machined`...), and it does not talk to `systemd-resolved`
///   over D-Bus or varlink; where that service runs, `/etc/resolv.conf`
///   names its local server, and names resolve through it as for any
///   program that reads the file. `localhost` and the names under it are
///   this machine also when `/etc/hosts` does not say so.
///
/// *The order* of the addresses is the system's on macOS and Windows,
/// which sort them by what the machine can reach and prefers (RFC 6724).
/// On Linux those of IPv6 come first, then those of IPv4, each in the
/// order found, and behind them all those the machine has no route to
/// (a host with no IPv6 connectivity gets the IPv4 addresses first).
///
/// When the resolver could not find out for another reason than time, the
/// error is the system's: see [`dns`] for Linux.
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly for
/// anything but an address.
pub fn resolve(
    host: &str,
    port: u16,
    version: IpVersion,
    addrs: &mut [SocketAddr],
) -> Result<usize> {
    if let Some(count) = dns::literal(host, port, version, addrs)? {
        return Ok(count);
    }
    if !dns::is_name(host) {
        return Err(ErrorKind::InvalidInput.into());
    }
    sys::resolve::resolve(host, port, version, addrs)
}

/// As [`resolve`], returning every address in a `Vec`.
#[cfg(feature = "alloc")]
pub fn resolve_vec(
    host: &str,
    port: u16,
    version: IpVersion,
) -> Result<alloc::vec::Vec<SocketAddr>> {
    /// More addresses than any name has.
    const MAX: usize = 4096;

    let mut addrs = alloc::vec::Vec::new();
    let mut size = 32;
    loop {
        addrs
            .try_reserve_exact(size - addrs.len())
            .map_err(|_| ErrorKind::OutOfMemory)?;
        addrs.resize(size, SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0));
        let count = resolve(host, port, version, &mut addrs)?;
        // A list that was filled may have been cut: ask again, with room.
        if count < size || size >= MAX {
            addrs.truncate(count);
            return Ok(addrs);
        }
        size *= 4;
    }
}

/// Finds the name of the machine at `addr` the way the system is set up
/// to, writes it to `buf` without a last dot, and returns it.
///
/// The name is what whoever is in charge of the address says it is:
/// nothing guarantees that it leads back to the address
/// ([`resolve`] it to check).
///
/// The same everywhere: an address with no name fails with
/// [`NotFound`](ErrorKind::NotFound), as does one whose name is not a
/// host name as [`resolve`] takes them; a `buf` too small for the name
/// fails with [`BufferTooSmall`](ErrorKind::BufferTooSmall), and 253
/// bytes hold any.
///
/// What differs is what [`resolve`] says: who is asked. macOS:
/// `getnameinfo`. Windows: `GetNameInfoW`. Linux: `/etc/hosts`, where the
/// name is the first of the address's line, and then the name servers
/// ([`dns::Config::reverse`]). For this machine's own addresses the
/// systems do not agree either: `127.0.0.1` is `localhost` where
/// `/etc/hosts` says so, and the name of the computer on Windows.
///
/// Fails with [`Unsupported`](ErrorKind::Unsupported) on WebAssembly.
pub fn reverse(addr: IpAddr, buf: &mut [u8]) -> Result<&str> {
    let len = sys::resolve::reverse(addr, buf)?;
    let name = buf.get(..len).ok_or(ErrorKind::Other)?;
    let name = name.strip_suffix(b".").unwrap_or(name);
    match core::str::from_utf8(name) {
        Ok(name) if dns::is_name(name) => Ok(name),
        _ => Err(ErrorKind::NotFound.into()),
    }
}

// ---------------------------------------------------------------------------
// Creation
// ---------------------------------------------------------------------------

/// The address family of a socket.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Family {
    /// IPv4 (`AF_INET`).
    Ipv4,
    /// IPv6 (`AF_INET6`).
    Ipv6,
    /// Unix-domain (`AF_UNIX`): sockets named by a path, local to the
    /// machine. On Windows (10 version 1803 and later) only [`Type::Stream`]
    /// exists in this family.
    Unix,
}

/// The type of a socket: how data travels over it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Type {
    /// A reliable stream of bytes over a connection (`SOCK_STREAM`): TCP.
    Stream,
    /// Separate messages, with no connection and no guarantee
    /// (`SOCK_DGRAM`): UDP.
    Datagram,
    /// Direct access to the network protocol (`SOCK_RAW`). Every system
    /// reserves it to privileged processes.
    Raw,
    /// Separate messages over a connection, reliable and in order
    /// (`SOCK_SEQPACKET`): what a stream is, without losing where each
    /// send ends.
    ///
    /// Only Linux has it for [`Family::Unix`]: macOS and Windows fail with
    /// `Unsupported`. No system has it for the Internet families with the
    /// protocols of [`Protocol`].
    SeqPacket,
}

/// The protocol of a socket.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Protocol {
    /// The protocol the family has for the type: TCP for a stream, UDP for
    /// datagrams. The only choice for Unix-domain sockets.
    Default,
    /// TCP.
    Tcp,
    /// UDP.
    Udp,
    /// ICMP, for [`Family::Ipv4`] and [`Type::Raw`] (Linux and macOS also
    /// allow [`Type::Datagram`], for echo requests without privileges).
    Icmpv4,
    /// ICMPv6, likewise for [`Family::Ipv6`].
    Icmpv6,
}

impl Protocol {
    /// The protocol's number, assigned by IANA and thus the same on every
    /// system.
    #[allow(dead_code)] // not on WebAssembly
    pub(crate) const fn number(self) -> i32 {
        match self {
            Self::Default => 0,
            Self::Icmpv4 => 1,
            Self::Tcp => 6,
            Self::Udp => 17,
            Self::Icmpv6 => 58,
        }
    }
}

/// Creates a socket (`socket`, `WSASocketW`).
///
/// The socket is in blocking mode and is not inherited by child processes.
/// On Windows it is created for overlapped I/O, like every socket there
/// unless asked otherwise, and the first call initializes Winsock for the
/// process (`WSAStartup`, never undone).
///
/// A family, type or protocol the system does not have fails with
/// `Unsupported`; so does every call on WebAssembly.
pub fn socket(family: Family, ty: Type, protocol: Protocol) -> Result<OwnedSocket> {
    sys::net::socket(family, ty, protocol).map(OwnedSocket)
}

/// Gives the socket its local address (`bind`).
///
/// For an Internet address, port 0 lets the system choose a port:
/// [`local_addr`] tells which. For a Unix-domain path, the call creates the
/// socket file, which must not exist (`AddrInUse`) and is not removed when
/// the socket is closed.
pub fn bind<S: AsSocket + ?Sized>(socket: &S, addr: &Address) -> Result<()> {
    sys::net::bind(raw(socket), &RawAddr::encode(addr)?)
}

/// Starts accepting connections on a bound stream socket (`listen`).
///
/// `backlog` is a hint of how many connections may wait to be accepted; the
/// system bounds it.
pub fn listen<S: AsSocket + ?Sized>(socket: &S, backlog: u32) -> Result<()> {
    sys::net::listen(raw(socket), backlog.min(i32::MAX as u32) as i32)
}

/// Takes the next connection waiting on a listening socket, and returns it
/// with the address of the peer (`accept4`, `accept`).
///
/// The new socket is in blocking mode, whatever the mode of the listener,
/// and is not inherited by child processes (on macOS and Windows that is set
/// right after the call, not atomically).
///
/// The address is [`UnixAddr::unnamed`] when the system has none to report,
/// which is always the case on WASI.
pub fn accept<S: AsSocket + ?Sized>(socket: &S) -> Result<(OwnedSocket, Address)> {
    let mut addr = RawAddr::new();
    let new = OwnedSocket(sys::net::accept(raw(socket), &mut addr)?);
    Ok((new, addr.decode().unwrap_or(NO_ADDRESS)))
}

/// Connects the socket to `addr` (`connect`).
///
/// On a datagram socket this only sets the default destination of [`send`]
/// and filters what [`recv`] receives.
///
/// On a non-blocking socket a connection that cannot be made at once fails
/// with `InProgress` and goes on in the background: wait for the socket to be
/// writable, then read its outcome with [`take_error`].
pub fn connect<S: AsSocket + ?Sized>(socket: &S, addr: &Address) -> Result<()> {
    sys::net::connect(raw(socket), &RawAddr::encode(addr)?)
}

// ---------------------------------------------------------------------------
// Data
// ---------------------------------------------------------------------------

flags! {
    /// How [`send`] and [`send_to`] send.
    pub struct SendFlags: u32 {
        /// Send out-of-band data (`MSG_OOB`): TCP's urgent data.
        const OUT_OF_BAND = 1;
        /// Send to a host on a directly connected network only, without
        /// looking at the routing table (`MSG_DONTROUTE`).
        const DONT_ROUTE = 2;
    }
}

flags! {
    /// How [`recv`] and [`recv_from`] receive.
    pub struct RecvFlags: u32 {
        /// Leave the data in the socket: the next call returns it again
        /// (`MSG_PEEK`).
        const PEEK = 1;
        /// Receive out-of-band data (`MSG_OOB`).
        const OUT_OF_BAND = 2;
        /// On a stream, wait until the buffer is full, the connection ends
        /// or an error occurs (`MSG_WAITALL`). The call can still return
        /// less.
        const WAIT_ALL = 4;
    }
}

/// `MSG_DONTWAIT`, a flag Windows does not have (see [`unix`]).
#[allow(dead_code)]
const DONT_WAIT: u32 = 0x100;

/// Sends data on a connected socket, and returns how many bytes were taken
/// (`sendto`, `send`, `sock_send`). A stream may take fewer than `buf`
/// holds; a datagram is sent whole or not at all.
///
/// If the peer closed the connection the call fails with `BrokenPipe` or
/// `ConnectionReset`; no signal is raised.
///
/// WASI has no flags to send with: any flag fails with `Unsupported` there.
pub fn send<S: AsSocket + ?Sized>(socket: &S, buf: &[u8], flags: SendFlags) -> Result<usize> {
    sys::net::send(raw(socket), buf, flags, None)
}

/// Sends a datagram to `addr` (`sendto`).
///
/// Fails with `Unsupported` on WASI.
pub fn send_to<S: AsSocket + ?Sized>(
    socket: &S,
    buf: &[u8],
    addr: &Address,
    flags: SendFlags,
) -> Result<usize> {
    sys::net::send(raw(socket), buf, flags, Some(&RawAddr::encode(addr)?))
}

/// Receives data, and returns how many bytes were written to `buf`
/// (`recvfrom`, `recv`, `sock_recv`; `recvmsg` on macOS, to close the
/// handles a peer may have sent with the data).
///
/// On a stream, 0 means the peer closed its side of the connection (or `buf`
/// is empty). A datagram is received whole: if it is longer than `buf`, the
/// rest is lost and the call returns the length of `buf`.
///
/// WASI cannot receive out-of-band data: that flag fails with `Unsupported`
/// there.
pub fn recv<S: AsSocket + ?Sized>(socket: &S, buf: &mut [u8], flags: RecvFlags) -> Result<usize> {
    sys::net::recv(raw(socket), buf, flags, None)
}

/// Receives data like [`recv`], and also returns the address it came from
/// (`recvfrom`).
///
/// The address is [`UnixAddr::unnamed`] when the system has none to report:
/// on a connected stream socket, or for a datagram from a Unix-domain socket
/// that is not bound.
///
/// Fails with `Unsupported` on WASI.
pub fn recv_from<S: AsSocket + ?Sized>(
    socket: &S,
    buf: &mut [u8],
    flags: RecvFlags,
) -> Result<(usize, Address)> {
    let mut addr = RawAddr::new();
    let n = sys::net::recv(raw(socket), buf, flags, Some(&mut addr))?;
    Ok((n, addr.decode().unwrap_or(NO_ADDRESS)))
}

/// The most buffers one vectored call takes (`IOV_MAX`, `UIO_MAXIOV`).
const MAX_BUFFERS: usize = 1024;

fn check_buffers(count: usize) -> Result<()> {
    if count > MAX_BUFFERS {
        return Err(ErrorKind::InvalidInput.into());
    }
    Ok(())
}

/// What [`recv_vectored`] and [`recv_from_vectored`] received.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Received {
    /// How many bytes were written to the buffers.
    pub len: usize,
    /// Whether the datagram was longer than the buffers, and its end lost.
    /// Always `false` on a stream, where what did not fit stays to be read.
    ///
    /// Linux and macOS say so in the flags of the message (`MSG_TRUNC`),
    /// Windows by failing with `WSAEMSGSIZE` after it filled the buffers,
    /// WASI in `roflags`.
    pub truncated: bool,
}

/// Sends the content of several buffers, in order, as [`send`] would send
/// their concatenation: one datagram, or the next bytes of a stream
/// (`sendmsg`, `WSASend`, `sock_send`). Returns how many bytes were taken.
///
/// At most 1024 buffers: more fail with `InvalidInput`, on every system. No
/// buffer at all is an empty message. See [`send`] for the rest, including
/// what WASI lacks.
pub fn send_vectored<S: AsSocket + ?Sized>(
    socket: &S,
    bufs: &[IoSlice<'_>],
    flags: SendFlags,
) -> Result<usize> {
    check_buffers(bufs.len())?;
    sys::net::send_vectored(raw(socket), bufs, flags, None)
}

/// Sends the content of several buffers as one datagram to `addr`
/// (`sendmsg`, `WSASendTo`): the vectored form of [`send_to`].
///
/// At most 1024 buffers, as for [`send_vectored`]. Fails with `Unsupported`
/// on WASI.
pub fn send_to_vectored<S: AsSocket + ?Sized>(
    socket: &S,
    bufs: &[IoSlice<'_>],
    addr: &Address,
    flags: SendFlags,
) -> Result<usize> {
    check_buffers(bufs.len())?;
    sys::net::send_vectored(raw(socket), bufs, flags, Some(&RawAddr::encode(addr)?))
}

/// Receives data into several buffers, filling each one before using the
/// next (`recvmsg`, `WSARecv`, `sock_recv`): the vectored form of [`recv`].
///
/// Unlike [`recv`], it tells whether a datagram was cut for being longer
/// than the buffers: see [`Received`].
///
/// At most 1024 buffers: more fail with `InvalidInput`, on every system.
/// With no room at all (no buffer, or empty ones) a datagram is taken and
/// lost whole, and reported as truncated unless it was empty; but macOS
/// does not wait for one then, and returns at once with nothing if none
/// has arrived yet.
///
/// See [`recv`] for the rest, including what WASI lacks.
pub fn recv_vectored<S: AsSocket + ?Sized>(
    socket: &S,
    bufs: &mut [IoSliceMut<'_>],
    flags: RecvFlags,
) -> Result<Received> {
    check_buffers(bufs.len())?;
    let (len, truncated) = sys::net::recv_vectored(raw(socket), bufs, flags, None)?;
    Ok(Received { len, truncated })
}

/// Receives data into several buffers like [`recv_vectored`], and also
/// returns the address it came from (`recvmsg`, `WSARecvFrom`): the vectored
/// form of [`recv_from`], with the same meaning of the address.
///
/// Fails with `Unsupported` on WASI.
pub fn recv_from_vectored<S: AsSocket + ?Sized>(
    socket: &S,
    bufs: &mut [IoSliceMut<'_>],
    flags: RecvFlags,
) -> Result<(Received, Address)> {
    check_buffers(bufs.len())?;
    let mut addr = RawAddr::new();
    let (len, truncated) = sys::net::recv_vectored(raw(socket), bufs, flags, Some(&mut addr))?;
    let received = Received { len, truncated };
    Ok((received, addr.decode().unwrap_or(NO_ADDRESS)))
}

/// Which half of a connection [`shutdown`] closes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Shutdown {
    /// No more data will be received.
    Read,
    /// No more data will be sent: the peer reads the end of the stream once
    /// it has read what was sent before.
    Write,
    /// Both.
    Both,
}

/// Closes one or both halves of a connection, while keeping the socket
/// (`shutdown`).
///
/// Sending after the write half was shut down fails with `BrokenPipe`.
pub fn shutdown<S: AsSocket + ?Sized>(socket: &S, how: Shutdown) -> Result<()> {
    sys::net::shutdown(raw(socket), how)
}

/// The address the socket is bound to (`getsockname`).
///
/// A socket that is not bound has the unspecified address of its family:
/// `0.0.0.0:0`, `[::]:0` or [`UnixAddr::unnamed`]. (Windows reports an error
/// instead; oscall then asks for the socket's family, `SO_PROTOCOL_INFOW`.)
///
/// A socket of a family oscall has no address type for fails with
/// `Unsupported`, as does every socket on WASI.
pub fn local_addr<S: AsSocket + ?Sized>(socket: &S) -> Result<Address> {
    let mut addr = RawAddr::new();
    sys::net::local_addr(raw(socket), &mut addr)?;
    addr.decode().ok_or(ErrorKind::Unsupported.into())
}

/// The address of the peer the socket is connected to (`getpeername`).
///
/// Fails with `NotConnected` if there is none, and with `Unsupported` as
/// [`local_addr`] does.
pub fn peer_addr<S: AsSocket + ?Sized>(socket: &S) -> Result<Address> {
    let mut addr = RawAddr::new();
    sys::net::peer_addr(raw(socket), &mut addr)?;
    addr.decode().ok_or(ErrorKind::Unsupported.into())
}

/// Puts the socket in non-blocking mode, or back in blocking mode
/// (`ioctl(FIONBIO)`, `ioctlsocket`, `fd_fdstat_set_flags`).
///
/// In non-blocking mode a call that would have to wait fails with
/// `WouldBlock` instead ([`connect`]: `InProgress`).
pub fn set_nonblocking<S: AsSocket + ?Sized>(socket: &S, nonblocking: bool) -> Result<()> {
    sys::net::set_nonblocking(raw(socket), nonblocking)
}

// ---------------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------------

/// The options that are one integer, named portably for the backends.
#[derive(Clone, Copy)]
#[allow(dead_code)] // WebAssembly has none of them
pub(crate) enum Opt {
    ReuseAddr,
    KeepAlive,
    Broadcast,
    SendBuffer,
    RecvBuffer,
    Error,
    NoDelay,
    KeepAliveIdle,
    KeepAliveInterval,
    KeepAliveCount,
    Ttl,
    MulticastTtlV4,
    MulticastLoopV4,
    HopLimit,
    MulticastHopsV6,
    MulticastLoopV6,
    OnlyV6,
}

/// The two directions of a socket, for its timeouts.
#[derive(Clone, Copy)]
#[allow(dead_code)] // WebAssembly has no timeouts
pub(crate) enum Direction {
    Send,
    Recv,
}

fn set_bool<S: AsSocket + ?Sized>(socket: &S, opt: Opt, value: bool) -> Result<()> {
    sys::net::set_opt(raw(socket), opt, value as i32)
}

fn get_bool<S: AsSocket + ?Sized>(socket: &S, opt: Opt) -> Result<bool> {
    Ok(sys::net::get_opt(raw(socket), opt)? != 0)
}

fn set_uint<S: AsSocket + ?Sized>(socket: &S, opt: Opt, value: u32) -> Result<()> {
    let value = i32::try_from(value).map_err(|_| ErrorKind::InvalidInput)?;
    sys::net::set_opt(raw(socket), opt, value)
}

fn get_uint<S: AsSocket + ?Sized>(socket: &S, opt: Opt) -> Result<u32> {
    Ok(sys::net::get_opt(raw(socket), opt)?.max(0) as u32)
}

/// Lets the socket bind to a local address that is still held by
/// connections of a previous socket: what a server sets to restart at once
/// (`SO_REUSEADDR`). Set it before [`bind`].
///
/// It does not let two sockets listen on the same address and port. Windows'
/// own `SO_REUSEADDR` would, so oscall does not use it there: Windows allows
/// rebinding by default, and this option is mapped to the absence of
/// `SO_EXCLUSIVEADDRUSE`. The option therefore reads `true` on a new socket
/// on Windows and `false` elsewhere.
///
/// What it means for datagram sockets bound to the same multicast address
/// depends on the system.
pub fn set_reuse_addr<S: AsSocket + ?Sized>(socket: &S, reuse: bool) -> Result<()> {
    set_bool(socket, Opt::ReuseAddr, reuse)
}

/// Whether [`set_reuse_addr`] is in effect.
pub fn reuse_addr<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
    get_bool(socket, Opt::ReuseAddr)
}

/// Sends small segments at once instead of gathering them (`TCP_NODELAY`:
/// turns off Nagle's algorithm). For TCP sockets.
pub fn set_nodelay<S: AsSocket + ?Sized>(socket: &S, nodelay: bool) -> Result<()> {
    set_bool(socket, Opt::NoDelay, nodelay)
}

/// Whether [`set_nodelay`] is in effect.
pub fn nodelay<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
    get_bool(socket, Opt::NoDelay)
}

/// Probes an idle connection to notice that the peer is gone
/// (`SO_KEEPALIVE`). The delays are the system's defaults (two hours of
/// silence before the first probe, usually), unless set with
/// [`set_keepalive_idle`], [`set_keepalive_interval`] and
/// [`set_keepalive_count`].
pub fn set_keepalive<S: AsSocket + ?Sized>(socket: &S, keepalive: bool) -> Result<()> {
    set_bool(socket, Opt::KeepAlive, keepalive)
}

/// Whether [`set_keepalive`] is in effect.
pub fn keepalive<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
    get_bool(socket, Opt::KeepAlive)
}

/// A duration in whole seconds, rounded up, as the options that count in
/// seconds take it.
fn whole_seconds(time: Duration) -> u32 {
    let up = time.subsec_nanos() != 0;
    time.as_secs()
        .saturating_add(up as u64)
        .min(i32::MAX as u64) as u32
}

fn set_seconds<S: AsSocket + ?Sized>(socket: &S, opt: Opt, time: Duration) -> Result<()> {
    if time.is_zero() {
        return Err(ErrorKind::InvalidInput.into());
    }
    sys::net::set_opt(raw(socket), opt, whole_seconds(time) as i32)
}

/// Sets how long a TCP connection stays silent before [keep-alive](set_keepalive)
/// probes start (`TCP_KEEPIDLE`; `TCP_KEEPALIVE` on macOS).
///
/// It only matters once [`set_keepalive`] is on. The time is in whole
/// seconds: a fraction is rounded up, zero fails with `InvalidInput`, and
/// the system refuses what is beyond its range (32767 seconds on Linux).
///
/// On Windows this needs Windows 10 version 1709.
pub fn set_keepalive_idle<S: AsSocket + ?Sized>(socket: &S, time: Duration) -> Result<()> {
    set_seconds(socket, Opt::KeepAliveIdle, time)
}

/// The value set by [`set_keepalive_idle`], or the system's default.
pub fn keepalive_idle<S: AsSocket + ?Sized>(socket: &S) -> Result<Duration> {
    Ok(Duration::from_secs(
        get_uint(socket, Opt::KeepAliveIdle)? as u64
    ))
}

/// Sets the time between two keep-alive probes that got no answer
/// (`TCP_KEEPINTVL`), in whole seconds like [`set_keepalive_idle`], with the
/// same limits.
pub fn set_keepalive_interval<S: AsSocket + ?Sized>(socket: &S, time: Duration) -> Result<()> {
    set_seconds(socket, Opt::KeepAliveInterval, time)
}

/// The value set by [`set_keepalive_interval`], or the system's default.
pub fn keepalive_interval<S: AsSocket + ?Sized>(socket: &S) -> Result<Duration> {
    Ok(Duration::from_secs(
        get_uint(socket, Opt::KeepAliveInterval)? as u64,
    ))
}

/// Sets how many keep-alive probes go unanswered before the connection is
/// given up (`TCP_KEEPCNT`): the next call on the socket then fails with
/// `TimedOut`.
///
/// Zero fails with `InvalidInput`; the system refuses what is beyond its
/// range (127 on Linux, 255 on Windows). On Windows this needs Windows 10
/// version 1703.
pub fn set_keepalive_count<S: AsSocket + ?Sized>(socket: &S, count: u32) -> Result<()> {
    if count == 0 {
        return Err(ErrorKind::InvalidInput.into());
    }
    set_uint(socket, Opt::KeepAliveCount, count)
}

/// The value set by [`set_keepalive_count`], or the system's default.
pub fn keepalive_count<S: AsSocket + ?Sized>(socket: &S) -> Result<u32> {
    get_uint(socket, Opt::KeepAliveCount)
}

/// Allows a datagram socket to send to a broadcast address
/// (`SO_BROADCAST`).
pub fn set_broadcast<S: AsSocket + ?Sized>(socket: &S, broadcast: bool) -> Result<()> {
    set_bool(socket, Opt::Broadcast, broadcast)
}

/// Whether [`set_broadcast`] is in effect.
pub fn broadcast<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
    get_bool(socket, Opt::Broadcast)
}

/// Sets what closing the socket does with data not sent yet (`SO_LINGER`).
///
/// `None`, the default, closes in the background. `Some(time)` makes closing
/// wait until the data is sent, for at most `time`; with a zero `time` the
/// connection is reset instead and the data discarded.
///
/// The time is in whole seconds: a fraction is rounded up, and a time beyond
/// what the system can hold (65535 seconds on Windows) is cut to that.
pub fn set_linger<S: AsSocket + ?Sized>(socket: &S, linger: Option<Duration>) -> Result<()> {
    let seconds = linger.map(whole_seconds);
    sys::net::set_linger(raw(socket), seconds)
}

/// The value set by [`set_linger`].
pub fn linger<S: AsSocket + ?Sized>(socket: &S) -> Result<Option<Duration>> {
    Ok(sys::net::linger(raw(socket))?.map(|seconds| Duration::from_secs(seconds as u64)))
}

/// Asks for a send buffer of `size` bytes (`SO_SNDBUF`).
///
/// The system bounds the size and may grant more than asked: Linux doubles
/// it to account for its own bookkeeping.
pub fn set_send_buffer_size<S: AsSocket + ?Sized>(socket: &S, size: usize) -> Result<()> {
    sys::net::set_opt(
        raw(socket),
        Opt::SendBuffer,
        size.min(i32::MAX as usize) as i32,
    )
}

/// The size of the send buffer, as the system reports it.
pub fn send_buffer_size<S: AsSocket + ?Sized>(socket: &S) -> Result<usize> {
    Ok(get_uint(socket, Opt::SendBuffer)? as usize)
}

/// Asks for a receive buffer of `size` bytes (`SO_RCVBUF`), with the same
/// reservations as [`set_send_buffer_size`].
pub fn set_recv_buffer_size<S: AsSocket + ?Sized>(socket: &S, size: usize) -> Result<()> {
    sys::net::set_opt(
        raw(socket),
        Opt::RecvBuffer,
        size.min(i32::MAX as usize) as i32,
    )
}

/// The size of the receive buffer, as the system reports it.
pub fn recv_buffer_size<S: AsSocket + ?Sized>(socket: &S) -> Result<usize> {
    Ok(get_uint(socket, Opt::RecvBuffer)? as usize)
}

fn set_timeout<S: AsSocket + ?Sized>(
    socket: &S,
    direction: Direction,
    timeout: Option<Duration>,
) -> Result<()> {
    // To the system a zero timeout means none: refuse it rather than turn
    // "do not wait" into "wait forever".
    if timeout == Some(Duration::ZERO) {
        return Err(ErrorKind::InvalidInput.into());
    }
    sys::net::set_timeout(raw(socket), direction, timeout)
}

/// Bounds the time a blocking [`send`] may wait (`SO_SNDTIMEO`). `None`, the
/// default, is no bound; a zero duration fails with `InvalidInput`.
///
/// When the time runs out the call fails with `WouldBlock` on Linux and
/// macOS and with `TimedOut` on Windows. The resolution is the microsecond,
/// or the millisecond on Windows; the duration is rounded up to it.
pub fn set_send_timeout<S: AsSocket + ?Sized>(socket: &S, timeout: Option<Duration>) -> Result<()> {
    set_timeout(socket, Direction::Send, timeout)
}

/// The value set by [`set_send_timeout`].
pub fn send_timeout<S: AsSocket + ?Sized>(socket: &S) -> Result<Option<Duration>> {
    sys::net::timeout(raw(socket), Direction::Send)
}

/// Bounds the time a blocking [`recv`] or [`accept`] may wait
/// (`SO_RCVTIMEO`), like [`set_send_timeout`] does for sending.
pub fn set_recv_timeout<S: AsSocket + ?Sized>(socket: &S, timeout: Option<Duration>) -> Result<()> {
    set_timeout(socket, Direction::Recv, timeout)
}

/// The value set by [`set_recv_timeout`].
pub fn recv_timeout<S: AsSocket + ?Sized>(socket: &S) -> Result<Option<Duration>> {
    sys::net::timeout(raw(socket), Direction::Recv)
}

/// Sets the time-to-live of the IPv4 packets the socket sends (`IP_TTL`):
/// the number of routers they may cross, from 1 to 255.
pub fn set_ttl<S: AsSocket + ?Sized>(socket: &S, ttl: u32) -> Result<()> {
    set_uint(socket, Opt::Ttl, ttl)
}

/// The value set by [`set_ttl`], or the system's default.
pub fn ttl<S: AsSocket + ?Sized>(socket: &S) -> Result<u32> {
    get_uint(socket, Opt::Ttl)
}

/// Sets the hop limit of the IPv6 packets the socket sends
/// (`IPV6_UNICAST_HOPS`): IPv6's time-to-live.
pub fn set_hop_limit<S: AsSocket + ?Sized>(socket: &S, hops: u32) -> Result<()> {
    set_uint(socket, Opt::HopLimit, hops)
}

/// The value set by [`set_hop_limit`], or the system's default. macOS does
/// not tell its default: until a limit is set, the result there is 0.
pub fn hop_limit<S: AsSocket + ?Sized>(socket: &S) -> Result<u32> {
    get_uint(socket, Opt::HopLimit)
}

/// Restricts an IPv6 socket to IPv6 (`IPV6_V6ONLY`). When off, the socket
/// also carries IPv4, with peers shown as IPv4-mapped addresses
/// (`::ffff:a.b.c.d`). Set it before [`bind`].
///
/// The default is the system's: on for Windows, off for macOS, configurable
/// (and usually off) on Linux. Set it to rely on it.
pub fn set_only_v6<S: AsSocket + ?Sized>(socket: &S, only_v6: bool) -> Result<()> {
    set_bool(socket, Opt::OnlyV6, only_v6)
}

/// Whether the IPv6 socket is restricted to IPv6: see [`set_only_v6`].
pub fn only_v6<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
    get_bool(socket, Opt::OnlyV6)
}

/// Joins an IPv4 multicast group (`IP_ADD_MEMBERSHIP`): the socket receives
/// the datagrams sent to `group` that arrive on the interface whose address
/// is `interface`. `Ipv4Addr::UNSPECIFIED` lets the system choose the
/// interface.
pub fn join_multicast_v4<S: AsSocket + ?Sized>(
    socket: &S,
    group: Ipv4Addr,
    interface: Ipv4Addr,
) -> Result<()> {
    sys::net::membership_v4(raw(socket), true, group.octets(), interface.octets())
}

/// Leaves a group joined with [`join_multicast_v4`], given the same
/// arguments (`IP_DROP_MEMBERSHIP`).
pub fn leave_multicast_v4<S: AsSocket + ?Sized>(
    socket: &S,
    group: Ipv4Addr,
    interface: Ipv4Addr,
) -> Result<()> {
    sys::net::membership_v4(raw(socket), false, group.octets(), interface.octets())
}

/// Sets whether the IPv4 multicast datagrams the socket sends are also
/// delivered to this host's own members of the group (`IP_MULTICAST_LOOP`;
/// on by default).
///
/// On Windows the option applies to the receiving socket rather than to the
/// sending one.
pub fn set_multicast_loop_v4<S: AsSocket + ?Sized>(socket: &S, enabled: bool) -> Result<()> {
    set_bool(socket, Opt::MulticastLoopV4, enabled)
}

/// Whether [`set_multicast_loop_v4`] is in effect.
pub fn multicast_loop_v4<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
    get_bool(socket, Opt::MulticastLoopV4)
}

/// Sets the time-to-live of the IPv4 multicast datagrams the socket sends
/// (`IP_MULTICAST_TTL`; 1 by default: the local network only).
pub fn set_multicast_ttl_v4<S: AsSocket + ?Sized>(socket: &S, ttl: u32) -> Result<()> {
    set_uint(socket, Opt::MulticastTtlV4, ttl)
}

/// The value set by [`set_multicast_ttl_v4`].
pub fn multicast_ttl_v4<S: AsSocket + ?Sized>(socket: &S) -> Result<u32> {
    get_uint(socket, Opt::MulticastTtlV4)
}

/// Joins an IPv6 multicast group (`IPV6_ADD_MEMBERSHIP`, `IPV6_JOIN_GROUP`)
/// on the interface of index `interface`; 0 lets the system choose it.
pub fn join_multicast_v6<S: AsSocket + ?Sized>(
    socket: &S,
    group: Ipv6Addr,
    interface: u32,
) -> Result<()> {
    sys::net::membership_v6(raw(socket), true, group.octets(), interface)
}

/// Leaves a group joined with [`join_multicast_v6`], given the same
/// arguments (`IPV6_DROP_MEMBERSHIP`, `IPV6_LEAVE_GROUP`).
pub fn leave_multicast_v6<S: AsSocket + ?Sized>(
    socket: &S,
    group: Ipv6Addr,
    interface: u32,
) -> Result<()> {
    sys::net::membership_v6(raw(socket), false, group.octets(), interface)
}

/// The IPv6 counterpart of [`set_multicast_loop_v4`]
/// (`IPV6_MULTICAST_LOOP`).
pub fn set_multicast_loop_v6<S: AsSocket + ?Sized>(socket: &S, enabled: bool) -> Result<()> {
    set_bool(socket, Opt::MulticastLoopV6, enabled)
}

/// Whether [`set_multicast_loop_v6`] is in effect.
pub fn multicast_loop_v6<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
    get_bool(socket, Opt::MulticastLoopV6)
}

/// Sets the hop limit of the IPv6 multicast datagrams the socket sends
/// (`IPV6_MULTICAST_HOPS`; 1 by default).
pub fn set_multicast_hops_v6<S: AsSocket + ?Sized>(socket: &S, hops: u32) -> Result<()> {
    set_uint(socket, Opt::MulticastHopsV6, hops)
}

/// The value set by [`set_multicast_hops_v6`].
pub fn multicast_hops_v6<S: AsSocket + ?Sized>(socket: &S) -> Result<u32> {
    get_uint(socket, Opt::MulticastHopsV6)
}

/// Makes an Internet socket send through the interface of index `index`,
/// whatever the routing table says; 0 lets the routing table choose again
/// (`SO_BINDTOIFINDEX` on Linux; `IP_BOUND_IF` or `IPV6_BOUND_IF` on macOS;
/// `IP_UNICAST_IF` or `IPV6_UNICAST_IF` on Windows).
///
/// This is how a host with several interfaces chooses the one a connection
/// or a datagram leaves from. What it does beyond that differs:
///
/// - On Linux the socket is bound to the device: it also receives only
///   what arrives on that interface. Going back to 0, or to another
///   interface, needs the `CAP_NET_RAW` privilege (`PermissionDenied`).
/// - On macOS the socket is scoped to the interface, for what it sends and
///   for the addresses it can reach.
/// - On Windows only the unicast packets sent are affected: the socket
///   receives from every interface.
///
/// An index that names no interface is refused by macOS, and by Windows
/// for an IPv6 socket. Linux takes any number, and the socket then has no
/// interface to send through; so does Windows for an IPv4 socket. Take the
/// index from [`interfaces`].
///
/// Linux and macOS can tell which interface a socket is bound to
/// ([`unix::bound_interface`]); Windows cannot: reading `IP_UNICAST_IF`
/// back does not give the index that was set.
///
/// The socket must be an IPv4 or IPv6 one: another family fails with
/// `InvalidInput` on macOS and Windows, which ask the socket for its family
/// first (`getsockname`). Fails with `Unsupported` on WebAssembly.
pub fn bind_interface<S: AsSocket + ?Sized>(socket: &S, index: u32) -> Result<()> {
    if index > i32::MAX as u32 {
        return Err(ErrorKind::InvalidInput.into());
    }
    sys::net::bind_interface(raw(socket), index)
}

/// Returns the error pending on the socket, and clears it (`SO_ERROR`).
///
/// This is how the outcome of a non-blocking [`connect`] is read once the
/// socket is writable: `None` means it succeeded.
pub fn take_error<S: AsSocket + ?Sized>(socket: &S) -> Result<Option<Error>> {
    let code = sys::net::get_opt(raw(socket), Opt::Error)?;
    Ok((code != 0).then(|| Error::from_raw_os_error(code)))
}

/// The type the socket was created with (`SO_TYPE`; on WASI,
/// `fd_fdstat_get`).
///
/// Fails with `Unsupported` for a type [`Type`] does not have.
pub fn socket_type<S: AsSocket + ?Sized>(socket: &S) -> Result<Type> {
    sys::net::socket_type(raw(socket))
}

// ---------------------------------------------------------------------------
// Interfaces
// ---------------------------------------------------------------------------

flags! {
    /// The state of a network [`Interface`].
    pub struct InterfaceFlags: u32 {
        /// The interface is up: it can carry packets (`IFF_UP`; on
        /// Windows, an operational status of `IfOperStatusUp`).
        const UP = 1;
        /// The interface is a loopback: what is sent to it comes back to
        /// this host (`IFF_LOOPBACK`, `IF_TYPE_SOFTWARE_LOOPBACK`).
        const LOOPBACK = 2;
    }
}

/// What a backend calls with each interface: its index, its name, whether it
/// is up and whether it is a loopback.
pub(crate) type InterfaceVisitor<'a> = dyn FnMut(u32, &[u8], bool, bool) + 'a;

/// What a backend calls with each address: the index of its interface, the
/// address and the length of its prefix.
pub(crate) type AddrVisitor<'a> = dyn FnMut(u32, IpAddr, u8) + 'a;

/// A network interface of the system, as [`interfaces`] reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Interface<'a> {
    index: u32,
    name: &'a [u8],
    flags: InterfaceFlags,
}

impl<'a> Interface<'a> {
    /// The index of the interface: the number that names it to
    /// [`join_multicast_v6`], to [`bind_interface`] and as the scope of a
    /// link-local [`SocketAddrV6`]. It is never 0, and stays the same for
    /// as long as the interface exists.
    pub fn index(&self) -> u32 {
        self.index
    }

    /// The name of the interface, if it is UTF-8, which it is in practice:
    /// see [`name_bytes`](Self::name_bytes).
    pub fn name(&self) -> Option<&'a str> {
        core::str::from_utf8(self.name).ok()
    }

    /// The name of the interface.
    ///
    /// On Linux and macOS it is the short name the system's tools use
    /// (`lo`, `eth0`, `en0`), which on Linux can be any bytes. On Windows
    /// it is the name shown to users (`Ethernet`, `Wi-Fi`,
    /// `Loopback Pseudo-Interface 1`), converted to UTF-8; users can
    /// change it.
    pub fn name_bytes(&self) -> &'a [u8] {
        self.name
    }

    /// The state of the interface.
    pub fn flags(&self) -> InterfaceFlags {
        self.flags
    }

    /// Whether the interface is up ([`InterfaceFlags::UP`]).
    pub fn is_up(&self) -> bool {
        self.flags.contains(InterfaceFlags::UP)
    }

    /// Whether the interface is a loopback ([`InterfaceFlags::LOOPBACK`]).
    pub fn is_loopback(&self) -> bool {
        self.flags.contains(InterfaceFlags::LOOPBACK)
    }
}

/// An address of a network interface, as [`interface_addrs`] reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct InterfaceAddr {
    interface: u32,
    addr: IpAddr,
    prefix_len: u8,
}

impl InterfaceAddr {
    /// The [index](Interface::index) of the interface that has the address.
    pub fn interface(&self) -> u32 {
        self.interface
    }

    /// The address.
    pub fn addr(&self) -> IpAddr {
        self.addr
    }

    /// The length of the network prefix, in bits: how much of the address
    /// names the network the interface is on (24 for a netmask of
    /// `255.255.255.0`).
    pub fn prefix_len(&self) -> u8 {
        self.prefix_len
    }
}

/// Calls `f` with each network interface of the system, in the system's
/// order.
///
/// Nothing is allocated by oscall: the interfaces are visited as the system
/// lists them. Those that are down are listed too. The addresses are
/// another list: [`interface_addrs`].
///
/// - Linux has no system call for this: oscall asks over a `NETLINK_ROUTE`
///   socket (an `RTM_GETLINK` dump), which it opens and closes. If the
///   configuration changes while the kernel lists it, the call fails with
///   `Interrupted` after `f` saw what may be an inconsistent list: call
///   again.
/// - macOS: `getifaddrs`, which allocates the list in the C library.
/// - Windows: `GetAdaptersAddresses`, into 32 KiB of stack; a machine with
///   more adapters than fit needs the `alloc` feature, without which the
///   call fails (`ERROR_BUFFER_OVERFLOW`).
///
/// Fails with `Unsupported` on WebAssembly.
pub fn interfaces<F: FnMut(&Interface<'_>)>(mut f: F) -> Result<()> {
    sys::net::interfaces(&mut |index, name, up, loopback| {
        let mut flags = InterfaceFlags::empty();
        if up {
            flags |= InterfaceFlags::UP;
        }
        if loopback {
            flags |= InterfaceFlags::LOOPBACK;
        }
        f(&Interface { index, name, flags });
    })
}

/// Calls `f` with each IPv4 and IPv6 address of each network interface, in
/// the system's order: an `RTM_GETADDR` dump on Linux, and otherwise as
/// [`interfaces`], with the same reservations.
///
/// The address of an interface is the one this host has on it, also on a
/// point-to-point link. An IPv6 link-local address is reported without its
/// scope: the scope is [`InterfaceAddr::interface`].
///
/// Every address the system holds is listed, whatever its state: also
/// those of interfaces that are down, and IPv6 addresses that are not
/// usable yet or any more (tentative, deprecated).
///
/// Fails with `Unsupported` on WebAssembly.
pub fn interface_addrs<F: FnMut(&InterfaceAddr)>(mut f: F) -> Result<()> {
    sys::net::interface_addrs(&mut |interface, addr, prefix_len| {
        f(&InterfaceAddr {
            interface,
            addr,
            prefix_len,
        });
    })
}

// ---------------------------------------------------------------------------
// Extensions
// ---------------------------------------------------------------------------

/// What Linux and macOS have and Windows has not.
#[cfg(any(target_os = "linux", target_os = "fullrust", target_os = "macos"))]
pub mod unix {
    use super::*;

    /// For [`send`] and [`send_to`]: do not wait, whatever the mode of the
    /// socket, and fail with `WouldBlock` instead (`MSG_DONTWAIT`).
    pub const SEND_DONT_WAIT: SendFlags = SendFlags(DONT_WAIT);

    /// For [`recv`] and [`recv_from`]: do not wait, whatever the mode of the
    /// socket, and fail with `WouldBlock` instead (`MSG_DONTWAIT`).
    pub const RECV_DONT_WAIT: RecvFlags = RecvFlags(DONT_WAIT);

    /// The most handles one message carries (`SCM_MAX_FD` on Linux; macOS
    /// would take one more).
    pub const MAX_HANDLES: usize = 253;

    /// Room for the control data of any message a Unix-domain socket
    /// delivers: `MAX_HANDLES` descriptors need half of it on Linux, and
    /// macOS cannot queue a control message longer than this (`MCLBYTES`).
    const CONTROL_SIZE: usize = 2048;

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

    /// The size of `cmsg_len`, which differs between the systems and is
    /// also what control messages are aligned to.
    const LEN: usize = sys::net::CMSG_LEN_BYTES;
    /// The size of `struct cmsghdr`: the length, the level and the type.
    /// It is a multiple of the alignment on every target.
    const HEADER: usize = LEN + 8;

    /// `CMSG_ALIGN`.
    const fn cmsg_align(len: usize) -> usize {
        (len + LEN - 1) & !(LEN - 1)
    }

    fn put_cmsg_len(header: &mut [u8], len: usize) {
        if LEN == size_of::<usize>() {
            header[..LEN].copy_from_slice(&len.to_ne_bytes());
        } else {
            header[..4].copy_from_slice(&(len as u32).to_ne_bytes());
        }
    }

    fn cmsg_len(header: &[u8]) -> usize {
        if LEN == size_of::<usize>() {
            let mut bytes = [0; size_of::<usize>()];
            bytes.copy_from_slice(&header[..LEN]);
            usize::from_ne_bytes(bytes)
        } else {
            u32::from_ne_bytes([header[0], header[1], header[2], header[3]]) as usize
        }
    }

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

    /// What [`recv_with_handles`] received.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub struct ReceivedHandles {
        /// How many bytes were written to the buffers.
        pub len: usize,
        /// Whether the datagram was longer than the buffers, and its end
        /// lost: see [`Received::truncated`].
        pub truncated: bool,
        /// How many handles were received: they are in the first slots.
        pub handles: usize,
        /// Whether the message carried handles that are not among them,
        /// for lack of slots or because the system cut the control data
        /// (`MSG_CTRUNC`). Those handles were closed; none is leaked.
        pub handles_truncated: bool,
    }

    /// Sends the content of `bufs` like [`send_vectored`], and with it the
    /// handles of `handles`: the receiver gets handles of its own to the
    /// same open files, sockets or pipes, as if duplicated across the two
    /// processes (`sendmsg` with an `SCM_RIGHTS` control message).
    ///
    /// The socket must be a Unix-domain one. The handles are only borrowed:
    /// the sender keeps its own, and may close them as soon as the call
    /// returns. Receive them with [`recv_with_handles`]; a receiver that
    /// uses [`recv`] instead gets the data alone, and the handles are
    /// dropped.
    ///
    /// At most [`MAX_HANDLES`] handles (`InvalidInput` beyond). On a stream,
    /// send at least one byte with them: handles attached to no data are
    /// not sent at all on Linux. The handles travel with the first byte of
    /// the data they were sent with.
    pub fn send_with_handles<S: AsSocket + ?Sized>(
        socket: &S,
        bufs: &[IoSlice<'_>],
        handles: &[crate::BorrowedHandle<'_>],
        flags: SendFlags,
    ) -> Result<usize> {
        check_buffers(bufs.len())?;
        if handles.len() > MAX_HANDLES {
            return Err(ErrorKind::InvalidInput.into());
        }
        let mut control = Control([0; CONTROL_SIZE]);
        let mut len = 0;
        if !handles.is_empty() {
            // One message: its header, then the descriptors.
            let data = 4 * handles.len();
            let buf = &mut control.0;
            put_cmsg_len(buf, HEADER + data);
            buf[LEN..LEN + 4].copy_from_slice(&sys::net::CMSG_SOL_SOCKET.to_ne_bytes());
            buf[LEN + 4..HEADER].copy_from_slice(&sys::net::SCM_RIGHTS.to_ne_bytes());
            let (slots, _) = buf[HEADER..].as_chunks_mut::<4>();
            for (slot, handle) in slots.iter_mut().zip(handles) {
                *slot = handle.as_raw().to_ne_bytes();
            }
            len = HEADER + cmsg_align(data);
        }
        sys::net::send_control(raw(socket), bufs, flags, &control.0[..len])
    }

    /// Receives data like [`recv_vectored`], and the handles that were sent
    /// with it by [`send_with_handles`] (`recvmsg`).
    ///
    /// The handles are written to the first slots of `handles`, as `Some`;
    /// what a slot held before is dropped, and the other slots are left
    /// alone. They are owned by the caller and, like every handle of
    /// oscall, not inherited by child processes (`MSG_CMSG_CLOEXEC` on
    /// Linux; on macOS the flag is set right after the call, not
    /// atomically).
    ///
    /// **No handle is ever leaked**: if the message carries more handles
    /// than there are slots, the others are closed and
    /// [`handles_truncated`](ReceivedHandles::handles_truncated) says so.
    /// oscall always gives the system room for the control data of the
    /// largest message, whatever the number of slots, since macOS would
    /// otherwise leave the handles that did not fit open in the process,
    /// out of reach.
    ///
    /// On a stream, one call does not read past the data a set of handles
    /// was sent with, so that sets are not mixed.
    ///
    /// [`RecvFlags::PEEK`] fails with `InvalidInput`: peeking at a message
    /// would create handles on Linux and report meaningless ones on macOS.
    pub fn recv_with_handles<S: AsSocket + ?Sized>(
        socket: &S,
        bufs: &mut [IoSliceMut<'_>],
        handles: &mut [Option<crate::OwnedHandle>],
        flags: RecvFlags,
    ) -> Result<ReceivedHandles> {
        check_buffers(bufs.len())?;
        if flags.contains(RecvFlags::PEEK) {
            return Err(ErrorKind::InvalidInput.into());
        }
        let mut control = Control([0; CONTROL_SIZE]);
        let (len, truncated, control_truncated, control_len) =
            sys::net::recv_control(raw(socket), bufs, flags, &mut control.0)?;
        let mut received = ReceivedHandles {
            len,
            truncated,
            handles: 0,
            handles_truncated: control_truncated,
        };
        let data = &control.0[..control_len.min(CONTROL_SIZE)];
        let mut at = 0;
        while data.len() - at >= HEADER {
            let message = &data[at..];
            let message_len = cmsg_len(message);
            if message_len < HEADER {
                break;
            }
            // A message cut by the system says its full length.
            let end = message_len.min(message.len());
            let is_rights = int_at(message, LEN) == sys::net::CMSG_SOL_SOCKET
                && int_at(message, LEN + 4) == sys::net::SCM_RIGHTS;
            if is_rights {
                for fd in message[HEADER..end].as_chunks::<4>().0 {
                    let fd = i32::from_ne_bytes(*fd);
                    if fd < 0 {
                        continue;
                    }
                    // SAFETY: the system just created this descriptor for
                    // the process, and nothing else knows of it. Owning it
                    // at once is what closes it on every path below.
                    let handle = unsafe { crate::OwnedHandle::from_raw(fd) };
                    let slot = handles.get_mut(received.handles);
                    match (slot, sys::net::received_handle(fd)) {
                        (Some(slot), Ok(())) => {
                            *slot = Some(handle);
                            received.handles += 1;
                        }
                        _ => received.handles_truncated = true,
                    }
                }
            }
            at = match at.checked_add(cmsg_align(message_len)) {
                Some(next) if next <= data.len() => next,
                _ => break,
            };
        }
        Ok(received)
    }

    /// Who is at the other end of a Unix-domain socket.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub struct PeerCred {
        /// The effective user of the peer.
        pub uid: u32,
        /// The effective group of the peer.
        pub gid: u32,
        /// The process of the peer, when the system tells.
        pub pid: Option<u32>,
    }

    /// The credentials of the process that connected the socket, or that
    /// listened on the other end: its user, its group and its process, as
    /// they were when it called [`connect`], [`listen`] or [`pair`]
    /// (`SO_PEERCRED` on Linux; `LOCAL_PEERCRED` and `LOCAL_PEERPID` on
    /// macOS). The system recorded them: the peer cannot forge them.
    ///
    /// The socket must be a connected Unix-domain stream socket: anything
    /// else fails, with `NotConnected` or `InvalidInput`. (Linux also
    /// answers for the datagram sockets of a [`pair`].)
    ///
    /// A handle can be passed to another process, and a process can change
    /// its user after connecting: the credentials say who opened the
    /// connection, not who is writing to it now.
    pub fn peer_cred<S: AsSocket + ?Sized>(socket: &S) -> Result<PeerCred> {
        let (uid, gid, pid) = sys::net::peer_cred(raw(socket))?;
        Ok(PeerCred { uid, gid, pid })
    }

    /// The index of the interface set by [`bind_interface`], or 0 if the
    /// socket is bound to none (`SO_BINDTOIFINDEX`; `IP_BOUND_IF` or
    /// `IPV6_BOUND_IF`).
    pub fn bound_interface<S: AsSocket + ?Sized>(socket: &S) -> Result<u32> {
        sys::net::bound_interface(raw(socket))
    }

    /// Lets several sockets bind the same address and port, if each sets
    /// this before [`bind`] (`SO_REUSEPORT`).
    ///
    /// What the sockets then share differs, and this is why the option is
    /// not portable:
    ///
    /// - On Linux, incoming connections and datagrams are distributed
    ///   between the sockets (by a hash of the peer's address): the way
    ///   several threads or processes share the load of one port. All the
    ///   sockets must belong to the same user.
    /// - On macOS, there is no distribution: which socket gets a
    ///   connection or a unicast datagram is not specified, and in
    ///   practice it is the last one bound. Multicast and broadcast
    ///   datagrams are delivered to each of the sockets.
    ///
    /// On both, [`set_reuse_addr`] is what several datagram sockets set to
    /// receive the same multicast group on one port.
    pub fn set_reuse_port<S: AsSocket + ?Sized>(socket: &S, reuse: bool) -> Result<()> {
        sys::net::set_ext_opt(raw(socket), sys::net::ExtOpt::ReusePort, reuse as i32)
    }

    /// Whether [`set_reuse_port`] is in effect.
    pub fn reuse_port<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
        Ok(sys::net::get_ext_opt(raw(socket), sys::net::ExtOpt::ReusePort)? != 0)
    }

    /// Creates two Unix-domain sockets connected to each other
    /// (`socketpair`). Neither has a name.
    ///
    /// `ty` is [`Type::Stream`] or [`Type::Datagram`], or on Linux
    /// [`Type::SeqPacket`]. Like every socket of oscall, they are not
    /// inherited by child processes.
    pub fn pair(ty: Type) -> Result<(OwnedSocket, OwnedSocket)> {
        let (a, b) = sys::net::pair(ty)?;
        Ok((OwnedSocket(a), OwnedSocket(b)))
    }
}

/// What only Linux has.
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
pub mod linux {
    use super::*;

    /// The Unix-domain address with the abstract name `name`: a name that is
    /// not in the filesystem, and disappears with the last socket bound to
    /// it.
    ///
    /// The name is any bytes, at most 107 of them (`InvalidInput` beyond).
    pub fn abstract_addr(name: &[u8]) -> Result<UnixAddr> {
        // The name follows a NUL in `sun_path`.
        if name.len() >= sys::net::UNIX_PATH_MAX {
            return Err(ErrorKind::InvalidInput.into());
        }
        Ok(UnixAddr::from_parts(UnixKind::Abstract, name))
    }

    fn set<S: AsSocket + ?Sized>(socket: &S, opt: sys::net::ExtOpt, value: i32) -> Result<()> {
        sys::net::set_ext_opt(raw(socket), opt, value)
    }

    fn get<S: AsSocket + ?Sized>(socket: &S, opt: sys::net::ExtOpt) -> Result<i32> {
        sys::net::get_ext_opt(raw(socket), opt)
    }

    /// Holds back what a TCP socket sends until a full segment is ready, or
    /// until the option is turned off, which sends what is held
    /// (`TCP_CORK`). The kernel does not hold data for more than 200
    /// milliseconds.
    ///
    /// It is for a sender that writes a message in several calls and wants
    /// it in as few packets as possible: cork, write, uncork.
    pub fn set_cork<S: AsSocket + ?Sized>(socket: &S, cork: bool) -> Result<()> {
        set(socket, sys::net::ExtOpt::Cork, cork as i32)
    }

    /// Whether [`set_cork`] is in effect.
    pub fn cork<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
        Ok(get(socket, sys::net::ExtOpt::Cork)? != 0)
    }

    /// Makes a TCP socket acknowledge what it receives at once rather than
    /// wait for data to send along (`TCP_QUICKACK`), or with `false` lets
    /// it delay acknowledgements.
    ///
    /// The setting is not permanent: the kernel goes back to its own
    /// judgement as the connection goes on. Set it again after a receive
    /// to keep it.
    pub fn set_quickack<S: AsSocket + ?Sized>(socket: &S, quickack: bool) -> Result<()> {
        set(socket, sys::net::ExtOpt::QuickAck, quickack as i32)
    }

    /// Whether the socket acknowledges at once now: see [`set_quickack`].
    pub fn quickack<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
        Ok(get(socket, sys::net::ExtOpt::QuickAck)? != 0)
    }

    /// Lets a listening TCP socket accept connections that carry data in
    /// their first packet (TCP Fast Open, `TCP_FASTOPEN`), with at most
    /// `queue` of them waiting for the end of their handshake; 0 turns it
    /// off. Set it before or after [`listen`].
    ///
    /// The system must allow it for servers (`net.ipv4.tcp_fastopen`),
    /// and clients must ask for it.
    pub fn set_fastopen<S: AsSocket + ?Sized>(socket: &S, queue: u32) -> Result<()> {
        set(
            socket,
            sys::net::ExtOpt::FastOpen,
            queue.min(i32::MAX as u32) as i32,
        )
    }

    /// The value set by [`set_fastopen`].
    pub fn fastopen<S: AsSocket + ?Sized>(socket: &S) -> Result<u32> {
        Ok(get(socket, sys::net::ExtOpt::FastOpen)?.max(0) as u32)
    }

    /// The name servers and the search list of the system, as
    /// `/etc/resolv.conf` has them: what [`resolve`] asks
    /// when `/etc/hosts` does not know. A file that is missing, or names
    /// no server, gives the server of the machine itself (`127.0.0.1`),
    /// as it does to a C library.
    ///
    /// Fails if the file is there and cannot be read.
    pub fn dns_config() -> Result<super::dns::Config> {
        sys::resolve::config()
    }

    /// The abstract name of `addr`, if it is an abstract address.
    pub fn abstract_name(addr: &UnixAddr) -> Option<&[u8]> {
        match addr.kind {
            UnixKind::Abstract => Some(&addr.bytes[..addr.len as usize]),
            _ => None,
        }
    }
}

/// What only Windows has.
#[cfg(windows)]
pub mod windows {
    use super::*;

    /// Lets the socket bind an address and port that another socket has
    /// bound, if that one set this option too: Windows' own `SO_REUSEADDR`.
    /// Set it before [`bind`].
    ///
    /// This is what several datagram sockets need to receive the same
    /// multicast group on one port, which [`set_reuse_addr`](super::set_reuse_addr)
    /// gives elsewhere and does not give on Windows. It is not for servers:
    /// between two stream sockets bound to the same port, which one gets a
    /// connection is not defined, and a socket of another program that sets
    /// the option can take over the port of one that did.
    ///
    /// It excludes `SO_EXCLUSIVEADDRUSE`, which is what
    /// [`set_reuse_addr(socket, false)`](super::set_reuse_addr) sets: after
    /// one of the two, the other fails with `InvalidInput`.
    pub fn set_reuse_addr<S: AsSocket + ?Sized>(socket: &S, reuse: bool) -> Result<()> {
        sys::net::set_ext_opt(raw(socket), sys::net::ExtOpt::ReuseAddr, reuse as i32)
    }

    /// Whether [`set_reuse_addr`] is in effect.
    pub fn reuse_addr<S: AsSocket + ?Sized>(socket: &S) -> Result<bool> {
        Ok(sys::net::get_ext_opt(raw(socket), sys::net::ExtOpt::ReuseAddr)? != 0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn addresses_round_trip() {
        let v4 = Address::from(SocketAddrV4::new(Ipv4Addr::new(192, 0, 2, 7), 8080));
        let raw = RawAddr::encode(&v4).unwrap();
        assert_eq!(raw.len(), 16);
        assert_eq!(raw.bytes[2..8], [0x1f, 0x90, 192, 0, 2, 7]);
        assert_eq!(raw.decode(), Some(v4));

        let ip = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
        let v6 = Address::from(SocketAddrV6::new(ip, 443, 5, 9));
        let raw = RawAddr::encode(&v6).unwrap();
        assert_eq!(raw.len(), 28);
        assert_eq!(raw.bytes[8..24], ip.octets());
        assert_eq!(raw.decode(), Some(v6));

        let unix = Address::from(UnixAddr::new("some/socket").unwrap());
        let raw = RawAddr::encode(&unix).unwrap();
        assert_eq!(raw.len(), 2 + 11 + 1);
        assert_eq!(raw.decode(), Some(unix));
        assert_eq!(
            unix.as_unix().unwrap().path_bytes(),
            Some(&b"some/socket"[..])
        );

        // No address, and an address with no name.
        assert_eq!(RawAddr::new().decode(), None);
        let mut raw = RawAddr::encode(&unix).unwrap();
        raw.set_len(2);
        assert_eq!(raw.decode(), Some(NO_ADDRESS));
        assert!(RawAddr::encode(&NO_ADDRESS).is_err());

        assert!(UnixAddr::new("").is_err());
        assert!(UnixAddr::new("a\0b").is_err());
        assert!(UnixAddr::new(&[b'a'; 200][..]).is_err());
    }
}