net-io 0.8.0

Network IO substrate for Rust: TCP, UDP and local-socket listeners, connection lifecycle, limits, graceful drain, PROXY protocol, and a TLS seam. Protocol-free and dependency-free.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
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
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
//! The connection core shared by `TcpConnection` and the server's workers:
//! deadlines per phase, the minimum transfer rate, the gate check before every
//! send, kill detection, and graceful or abortive close.

use std::io::{self, IoSlice};
use std::net::Shutdown;
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::buf::Buffer;
use crate::error::{
    CloseReason, Direction, KillReason, LimitKind, NetError, OsErrorClass, TimeoutKind,
};
use crate::gate::{Denial, ErasedGate, WriteCheck};
use crate::info::{ConnectionInfo, GateTag, Transport};
use crate::limits::Effective;
use crate::rate::Rate;
use crate::session::Phase;
use crate::sys::{self, AsSock, Interest, KillSlot, Ready, SlotLease, Wake};
use crate::tcp::Health;
use crate::time::Clock;
use crate::tls::{TlsError, TlsEvent, TlsFailure, TlsSession};

/// Where time comes from.
#[derive(Clone)]
pub(crate) enum ClockRef {
    Monotonic,
    Custom(Arc<dyn Clock>),
    /// The time of this reactor turn: one clock read per trip through the OS, however
    /// many connections and deadlines the turn touches. Off a worker's thread, the
    /// clock itself.
    #[cfg(feature = "reactor")]
    Turn,
}

#[cfg(feature = "reactor")]
thread_local! {
    static TURN: std::cell::Cell<Option<Instant>> = const { std::cell::Cell::new(None) };
}

/// A new reactor turn: reads the clock for it.
#[cfg(feature = "reactor")]
pub(crate) fn begin_turn() {
    TURN.with(|t| t.set(Some(Instant::now())));
}

impl ClockRef {
    #[inline]
    pub(crate) fn now(&self) -> Instant {
        match self {
            ClockRef::Monotonic => Instant::now(),
            ClockRef::Custom(c) => c.now(),
            #[cfg(feature = "reactor")]
            ClockRef::Turn => TURN.with(std::cell::Cell::get).unwrap_or_else(Instant::now),
        }
    }
}

/// The wake channel a connection's owner waits on.
#[derive(Clone, Debug)]
pub(crate) enum WakeSource {
    /// A worker's own channel, registered in the kill slot once.
    Fixed(Arc<Wake>),
    /// The calling thread's channel, registered around each wait.
    Thread,
    /// None: a reactor worker never waits on one connection.
    #[cfg_attr(not(feature = "reactor"), allow(dead_code))]
    Reactor,
}

thread_local! {
    static THREAD_WAKE: std::cell::OnceCell<ThreadWake> = const { std::cell::OnceCell::new() };
}

/// Wakes of threads that ended, for the next thread that needs one (Windows). A
/// thread-local destructor runs under the Windows loader lock, where closing a
/// socket can deadlock the whole process against a thread that is loading a
/// Winsock extension (D-173), so there a thread's wake is never closed when it
/// ends. Elsewhere it closes with its thread, which returns its descriptors.
static SPARE_WAKES: std::sync::Mutex<Vec<Arc<Wake>>> = std::sync::Mutex::new(Vec::new());

/// A thread's wake channel; on Windows given back to `SPARE_WAKES` when the thread
/// ends.
struct ThreadWake(Option<Arc<Wake>>);

impl Drop for ThreadWake {
    fn drop(&mut self) {
        if !cfg!(windows) {
            return;
        }
        if let Some(w) = self.0.take() {
            match SPARE_WAKES.lock() {
                Ok(mut spare) => spare.push(w),
                // Never close it here, even if that leaks it.
                Err(_) => std::mem::forget(w),
            }
        }
    }
}

fn thread_wake() -> Option<Arc<Wake>> {
    THREAD_WAKE.with(|cell| {
        cell.get_or_init(|| {
            let spare = SPARE_WAKES.lock().ok().and_then(|mut s| s.pop());
            ThreadWake(spare.or_else(|| Wake::new().ok().map(Arc::new)))
        })
        .0
        .clone()
    })
}

/// What a read produced.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Got {
    Data(usize),
    Eof,
    Woken,
}

/// `Link::drains` bits.
const DRAIN_HOOK: u8 = 1;
const DRAIN_REACHED: u8 = 2;
const DRAIN_KEPT: u8 = 4;
/// Not a drain bit: net-io still picks the phase (the owner never set one).
const AUTO_PHASE: u8 = 8;
/// Not a drain bit: the session's last bytes went out while the connection was
/// idle (a reply at open, a push). The peer may be sending its own request, so a
/// close lingers instead of taking the idle shortcut; otherwise that request draws
/// a reset and the peer's stack can discard the reply it already holds (D-192).
const SPOKE_IDLE: u8 = 16;
/// Not a drain bit: the session was given input in this exchange, so what it sends
/// while idle is its answer, not news the peer did not ask for. Cleared when the
/// exchange ends (`settle_phase` with nothing left over and the phase `Idle`).
const HEARD: u8 = 32;

/// Soft closes in progress across a server, against `Limits::denial_linger_max`.
#[derive(Debug)]
pub(crate) struct SoftCloses {
    live: std::sync::atomic::AtomicU32,
    max: u32,
}

impl SoftCloses {
    pub(crate) fn new(max: u32) -> Arc<SoftCloses> {
        Arc::new(SoftCloses {
            live: std::sync::atomic::AtomicU32::new(0),
            max,
        })
    }

    /// One place, or `None` when `max` are taken.
    fn take(self: &Arc<Self>) -> Option<SoftPermit> {
        use std::sync::atomic::Ordering;
        let mut n = self.live.load(Ordering::Acquire);
        while n < self.max {
            match self
                .live
                .compare_exchange_weak(n, n + 1, Ordering::AcqRel, Ordering::Acquire)
            {
                Ok(_) => return Some(SoftPermit(self.clone())),
                Err(seen) => n = seen,
            }
        }
        None
    }
}

/// A place among the soft closes, given back when the connection closes.
#[derive(Debug)]
struct SoftPermit(Arc<SoftCloses>);

/// A connection's soft close: allocated only on a connection that has one, so an
/// idle connection carries one pointer for it.
#[derive(Debug, Default)]
struct SoftClose {
    /// When a soft kill stops letting output go out: set when the owner first sees
    /// it, from its bound.
    until: Option<Instant>,
    /// This connection's place among the server's soft closes, once it took one.
    permit: Option<SoftPermit>,
    /// It may close softly (it has its place, or runs outside a server).
    placed: bool,
    /// The server's places were all taken: the close is a reset.
    refused: bool,
    /// A denial went out (`send_denial_once`): the close lingers for
    /// `Limits::denial_linger` instead of resetting at once, so the peer reads it.
    denial: bool,
}

impl Drop for SoftPermit {
    fn drop(&mut self) {
        self.0
            .live
            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
    }
}

pub(crate) struct Link {
    /// First, so that it drops before `stream`: a link dropped without a close
    /// (unwinding) ends its kill slot before its descriptor closes.
    pub(crate) slot: SlotLease,
    pub(crate) stream: sys::Stream,
    pub(crate) info: ConnectionInfo,
    pub(crate) limits: Arc<Effective>,
    clock: ClockRef,
    phase: Phase,
    progress_at: Instant,
    exchange_deadline: Option<Instant>,
    rate_in: Rate,
    rate_out: Rate,
    wake: WakeSource,
    recv_timeout_set: Option<Duration>,
    pub(crate) gate: Option<Box<dyn ErasedGate>>,
    pub(crate) bytes_in: u64,
    pub(crate) bytes_out: u64,
    pub(crate) response_started: bool,
    pub(crate) response_tag: Option<GateTag>,
    pub(crate) peer_closed: bool,
    /// The first fatal condition seen; it becomes the close reason.
    pub(crate) terminal: Option<CloseReason>,
    likely_more: bool,
    /// The session took a completer, so posts may come: on the pool a receive
    /// waits on the wake channel first, as on Windows and macOS (D-163).
    pub(crate) wakeable: std::cell::Cell<bool>,
    /// Bytes went out since the last bytes came in.
    replied: bool,
    /// `DRAIN_HOOK`: the owner hears a drain at its idle wait (`Session::on_drain`)
    /// instead of the read closing with `Drained`; `DRAIN_REACHED`: that news;
    /// `DRAIN_KEPT`: the session kept the connection through the drain; and
    /// `AUTO_PHASE`: net-io picks the phase (the owner never set one); `SPOKE_IDLE`:
    /// the last send went out while idle and unasked; `HEARD`: the session was given
    /// input in this exchange. One byte.
    drains: u8,
    /// The soft close (after a denial, or `close_after_flush`), once there is one.
    /// Boxed: one pointer on every connection, the rest only where it happens.
    soft: Option<Box<SoftClose>>,
    /// The idle timeout in force: the limits' value, or this connection's override.
    idle_timeout: Duration,
    /// While a PROXY (or TLS) handshake runs: its deadline replaces the phase's.
    handshake_deadline: Option<Instant>,
    /// What deadlines are multiplied by under pressure (1 otherwise).
    deadline_scale: f32,
    /// The owner reads the scale again when an idle wait ends (the pool's sessions).
    rescales: bool,
    /// Bytes read past a handshake, served before the socket (the buffer returns
    /// to the worker's pool at close).
    pending: Option<Buffer>,
    pending_at: usize,
    /// Bytes at the head of the next send that the gate already approved (the
    /// unsent tail of a partial send), so a byte-counting gate counts each once.
    approved: usize,
    /// TLS on this connection (feature `tls`).
    tls: Option<Box<TlsLayer>>,
}

/// TLS on a connection: the engine's session and its two buffers.
pub(crate) struct TlsLayer {
    session: Box<dyn TlsSession>,
    /// Ciphertext in; `[start, len)` is not yet consumed by the engine.
    cin: Buffer,
    start: usize,
    /// Decrypted plaintext not yet delivered: `[plain_at, plain_end)` inside `cin`.
    plain_at: usize,
    plain_end: usize,
    /// Ciphertext out: scratch, flushed within each call, except `[0, held)`.
    cout: Buffer,
    /// Records the engine wrote as the handshake ended, kept at the front of `cout`
    /// to leave with the session's first reply in one send (the reactor, D-180).
    /// They are already encrypted in sequence, so whatever is sent next goes after
    /// them, never without them.
    held: usize,
    /// `close_notify` is in `cout` (sealed with the last reply, D-180): a close
    /// sends no second one.
    notified: bool,
    /// Both buffers went back to the pool while the connection waits (D-181), or
    /// were never taken because no byte has arrived yet (reactor). A buffer out
    /// with an operation in flight leaves a stand-in too, so this flag, not the
    /// stand-in, says which it is.
    #[cfg_attr(not(feature = "reactor"), allow(dead_code))]
    released: bool,
    done: bool,
    eof: bool,
    /// What the engine reported last, not acted on yet.
    event: Option<Ev>,
    /// The input range of the last engine step: plaintext must lie inside it.
    data_from: usize,
    data_to: usize,
}

impl TlsLayer {
    fn new(session: Box<dyn TlsSession>, cin: Buffer, cout: Buffer, released: bool) -> Box<Self> {
        Box::new(TlsLayer {
            session,
            cin,
            start: 0,
            plain_at: 0,
            plain_end: 0,
            cout,
            held: 0,
            notified: false,
            released,
            done: false,
            eof: false,
            event: None,
            data_from: 0,
            data_to: 0,
        })
    }
}

/// What one round of the TLS engine produced.
enum Pump {
    Plain,
    Handshaken,
    Eof,
    Woken,
}

/// What the TLS machine needs next. Both drivers run the same machine: the
/// blocking driver sends and reads in place, the reactor through operations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum TlsNext {
    /// `cout` holds records to send.
    Transmit,
    /// The engine wants more ciphertext.
    NeedInput,
    /// Plaintext is ready to deliver.
    Plain,
    /// The handshake just finished.
    Handshaken,
    /// The stream ended.
    Eof,
}

/// The engine's event, without the borrow of the input.
#[derive(Clone, Copy)]
enum Ev {
    NeedInput,
    Transmit,
    Handshaken,
    Data(usize, usize),
    OutputFull,
    Closed,
}

/// How much of a file one gate check covers.
const FILE_CHUNK: u64 = 1 << 20;
/// The buffer of a file sent by reading and writing.
const FILE_COPY: usize = 64 * 1024;

/// The largest plaintext encrypted into one record.
const TLS_RECORD: usize = 16 * 1024;
/// Room kept per record for the TLS header, padding, and tag.
const TLS_OVERHEAD: usize = 2 * 1024;

/// `d` under a pressure scale: never below 1 s, never above `d`.
fn scale(d: Duration, by: f32) -> Duration {
    if by >= 1.0 {
        return d;
    }
    d.mul_f32(by).max(Duration::from_secs(1)).min(d)
}

impl Link {
    /// The generation this connection holds its kill slot with.
    pub(crate) fn generation(&self) -> u32 {
        self.slot.generation()
    }

    pub(crate) fn new(
        stream: sys::Stream,
        info: ConnectionInfo,
        limits: Arc<Effective>,
        clock: ClockRef,
        slot: Arc<KillSlot>,
        wake: WakeSource,
        phase: Phase,
    ) -> Link {
        let now = clock.now();
        let generation = slot.install(stream.sock());
        if let WakeSource::Fixed(w) = &wake {
            slot.set_wake(Some(w.clone()));
        }
        let rate_in = Rate::new(&limits.min_rate, now);
        let rate_out = Rate::new(&limits.min_rate, now);
        let idle_timeout = limits.idle_timeout;
        let mut link = Link {
            slot: SlotLease::new(slot, generation),
            stream,
            info,
            limits,
            clock,
            phase,
            progress_at: now,
            exchange_deadline: None,
            rate_in,
            rate_out,
            wake,
            recv_timeout_set: None,
            gate: None,
            bytes_in: 0,
            bytes_out: 0,
            response_started: false,
            response_tag: None,
            peer_closed: false,
            terminal: None,
            likely_more: false,
            wakeable: std::cell::Cell::new(false),
            replied: false,
            soft: None,
            drains: if phase == Phase::Idle { AUTO_PHASE } else { 0 },
            idle_timeout,
            handshake_deadline: None,
            deadline_scale: 1.0,
            rescales: false,
            pending: None,
            pending_at: 0,
            approved: 0,
            tls: None,
        };
        if phase == Phase::Receiving {
            link.rate_in.activate(now);
        }
        link
    }

    #[inline]
    pub(crate) fn now(&self) -> Instant {
        self.clock.now()
    }

    pub(crate) fn phase(&self) -> Phase {
        self.phase
    }

    /// The owner sets the phase; net-io stops choosing it.
    pub(crate) fn set_phase(&mut self, phase: Phase) {
        self.drains &= !AUTO_PHASE;
        if phase == self.phase {
            return;
        }
        let now = self.now();
        self.phase = phase;
        self.progress_at = now;
        match phase {
            Phase::Idle => {
                self.rate_in.deactivate();
                self.exchange_deadline = None;
            }
            Phase::Receiving => self.rate_in.activate(now),
            Phase::Sending => self.rate_in.deactivate(),
        }
    }

    /// When net-io chooses the phase, an exchange ends once a reply went out and
    /// no input is left over (`done`): the connection goes back to `Idle`, so it
    /// waits under the idle timeout and a drain can close it at once. Input left
    /// over (a pipelined request) keeps the read deadline and inbound rate.
    pub(crate) fn settle_phase(&mut self, done: bool) {
        if done && self.drains & AUTO_PHASE != 0 && self.replied && self.phase == Phase::Receiving {
            let now = self.now();
            self.phase = Phase::Idle;
            self.progress_at = now;
            self.rate_in.deactivate();
        }
        // The exchange is over: what goes out from here until the next input is the
        // session's own news (D-192).
        if done && self.phase == Phase::Idle {
            self.drains &= !HEARD;
        }
        self.replied = false;
    }

    /// The session is about to see input: what it sends until the exchange ends
    /// answers the peer.
    #[inline]
    pub(crate) fn note_heard(&mut self) {
        self.drains |= HEARD;
    }

    pub(crate) fn set_exchange_deadline(&mut self, at: Option<Instant>) {
        self.exchange_deadline = at;
    }

    pub(crate) fn set_limits(&mut self, limits: Effective) {
        let now = self.now();
        let in_active = self.rate_in.is_active(&self.limits.min_rate);
        self.idle_timeout = limits.idle_timeout;
        self.rate_in = Rate::new(&limits.min_rate, now);
        self.rate_out = Rate::new(&limits.min_rate, now);
        self.limits = Arc::new(limits);
        if in_active {
            self.rate_in.activate(now);
        }
    }

    /// Puts TLS on this connection: from now on reads return plaintext and
    /// writes encrypt. `cin` must hold the largest record the engine needs.
    ///
    /// Bytes read past a PROXY header are ciphertext: they move into `cin` here, so
    /// the engine reads them first and nothing reaches the session unencrypted. The
    /// emptied read-ahead buffer is returned for its pool.
    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
    #[must_use]
    pub(crate) fn attach_tls(
        &mut self,
        session: Box<dyn TlsSession>,
        mut cin: Buffer,
        mut cout: Buffer,
    ) -> Option<Buffer> {
        cin.set_len(0);
        cout.set_len(0);
        let ahead = self.pending.take();
        if let Some(p) = ahead.as_ref() {
            let rest = p.as_slice().get(self.pending_at..).unwrap_or(&[]);
            if rest.len() > cin.capacity() {
                // Cannot happen with the pool's classes; fail closed if it does.
                self.terminal.get_or_insert(CloseReason::TlsFailed);
            } else {
                cin.spare()[..rest.len()].copy_from_slice(rest);
                cin.set_len(rest.len());
            }
        }
        self.pending_at = 0;
        self.tls = Some(TlsLayer::new(session, cin, cout, false));
        ahead
    }

    /// Puts TLS on this connection without its buffers, for a connection that has
    /// not sent a byte yet: they come from the pool with `tls_restore` once bytes
    /// arrive, so a peer that connects and stays silent holds none. Only without
    /// bytes read ahead (those must go to the engine at once: `attach_tls`).
    #[cfg(all(feature = "tls", feature = "reactor"))]
    pub(crate) fn attach_tls_released(&mut self, session: Box<dyn TlsSession>) {
        debug_assert!(!self.has_read_ahead(), "read-ahead needs the buffers now");
        self.tls = Some(TlsLayer::new(
            session,
            Buffer::placeholder(),
            Buffer::placeholder(),
            true,
        ));
    }

    /// Whether TLS is on this connection.
    pub(crate) fn has_tls(&self) -> bool {
        self.tls.is_some()
    }

    /// Both TLS buffers, for the pool, while the connection waits between
    /// exchanges with nothing in them: the handshake is done, every byte of
    /// ciphertext was consumed, all plaintext delivered, and no event is pending.
    /// `None` (nothing taken) otherwise. The engine keeps nothing in the caller's
    /// buffers between steps (D-066), so the next read starts in fresh ones (D-181).
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_release(&mut self) -> Option<(Buffer, Buffer)> {
        let t = self.tls.as_mut()?;
        let idle = t.done
            && !t.released
            && !t.eof
            && t.event.is_none()
            && t.start >= t.cin.len()
            && t.plain_at >= t.plain_end
            && t.cin.capacity() > 0
            && t.cout.capacity() > 0
            && t.held == 0;
        if !idle {
            return None;
        }
        t.start = 0;
        t.plain_at = 0;
        t.plain_end = 0;
        t.data_from = 0;
        t.data_to = 0;
        let cin = std::mem::replace(&mut t.cin, Buffer::placeholder());
        let cout = std::mem::replace(&mut t.cout, Buffer::placeholder());
        t.released = true;
        Some((cin, cout))
    }

    /// Whether the TLS buffers are with the pool (`tls_release`, or a TLS start
    /// that took none yet: `attach_tls_released`). Not while a buffer is merely out
    /// with an operation: restoring then would drop the buffer that comes back.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_released(&self) -> bool {
        self.tls.as_ref().is_some_and(|t| t.released)
    }

    /// Gives a released connection its TLS buffers again. `Err` hands them back
    /// when the connection is not released, so a buffer in use is never replaced.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_restore(
        &mut self,
        mut cin: Buffer,
        mut cout: Buffer,
    ) -> Result<(), (Buffer, Buffer)> {
        let Some(t) = self.tls.as_mut().filter(|t| t.released) else {
            return Err((cin, cout));
        };
        cin.set_len(0);
        cout.set_len(0);
        t.cin = cin;
        t.cout = cout;
        t.released = false;
        Ok(())
    }

    /// The TLS buffers, for their pool.
    pub(crate) fn take_tls_buffers(&mut self) -> Option<(Buffer, Buffer)> {
        self.tls.take().map(|t| (t.cin, t.cout))
    }

    /// Runs the TLS handshake to completion (under the handshake deadline set by
    /// `begin_handshake`); the engine's facts land in `info.tls`.
    #[cfg_attr(not(feature = "tls"), allow(dead_code))]
    pub(crate) fn tls_handshake(&mut self) -> Result<(), NetError> {
        let Some(mut t) = self.tls.take() else {
            return Ok(());
        };
        let r = loop {
            match self.tls_pump(&mut t) {
                Ok(Pump::Handshaken) => break Ok(()),
                // Plaintext before the handshake completed is not something net-io accepts.
                Ok(Pump::Plain) if !t.done => {
                    break Err(self.tls_error(TlsError::new(TlsFailure::State, 0, None)));
                }
                Ok(Pump::Plain) => break Ok(()),
                Ok(Pump::Eof) => break Err(self.fail(CloseReason::TlsFailed, NetError::Closed)),
                Ok(Pump::Woken) => {}
                Err(e) => break Err(e),
            }
        };
        self.tls = Some(t);
        r
    }

    /// Plaintext for a reader.
    fn read_tls(&mut self, t: &mut TlsLayer, buf: &mut [u8]) -> Result<Got, NetError> {
        loop {
            match self.tls_pump(t)? {
                Pump::Plain => {
                    let have = &t.cin.as_slice()[t.plain_at..t.plain_end];
                    let n = have.len().min(buf.len());
                    buf[..n].copy_from_slice(&have[..n]);
                    t.plain_at += n;
                    let now = self.now();
                    self.progress_at = now;
                    if self.phase == Phase::Idle {
                        self.phase = Phase::Receiving;
                        self.rate_in.activate(now);
                    }
                    return Ok(Got::Data(n));
                }
                Pump::Handshaken => {}
                Pump::Eof => {
                    self.peer_closed = true;
                    return Ok(Got::Eof);
                }
                Pump::Woken => return Ok(Got::Woken),
            }
        }
    }

    /// Drives the engine until it has plaintext to deliver, finished the
    /// handshake, or the transport ended. Records the engine writes (handshake,
    /// alerts, tickets) go out at once.
    fn tls_pump(&mut self, t: &mut TlsLayer) -> Result<Pump, NetError> {
        loop {
            match self.tls_advance(t)? {
                TlsNext::Plain => return Ok(Pump::Plain),
                TlsNext::Handshaken => return Ok(Pump::Handshaken),
                TlsNext::Eof => return Ok(Pump::Eof),
                TlsNext::Transmit => {
                    // Records the engine wrote on its own are not the session's reply:
                    // they must not end an exchange, and they go out under the
                    // outbound rate like any send.
                    let (replied, spoke) = (self.replied, self.drains & SPOKE_IDLE);
                    self.rate_out.activate(self.now());
                    let r = self.send_raw_all(t.cout.as_slice());
                    self.replied = replied;
                    self.drains = self.drains & !SPOKE_IDLE | spoke;
                    r?;
                }
                TlsNext::NeedInput => {
                    if let Some(p) = self.tls_fill(t)? {
                        return Ok(p);
                    }
                }
            }
        }
    }

    /// One turn of the TLS machine: runs the engine until something outside it
    /// has to happen. Does no IO.
    fn tls_advance(&mut self, t: &mut TlsLayer) -> Result<TlsNext, NetError> {
        loop {
            if t.plain_at < t.plain_end {
                return Ok(TlsNext::Plain);
            }
            if t.eof {
                return Ok(TlsNext::Eof);
            }
            if let Some(ev) = t.event.take() {
                match ev {
                    Ev::NeedInput => return Ok(TlsNext::NeedInput),
                    Ev::Transmit | Ev::OutputFull => {}
                    Ev::Handshaken => {
                        t.done = true;
                        if let Some(info) = t.session.info() {
                            self.info.tls = Some(Arc::new(info));
                        }
                        return Ok(TlsNext::Handshaken);
                    }
                    Ev::Data(off, len) => {
                        // The plaintext must lie inside the input the engine was given.
                        if off < t.data_from || off.saturating_add(len) > t.data_to {
                            return Err(self.tls_error(TlsError::new(TlsFailure::State, 0, None)));
                        }
                        t.plain_at = off;
                        t.plain_end = off + len;
                    }
                    Ev::Closed => {
                        t.eof = true;
                        return Ok(TlsNext::Eof);
                    }
                }
                continue;
            }
            let start = t.start;
            let end = t.cin.len();
            let base = t.cin.as_slice().as_ptr() as usize;
            let held = t.held;
            let TlsLayer {
                session, cin, cout, ..
            } = &mut *t;
            cout.set_len(held);
            let stepped = session
                .step(&mut cin.as_mut_slice()[start..end], cout.spare())
                .map(|p| {
                    let ev = match p.event {
                        TlsEvent::NeedInput => Ev::NeedInput,
                        TlsEvent::Transmit => Ev::Transmit,
                        TlsEvent::HandshakeComplete => Ev::Handshaken,
                        TlsEvent::Data(d) => match (d.as_ptr() as usize).checked_sub(base) {
                            Some(off) if !d.is_empty() => Ev::Data(off, d.len()),
                            Some(_) => Ev::Transmit,
                            None => Ev::Data(usize::MAX, 0),
                        },
                        TlsEvent::OutputFull => Ev::OutputFull,
                        TlsEvent::PeerClosed | TlsEvent::Closed => Ev::Closed,
                    };
                    (p.consumed, p.written, ev)
                });
            let (consumed, written, ev) = match stepped {
                Ok(v) => v,
                Err(e) => return Err(self.tls_error(e)),
            };
            t.start = (start + consumed).min(end);
            t.data_from = start;
            t.data_to = end;
            if matches!(ev, Ev::OutputFull) && written == 0 {
                return Err(self.tls_error(TlsError::new(TlsFailure::OutputFull, 0, None)));
            }
            t.event = Some(ev);
            if written > 0 {
                t.cout.set_len((held + written).min(t.cout.capacity()));
                return Ok(TlsNext::Transmit);
            }
        }
    }

    /// Reads more ciphertext after compacting the input. `Some` ends the pump.
    fn tls_fill(&mut self, t: &mut TlsLayer) -> Result<Option<Pump>, NetError> {
        self.tls_make_room(t)?;
        let len = t.cin.len();
        match self.read_raw(t.cin.spare())? {
            Got::Data(n) => {
                t.cin.set_len(len + n);
                Ok(None)
            }
            Got::Eof => {
                // An unclean end (no close_notify) still ends the stream; the
                // protocol above decides whether its message was complete.
                let _ = t.session.on_transport_closed();
                t.eof = true;
                Ok(Some(Pump::Eof))
            }
            Got::Woken => Ok(Some(Pump::Woken)),
        }
    }

    /// Compacts the ciphertext input and checks there is room for more.
    fn tls_make_room(&mut self, t: &mut TlsLayer) -> Result<(), NetError> {
        if t.start > 0 {
            let len = t.cin.len();
            t.cin.as_mut_slice().copy_within(t.start..len, 0);
            t.cin.set_len(len - t.start);
            t.start = 0;
            t.plain_at = 0;
            t.plain_end = 0;
        }
        let need = t.session.input_capacity_required();
        if need > t.cin.capacity() || t.cin.spare().is_empty() {
            return Err(self.fail(
                CloseReason::Limit(LimitKind::ReadBuffer),
                NetError::Limit {
                    which: LimitKind::ReadBuffer,
                },
            ));
        }
        Ok(())
    }

    /// The plaintext one vectored TLS write takes: whole records that fit the
    /// output buffer.
    fn tls_budget(&self) -> usize {
        self.tls.as_ref().map_or(0, |t| {
            let room = t.cout.capacity().saturating_sub(t.held);
            (room / (TLS_RECORD + TLS_OVERHEAD)).max(1) * TLS_RECORD
        })
    }

    /// Encrypts `plain` (at most one record) and sends all of it.
    fn write_tls(&mut self, plain: &[u8]) -> Result<usize, NetError> {
        let Some(mut t) = self.tls.take() else {
            return Ok(0);
        };
        t.cout.set_len(0);
        let r = match t.session.encrypt(plain, t.cout.spare()) {
            Ok(n) => {
                t.cout.set_len(n.min(t.cout.capacity()));
                self.send_raw_all(t.cout.as_slice()).map(|()| plain.len())
            }
            Err(e) => Err(self.tls_error(e)),
        };
        self.tls = Some(t);
        r
    }

    /// Encrypts up to `take` plaintext bytes from `bufs` and sends all of it.
    fn write_vectored_tls(&mut self, bufs: &[IoSlice<'_>], take: usize) -> Result<usize, NetError> {
        let Some(mut t) = self.tls.take() else {
            return Ok(0);
        };
        let r = match self.tls_encrypt(&mut t, bufs, take) {
            Ok(taken) => self.send_raw_all(t.cout.as_slice()).map(|()| taken),
            Err(e) => Err(e),
        };
        self.tls = Some(t);
        r
    }

    /// Encrypts up to `take` plaintext bytes from `bufs` into `cout`.
    fn tls_encrypt(
        &mut self,
        t: &mut TlsLayer,
        bufs: &[IoSlice<'_>],
        take: usize,
    ) -> Result<usize, NetError> {
        t.cout.set_len(t.held);
        let mut taken = 0;
        let mut failed = None;
        'slices: for b in bufs.iter().take(sys::MAX_SLICES) {
            let mut s: &[u8] = b;
            while !s.is_empty() && taken < take {
                let chunk = s.len().min(TLS_RECORD).min(take - taken);
                if t.cout.spare().len() < chunk + TLS_OVERHEAD {
                    break 'slices;
                }
                let used = t.cout.len();
                match t.session.encrypt(&s[..chunk], t.cout.spare()) {
                    Ok(n) => t.cout.set_len(used + n),
                    Err(e) => {
                        failed = Some(e);
                        break 'slices;
                    }
                }
                taken += chunk;
                s = &s[chunk..];
            }
        }
        match failed {
            Some(e) => Err(self.tls_error(e)),
            None => Ok(taken),
        }
    }

    /// Sends `close_notify` once, without waiting (a graceful close).
    pub(crate) fn tls_close_notify(&mut self) {
        let Some(mut t) = self.tls.take() else {
            return;
        };
        // Without its output buffer (released, and none could be taken back) the
        // close is a plain FIN.
        if t.done && !t.eof && !t.notified && t.cout.capacity() > 0 {
            t.cout.set_len(t.held);
            if let Ok(n) = t.session.close(t.cout.spare()) {
                t.cout.set_len((t.held + n).min(t.cout.capacity()));
                if let Ok(sent) = sys::send(&self.stream, t.cout.as_slice()) {
                    self.bytes_out += sent as u64;
                }
            }
            t.held = 0;
            t.notified = true;
        }
        self.tls = Some(t);
    }

    /// Sends all of `bytes` without the gate check (TLS records the engine wrote).
    fn send_raw_all(&mut self, mut bytes: &[u8]) -> Result<(), NetError> {
        while !bytes.is_empty() {
            let n = self.send_raw(bytes)?;
            bytes = &bytes[n..];
        }
        Ok(())
    }

    fn tls_error(&mut self, e: TlsError) -> NetError {
        let reason = if e.kind == TlsFailure::HelloRefused {
            CloseReason::HelloRefused
        } else {
            CloseReason::TlsFailed
        };
        self.fail(reason, NetError::Tls(e))
    }

    /// Starts a handshake: reads time out at `deadline` with `HandshakeTimeout`.
    #[cfg_attr(not(feature = "proxy"), allow(dead_code))]
    pub(crate) fn begin_handshake(&mut self, deadline: Instant) {
        self.handshake_deadline = Some(deadline);
    }

    /// Ends a handshake. `rest` holds bytes read past it (`buffer[at..]`), served
    /// before the socket. The connection waits for its first exchange again. A
    /// buffer with nothing past the header comes back for its pool at once, so an
    /// idle connection holds no read buffer.
    #[cfg_attr(not(feature = "proxy"), allow(dead_code))]
    #[must_use]
    pub(crate) fn end_handshake(&mut self, rest: Option<(Buffer, usize)>) -> Option<Buffer> {
        self.handshake_deadline = None;
        let mut unused = None;
        if let Some((buffer, at)) = rest {
            if at < buffer.len() {
                self.pending_at = at;
                self.pending = Some(buffer);
            } else {
                unused = Some(buffer);
            }
        }
        self.phase = Phase::Idle;
        self.progress_at = self.now();
        self.rate_in.deactivate();
        unused
    }

    /// The handshake buffer, for its pool.
    pub(crate) fn take_pending(&mut self) -> Option<Buffer> {
        self.pending_at = 0;
        self.pending.take()
    }

    /// Copies bytes read past a handshake into `buf`; 0 when none are left.
    fn read_pending(&mut self, buf: &mut [u8]) -> usize {
        let Some(p) = self.pending.as_ref() else {
            return 0;
        };
        let have = p.as_slice().get(self.pending_at..).unwrap_or(&[]);
        let n = have.len().min(buf.len());
        buf[..n].copy_from_slice(&have[..n]);
        self.pending_at = self.pending_at.saturating_add(n);
        n
    }

    /// Under pressure deadlines shrink by `scale`, never below 1 s.
    pub(crate) fn set_deadline_scale(&mut self, scale: f32) {
        self.deadline_scale = scale;
    }

    /// The owner reads the server's scale again when `read` returns `Woken`, so an
    /// idle wait may end at the deadline pressure would give.
    pub(crate) fn set_rescales(&mut self) {
        self.rescales = true;
    }

    pub(crate) fn scaled(&self, d: Duration) -> Duration {
        scale(d, self.deadline_scale)
    }

    /// The longest an idle wait may last before the scale is read again, so a
    /// crossing reaches a connection already waiting.
    fn idle_slice(&self) -> Option<Duration> {
        let p = self.limits.pressure.filter(|_| self.rescales)?;
        (self.phase == Phase::Idle && self.handshake_deadline.is_none())
            .then(|| scale(self.idle_timeout, p.factor))
    }

    /// This connection's idle timeout from its next idle wait on (`None`: the
    /// limits' value again). At least one tick.
    pub(crate) fn set_idle_timeout(&mut self, timeout: Option<Duration>) {
        self.idle_timeout = timeout.map_or(self.limits.idle_timeout, |t| {
            crate::time::bounded(t).max(self.limits.tick)
        });
    }

    pub(crate) fn killed(&self) -> Option<KillReason> {
        self.slot.killed()
    }

    fn fail(&mut self, reason: CloseReason, err: NetError) -> NetError {
        if self.terminal.is_none() {
            self.terminal = Some(reason);
        }
        err
    }

    fn check_terminal(&mut self) -> Result<(), NetError> {
        if let Some(reason) = self.killed() {
            return Err(self.fail(CloseReason::Killed(reason), NetError::Killed { reason }));
        }
        match self.terminal {
            None => Ok(()),
            Some(CloseReason::EgressDenied(code)) => Err(NetError::EgressDenied { code }),
            Some(_) => Err(NetError::Closed),
        }
    }

    /// `check_terminal` for output: during a soft kill (`close_after_flush`) output
    /// already queued still goes out, until the kill's bound.
    fn check_sendable(&mut self) -> Result<(), NetError> {
        if self.soft_kill_left().is_some_and(|left| !left.is_zero()) {
            return match self.terminal {
                None | Some(CloseReason::Killed(_)) => Ok(()),
                Some(CloseReason::EgressDenied(code)) => Err(NetError::EgressDenied { code }),
                Some(_) => Err(NetError::Closed),
            };
        }
        self.check_terminal()
    }

    /// A session owner: a drain that reaches the idle wait is reported (`Got::Woken`
    /// with `take_drain_reached`) for `Session::on_drain` instead of closing.
    pub(crate) fn hear_drains(&mut self) {
        self.drains |= DRAIN_HOOK;
    }

    /// Whether a drain reached the idle wait since the last call.
    pub(crate) fn take_drain_reached(&mut self) -> bool {
        let reached = self.drains & DRAIN_REACHED != 0;
        self.drains &= !DRAIN_REACHED;
        reached
    }

    /// The session kept the connection through the drain: its waits no longer count
    /// as idle for a drain, so no pass marks it again.
    pub(crate) fn keep_through_drain(&mut self) {
        self.drains |= DRAIN_KEPT;
    }

    pub(crate) fn drain_kept(&self) -> bool {
        self.drains & DRAIN_KEPT != 0
    }

    /// Where this connection takes its place for a soft close (a server's links).
    pub(crate) fn set_soft_closes(&self, places: &Arc<SoftCloses>) {
        self.slot.set_soft_closes(places);
    }

    /// Takes (once) this connection's place among the soft closes; `false` when the
    /// server's `denial_linger_max` are all taken: the close is a reset instead.
    fn soft_place(&mut self) -> bool {
        let places = self.slot.soft_closes();
        let soft = self.soft.get_or_insert_with(Box::default);
        if soft.placed {
            return true;
        }
        if soft.refused {
            return false;
        }
        let Some(places) = places else {
            soft.placed = true;
            return true;
        };
        match places.take() {
            Some(p) => {
                soft.permit = Some(p);
                soft.placed = true;
                true
            }
            None => {
                soft.refused = true;
                false
            }
        }
    }

    /// When a soft kill stops letting output go out, once the owner has seen it.
    fn soft_until(&self) -> Option<Instant> {
        self.soft.as_ref().and_then(|s| s.until)
    }

    /// What is left of a soft kill's bound, while the kill is soft (a hard kill
    /// upgrades it) and it has its place (without one it acts as a kill). The bound
    /// runs from when the owner first sees the kill.
    pub(crate) fn soft_kill_left(&mut self) -> Option<Duration> {
        let bound = self.slot.soft_kill()?;
        if !self.soft_place() {
            return None;
        }
        let now = self.now();
        let soft = self.soft.get_or_insert_with(Box::default);
        let until = *soft
            .until
            .get_or_insert_with(|| now.checked_add(bound).unwrap_or(now + crate::time::LONGEST));
        Some(until.saturating_duration_since(now))
    }

    /// Killed, and not by a soft kill that has its place.
    fn hard_killed(&self) -> bool {
        self.killed().is_some()
            && (self.slot.soft_kill().is_none() || !self.soft.as_ref().is_some_and(|s| s.placed))
    }

    /// How long an abortive close lingers instead of resetting at once: what is left
    /// of a soft kill, or the denial linger after a denial went out; `None` for a
    /// reset (a hard kill, or no denial).
    pub(crate) fn soft_close(&mut self) -> Option<Duration> {
        if let Some(left) = self.soft_kill_left() {
            return Some(left);
        }
        if self.killed().is_some() {
            return None;
        }
        if !self.soft.as_ref().is_some_and(|s| s.denial) || !self.soft_place() {
            return None;
        }
        Some(self.limits.denial_linger)
    }

    fn timed_out(&mut self, kind: TimeoutKind) -> NetError {
        self.fail(CloseReason::for_timeout(kind), NetError::TimedOut { kind })
    }

    fn os_error(&mut self, op: &'static str, e: io::Error) -> NetError {
        let reason = match e.kind() {
            io::ErrorKind::ConnectionReset
            | io::ErrorKind::ConnectionAborted
            | io::ErrorKind::BrokenPipe => CloseReason::PeerReset,
            _ => CloseReason::Io(OsErrorClass::from_io(&e)),
        };
        let err = NetError::from_os(op, e);
        self.fail(reason, err)
    }

    /// Runs a wait with the right wake channel registered.
    fn wait(&self, interest: Interest, timeout: Duration) -> io::Result<Ready> {
        match &self.wake {
            WakeSource::Fixed(w) => self.stream.wait(interest, Some(w), Some(timeout)),
            WakeSource::Thread => {
                let w = thread_wake();
                self.slot.set_wake(w.clone());
                let r = self.stream.wait(interest, w.as_deref(), Some(timeout));
                self.slot.set_wake(None);
                r
            }
            WakeSource::Reactor => Err(io::Error::from(io::ErrorKind::Unsupported)),
        }
    }

    /// One read into `buf`, honouring the phase's deadline, the exchange deadline,
    /// and the inbound minimum rate. `Woken` means the wake channel fired (drain,
    /// control line, kill); the caller re-checks and calls again.
    pub(crate) fn read(&mut self, buf: &mut [u8]) -> Result<Got, NetError> {
        if buf.is_empty() {
            return Ok(Got::Data(0));
        }
        let r = if let Some(mut t) = self.tls.take() {
            self.settle_phase(true);
            let r = self.read_tls(&mut t, buf);
            self.tls = Some(t);
            r
        } else {
            self.read_raw(buf)
        };
        if matches!(r, Ok(Got::Data(n)) if n > 0) {
            self.note_heard();
        }
        r
    }

    /// One read from the socket (or from the bytes left after a handshake),
    /// under the phase's or the handshake's deadline.
    fn read_raw(&mut self, buf: &mut [u8]) -> Result<Got, NetError> {
        self.read_raw_with(buf, sys::recv)
    }

    /// As `read_raw`, with `recv` as the receive call.
    fn read_raw_with<R>(&mut self, buf: &mut [u8], mut recv: R) -> Result<Got, NetError>
    where
        R: FnMut(&sys::Stream, &mut [u8]) -> io::Result<usize>,
    {
        self.settle_phase(true);
        let n = self.read_pending(buf);
        if n > 0 {
            let now = self.now();
            self.progress_at = now;
            if self.phase == Phase::Idle {
                self.phase = Phase::Receiving;
                self.rate_in.activate(now);
            }
            return Ok(Got::Data(n));
        }
        loop {
            self.check_terminal()?;
            if self.peer_closed {
                return Ok(Got::Eof);
            }
            let now = self.now();
            let (op_deadline, op_kind) = self.read_deadline();
            if now >= op_deadline {
                return Err(self.timed_out(op_kind));
            }
            if self.exchange_deadline.is_some_and(|d| now >= d) {
                return Err(self.timed_out(TimeoutKind::Exchange));
            }
            if self.rate_in.too_slow(&self.limits.min_rate, now) {
                return Err(self.fail(
                    CloseReason::SlowPeer {
                        direction: Direction::In,
                    },
                    NetError::SlowPeer {
                        direction: Direction::In,
                    },
                ));
            }
            let mut until = op_deadline;
            if let Some(d) = self.exchange_deadline {
                until = until.min(d);
            }
            if let Some(c) = self.rate_in.next_check(&self.limits.min_rate, now) {
                until = until.min(c);
            }
            let recheck = self.idle_slice().map(|s| now + s).filter(|&r| r < until);
            if let Some(r) = recheck {
                until = r;
            }
            let timeout = until
                .saturating_duration_since(now)
                .max(Duration::from_millis(1));

            // Waiting for the next exchange: a drain may close the connection now
            // (unless the session kept it through the drain).
            let idle = self.phase == Phase::Idle && !self.drain_kept();
            if idle {
                self.slot.set_idle(true);
            }
            let got = self.wait_and_recv(buf, timeout, &mut recv);
            if idle {
                self.slot.set_idle(false);
            }
            if let Some(result) = got {
                return result;
            }
            if recheck.is_some_and(|r| self.now() >= r) {
                // The owner reads the server's scale again before the next wait.
                return Ok(Got::Woken);
            }
        }
    }

    /// One wait where the OS needs it (Windows and macOS: every receive; D-052,
    /// D-083) and one receive. Linux receives block under `SO_RCVTIMEO`, so an
    /// exchange costs one receive and one send. `None` means try again (timed out or would block).
    fn wait_and_recv<R>(
        &mut self,
        buf: &mut [u8],
        timeout: Duration,
        recv: &mut R,
    ) -> Option<Result<Got, NetError>>
    where
        R: FnMut(&sys::Stream, &mut [u8]) -> io::Result<usize>,
    {
        // Between exchanges Linux waits first too, so a drain reaches the owner
        // through its wake channel and the owner decides; a drain that shut the read
        // side could cut short a request whose first bytes it saw too late (D-178).
        let linux_idle = !sys::WAIT_BEFORE_RECV && self.phase == Phase::Idle;
        if sys::WAIT_BEFORE_RECV || self.wakeable.get() || linux_idle {
            if !self.likely_more || linux_idle {
                match self.wait(Interest::Read, timeout) {
                    Ok(Ready::TimedOut) => return None,
                    Ok(Ready::Woken) => {
                        if let Err(e) = self.check_terminal() {
                            return Some(Err(e));
                        }
                        // A drain closes a connection between exchanges, not one whose
                        // next request already arrived: that one is read and answered,
                        // and the drain closes it after (serve-net's drain race).
                        if !self.slot.drained() {
                            return Some(Ok(Got::Woken));
                        }
                        if self.phase != Phase::Idle {
                            // Marked while it was leaving its wait: a later pass marks
                            // it again at its next one.
                            self.slot.undrain();
                            return Some(Ok(Got::Woken));
                        }
                        if !self.slot.shed() && self.awaits_first_request() {
                            // Fresh: a later pass of the drain marks it again.
                            self.slot.undrain();
                            return Some(Ok(Got::Woken));
                        }
                        if !self.input_waiting() {
                            if self.drains & DRAIN_HOOK != 0 {
                                // The session hears it (`on_drain`) and decides.
                                self.slot.undrain();
                                self.drains |= DRAIN_REACHED;
                                return Some(Ok(Got::Woken));
                            }
                            return Some(Err(self.fail(CloseReason::Drained, NetError::Closed)));
                        }
                        self.slot.undrain();
                    }
                    Ok(Ready::Socket) => {}
                    Err(e) => return Some(Err(self.os_error("wait", e))),
                }
            }
        } else {
            let want = Some(timeout);
            let tick = self.limits.tick;
            let stale = match (self.recv_timeout_set, want) {
                (Some(set), Some(w)) => set.abs_diff(w) > tick,
                _ => true,
            };
            if stale {
                if let Err(e) = sys::set_recv_timeout(&self.stream, want) {
                    return Some(Err(self.os_error("setsockopt", e)));
                }
                self.recv_timeout_set = want;
            }
        }
        match recv(&self.stream, buf) {
            Ok(0) => {
                // A kill or a drain shuts the read side, which also reads as 0.
                if let Err(e) = self.check_terminal() {
                    return Some(Err(e));
                }
                if self.slot.drained() {
                    return Some(Err(self.fail(CloseReason::Drained, NetError::Closed)));
                }
                self.peer_closed = true;
                self.likely_more = false;
                Some(Ok(Got::Eof))
            }
            Ok(n) => {
                let now = self.now();
                self.bytes_in += n as u64;
                self.progress_at = now;
                self.likely_more = n == buf.len();
                if self.phase == Phase::Idle {
                    self.phase = Phase::Receiving;
                    self.rate_in.activate(now);
                }
                self.rate_in.record(now, n);
                Some(Ok(Got::Data(n)))
            }
            // `SO_RCVTIMEO` expiring reads as `WouldBlock` on Linux, and Windows and
            // macOS sockets are non-blocking. `TimedOut` is the kernel giving up on the connection
            // (keepalive), which is `Io(TimedOut)`, not one of our deadlines.
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                self.likely_more = false;
                None
            }
            Err(e) => Some(Err(self.os_error("recv", e))),
        }
    }

    /// Asks the gate about a write of `bytes`.
    fn gate_check(&mut self, bytes: usize) -> Result<(), NetError> {
        if let Some(gate) = self.gate.as_mut() {
            let w = WriteCheck::new(
                self.info.id,
                self.info.lane,
                u32::try_from(bytes).unwrap_or(u32::MAX),
                self.response_started,
                self.response_tag,
            );
            if let Err(Denial { code }) = gate.check(&w) {
                return Err(self.fail(
                    CloseReason::EgressDenied(code),
                    NetError::EgressDenied { code },
                ));
            }
        }
        Ok(())
    }

    /// Waits until the socket can take bytes, honouring the write deadline, the
    /// exchange deadline, and the outbound minimum rate.
    fn wait_writable(&mut self) -> Result<(), NetError> {
        loop {
            self.check_sendable()?;
            let now = self.now();
            let deadline = self.progress_at + self.limits.write_timeout;
            if now >= deadline {
                return Err(self.timed_out(TimeoutKind::Write));
            }
            if self.exchange_deadline.is_some_and(|d| now >= d) {
                return Err(self.timed_out(TimeoutKind::Exchange));
            }
            // A handshake flight that the peer drains a byte at a time still ends at
            // the handshake deadline, not at a write timeout each byte restarts.
            if self.handshake_deadline.is_some_and(|d| now >= d) {
                return Err(self.timed_out(TimeoutKind::Handshake));
            }
            if self.rate_out.too_slow(&self.limits.min_rate, now) {
                return Err(self.fail(
                    CloseReason::SlowPeer {
                        direction: Direction::Out,
                    },
                    NetError::SlowPeer {
                        direction: Direction::Out,
                    },
                ));
            }
            let mut until = deadline;
            if let Some(d) = self.exchange_deadline {
                until = until.min(d);
            }
            if let Some(d) = self.handshake_deadline {
                until = until.min(d);
            }
            if let Some(c) = self.rate_out.next_check(&self.limits.min_rate, now) {
                until = until.min(c);
            }
            if let Some(d) = self.soft_until() {
                until = until.min(d);
            }
            let timeout = until
                .saturating_duration_since(now)
                .max(Duration::from_millis(1));
            match self.wait(Interest::Write, timeout) {
                Ok(Ready::Socket) => return Ok(()),
                Ok(Ready::TimedOut | Ready::Woken) => continue,
                Err(e) => return Err(self.os_error("wait", e)),
            }
        }
    }

    fn sent(&mut self, n: usize) {
        let now = self.now();
        self.bytes_out += n as u64;
        self.replied = true;
        // A reply the session wrote after it set `Idle` for the exchange it answered
        // is not unasked: only bytes sent while idle with no input heard are (D-201).
        if self.phase == Phase::Idle && self.drains & HEARD == 0 {
            self.drains |= SPOKE_IDLE;
        } else {
            self.drains &= !SPOKE_IDLE;
        }
        self.progress_at = now;
        self.rate_out.record(now, n);
        if n > 0 {
            self.response_started = true;
        }
    }

    /// One send (gate check first); may be partial. Waits while the socket is full.
    pub(crate) fn write(&mut self, buf: &[u8]) -> Result<usize, NetError> {
        if buf.is_empty() {
            return Ok(0);
        }
        let now = self.now();
        self.rate_out.activate(now);
        if self.phase == Phase::Idle {
            self.progress_at = now;
        }
        // One gate check per write, for the bytes the gate has not approved yet:
        // a retry after `WouldBlock`, or the tail of a partial send offered again,
        // is not counted twice by a byte-counting gate.
        self.check_sendable()?;
        if self.tls.is_some() {
            let chunk = buf.len().min(TLS_RECORD);
            self.gate_check(chunk)?;
            return self.write_tls(&buf[..chunk]);
        }
        // One offer is at most what `WriteCheck::bytes` can say, so the gate's
        // count stays exact for a single enormous write.
        let buf = &buf[..buf.len().min(u32::MAX as usize)];
        self.gate_check(buf.len().saturating_sub(self.approved))?;
        let n = self.send_raw(buf)?;
        self.approved = buf.len() - n;
        Ok(n)
    }

    /// One send without the gate check (waits while the socket is full).
    fn send_raw(&mut self, buf: &[u8]) -> Result<usize, NetError> {
        let mut zero_writes = 0u8;
        loop {
            self.check_sendable()?;
            match sys::send(&self.stream, buf) {
                Ok(0) => {
                    // Should not happen on TCP; treat once as "full", then as an error.
                    zero_writes += 1;
                    if zero_writes > 1 {
                        break Err(self.os_error("send", io::Error::from(io::ErrorKind::WriteZero)));
                    }
                    self.wait_writable()?;
                }
                Ok(n) => {
                    self.sent(n);
                    break Ok(n);
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.wait_writable()?,
                Err(e) => break Err(self.os_error("send", e)),
            }
        }
    }

    /// One read that also takes descriptors passed with the bytes (`SCM_RIGHTS`),
    /// stored into `into` from index 0. Returns what was read and how many
    /// descriptors came with it.
    #[cfg(all(unix, feature = "local"))]
    pub(crate) fn read_with_fds(
        &mut self,
        buf: &mut [u8],
        into: &mut [Option<std::os::fd::OwnedFd>; sys::MAX_FDS],
    ) -> Result<(Got, usize), NetError> {
        if self.tls.is_some() {
            return Err(NetError::Unsupported {
                feature: "descriptor passing on a TLS connection",
                platform: std::env::consts::OS,
            });
        }
        if buf.is_empty() {
            return Ok((Got::Data(0), 0));
        }
        let mut fds = 0;
        let mut truncated = false;
        let got = self.read_raw_with(buf, |s, b| {
            let r = sys::recv_with_fds(s, b, into)?;
            fds = r.fds;
            truncated = r.truncated;
            Ok(r.bytes)
        })?;
        if truncated {
            // Every descriptor of the message was closed. The bytes came with
            // them, so the stream can no longer be framed: the connection fails.
            return Err(self.fail(
                CloseReason::SessionError,
                NetError::Handoff(crate::handoff::HandoffError::Truncated),
            ));
        }
        Ok((got, fds))
    }

    /// Sends all of `body` with `fds` attached to its first byte (`SCM_RIGHTS`).
    /// One gate check for the whole body.
    #[cfg(all(unix, feature = "local"))]
    pub(crate) fn write_with_fds(
        &mut self,
        body: &[u8],
        fds: &[std::os::fd::BorrowedFd<'_>],
    ) -> Result<(), NetError> {
        if self.tls.is_some() {
            return Err(NetError::Unsupported {
                feature: "descriptor passing on a TLS connection",
                platform: std::env::consts::OS,
            });
        }
        if body.is_empty() {
            return Err(NetError::InvalidConfig {
                field: "body",
                reason: crate::error::ConfigReason::Zero,
            });
        }
        if fds.len() > sys::MAX_FDS {
            return Err(NetError::InvalidConfig {
                field: "descriptors",
                reason: crate::error::ConfigReason::TooLarge {
                    max: sys::MAX_FDS as u64,
                },
            });
        }
        let now = self.now();
        self.rate_out.activate(now);
        self.check_sendable()?;
        self.gate_check(body.len())?;
        self.approved = 0;
        let mut zero_writes = 0u8;
        let first = loop {
            self.check_sendable()?;
            match sys::send_with_fds(&self.stream, body, fds) {
                Ok(0) => {
                    zero_writes += 1;
                    if zero_writes > 1 {
                        return Err(
                            self.os_error("sendmsg", io::Error::from(io::ErrorKind::WriteZero))
                        );
                    }
                    self.wait_writable()?;
                }
                Ok(n) => {
                    self.sent(n);
                    break n;
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.wait_writable()?,
                Err(e) => return Err(self.os_error("sendmsg", e)),
            }
        };
        let mut rest = &body[first..];
        while !rest.is_empty() {
            let n = self.send_raw(rest)?;
            rest = &rest[n..];
        }
        self.rate_out.deactivate();
        Ok(())
    }

    /// Sends all of `buf`, continuing partial writes from the exact offset.
    pub(crate) fn write_all(&mut self, mut buf: &[u8]) -> Result<(), NetError> {
        let start = self.now();
        self.rate_out.activate(start);
        while !buf.is_empty() {
            let n = self.write(buf)?;
            buf = &buf[n..];
        }
        self.rate_out.deactivate();
        Ok(())
    }

    /// One vectored send (gate check first); may be partial.
    pub(crate) fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, NetError> {
        let total: usize = bufs.iter().take(sys::MAX_SLICES).map(|b| b.len()).sum();
        if total == 0 {
            return Ok(0);
        }
        let now = self.now();
        self.rate_out.activate(now);
        self.check_sendable()?;
        if self.tls.is_some() {
            let take = total.min(self.tls_budget());
            self.gate_check(take)?;
            return self.write_vectored_tls(bufs, take);
        }
        self.gate_check(total.saturating_sub(self.approved))?;
        let mut zero_writes = 0u8;
        loop {
            self.check_sendable()?;
            match sys::send_vectored(&self.stream, bufs) {
                Ok(n) if n > 0 => {
                    self.sent(n);
                    self.approved = total - n;
                    return Ok(n);
                }
                Ok(_) => {
                    // As in `write`: once "full", the second time an error.
                    zero_writes += 1;
                    if zero_writes > 1 {
                        return Err(
                            self.os_error("send", io::Error::from(io::ErrorKind::WriteZero))
                        );
                    }
                    self.wait_writable()?;
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.wait_writable()?,
                Err(e) => return Err(self.os_error("send", e)),
            }
        }
    }

    /// Whether `sendfile` can take this connection: a plain socket, and on Windows only
    /// through the reactor's `TransmitFile`.
    pub(crate) fn sends_files_directly(&self) -> bool {
        self.tls.is_none()
            && (self.info.transport == Transport::Tcp
                || (self.info.transport == Transport::Unix && cfg!(target_os = "linux")))
    }

    /// Sends `len` bytes of `file` from `offset`, a gate check before each chunk; returns
    /// the count, which is `len`: a file that ends early fails the connection.
    pub(crate) fn send_file(
        &mut self,
        file: &std::fs::File,
        offset: u64,
        len: u64,
    ) -> Result<u64, NetError> {
        if len == 0 {
            return Ok(0);
        }
        let start = self.now();
        self.rate_out.activate(start);
        let direct = cfg!(unix) && self.sends_files_directly();
        let sent = if direct {
            self.send_file_direct(file, offset, len)?
        } else {
            0
        };
        let copied = self.send_file_copy(file, offset + sent, len - sent)?;
        self.rate_out.deactivate();
        Ok(sent + copied)
    }

    /// Zero copy until the file is done. Stops early, with the count so far, if the OS
    /// turns the file down, and the rest goes by reading and writing.
    fn send_file_direct(
        &mut self,
        file: &std::fs::File,
        offset: u64,
        len: u64,
    ) -> Result<u64, NetError> {
        // `sendfile` has no non-blocking flag, and Linux keeps sockets blocking here.
        let was_blocking = !sys::WAIT_BEFORE_RECV;
        if was_blocking {
            self.stream
                .set_nonblocking(true)
                .map_err(|e| self.fail_os("ioctl", e))?;
        }
        let result = self.send_file_chunks(file, offset, len);
        if was_blocking {
            let _ = self.stream.set_nonblocking(false);
        }
        result
    }

    fn send_file_chunks(
        &mut self,
        file: &std::fs::File,
        offset: u64,
        len: u64,
    ) -> Result<u64, NetError> {
        let mut sent = 0u64;
        while sent < len {
            let take = (len - sent).min(FILE_CHUNK) as usize;
            self.check_sendable()?;
            self.gate_check(take.saturating_sub(self.approved))?;
            self.approved = take;
            loop {
                self.check_sendable()?;
                match self.send_file_once(file, offset + sent, take) {
                    Ok(0) => return Err(self.file_truncated(sent)),
                    Ok(n) => {
                        self.sent(n);
                        self.approved = take - n;
                        sent += n as u64;
                        break;
                    }
                    Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.wait_writable()?,
                    Err(e) if sent == 0 && sys::send_file_refused(&e) => {
                        // The copy that follows asks the gate for these bytes itself.
                        self.approved = 0;
                        return Ok(0);
                    }
                    Err(e) => return Err(self.os_error("sendfile", e)),
                }
            }
        }
        Ok(sent)
    }

    #[cfg(unix)]
    fn send_file_once(&self, file: &std::fs::File, offset: u64, len: usize) -> io::Result<usize> {
        sys::send_file(self.stream.sock(), file, offset, len)
    }

    #[cfg(not(unix))]
    fn send_file_once(
        &self,
        _file: &std::fs::File,
        _offset: u64,
        _len: usize,
    ) -> io::Result<usize> {
        Err(io::Error::from(io::ErrorKind::Unsupported))
    }

    /// Reads and writes, for what cannot use `sendfile`: TLS, pipes, and the blocking
    /// path on Windows.
    fn send_file_copy(
        &mut self,
        file: &std::fs::File,
        offset: u64,
        len: u64,
    ) -> Result<u64, NetError> {
        if len == 0 {
            return Ok(0);
        }
        let mut buf = vec![0u8; FILE_COPY.min(len as usize)];
        let mut sent = 0u64;
        while sent < len {
            let take = ((len - sent) as usize).min(buf.len());
            let n = sys::read_file_at(file, &mut buf[..take], offset + sent)
                .map_err(|e| self.os_error("read", e))?;
            if n == 0 {
                return Err(self.file_truncated(sent));
            }
            let mut at = 0;
            while at < n {
                at += self.write(&buf[at..n])?;
            }
            sent += n as u64;
        }
        Ok(sent)
    }

    /// Receives up to `len` bytes into `file` at `offset`, under the same deadlines,
    /// minimum rate, kill, and drain as `read`; returns the count, short of `len` only
    /// when the peer closed. Linux splices socket to pipe to file (no copy through
    /// user space) unless TLS is on or bytes were read ahead; elsewhere, and when the
    /// socket or the file turns `splice` down, it copies through a 64 KiB buffer.
    pub(crate) fn recv_file(
        &mut self,
        file: &std::fs::File,
        offset: u64,
        len: u64,
    ) -> Result<u64, NetError> {
        if len == 0 {
            return Ok(0);
        }
        offset.checked_add(len).ok_or_else(|| {
            NetError::from_os("recv", io::Error::from(io::ErrorKind::InvalidInput))
        })?;
        #[cfg(target_os = "linux")]
        let pipe = if self.tls.is_none() {
            Some(sys::splice_pipe().map_err(|e| self.os_error("pipe", e))?)
        } else {
            None
        };
        // Off for good once the socket or the file turns `splice` down.
        #[cfg(target_os = "linux")]
        let refused = std::cell::Cell::new(pipe.is_none());
        let mut buf = vec![0u8; FILE_COPY.min(usize::try_from(len).unwrap_or(usize::MAX))];
        let mut got = 0u64;
        while got < len {
            let take = usize::try_from(len - got).map_or(buf.len(), |n| n.min(buf.len()));
            let at = offset + got;
            // Set when the bytes went straight into the file, not into `buf`.
            let spliced = std::cell::Cell::new(false);
            #[cfg(target_os = "linux")]
            let file_failed = std::cell::Cell::new(None);
            #[cfg(target_os = "linux")]
            let result = match &pipe {
                Some(pipe) if !refused.get() => {
                    self.read_raw_with(&mut buf[..take], |stream, b| {
                        if !refused.get() {
                            match sys::splice_to_file(stream.sock(), pipe, file, at, b.len()) {
                                Ok(s) => {
                                    spliced.set(true);
                                    refused.set(s.file_refused);
                                    return Ok(s.bytes);
                                }
                                Err(sys::SpliceError::Socket(e)) if sys::send_file_refused(&e) => {
                                    refused.set(true);
                                }
                                Err(sys::SpliceError::Socket(e)) => return Err(e),
                                // Bytes left the socket and are lost: never fall back to
                                // `recv`, which would put later bytes in their place.
                                Err(sys::SpliceError::File(e)) => {
                                    let same = Self::same_error(&e);
                                    file_failed.set(Some(e));
                                    return Err(same);
                                }
                            }
                        }
                        sys::recv(stream, b)
                    })
                }
                _ => self.read(&mut buf[..take]),
            };
            #[cfg(target_os = "linux")]
            if let Some(e) = file_failed.take() {
                // The read path closed the connection with this error's class; the
                // caller hears it as the file write it was.
                return Err(NetError::from_os("write", e));
            }
            #[cfg(not(target_os = "linux"))]
            let result = self.read(&mut buf[..take]);
            match result? {
                Got::Data(n) => {
                    if !spliced.get() {
                        sys::write_file_at(file, &buf[..n], at)
                            .map_err(|e| self.os_error("write", e))?;
                    }
                    got += n as u64;
                }
                Got::Eof => break,
                Got::Woken => {}
            }
        }
        Ok(got)
    }

    /// An error with the OS code (or the kind) of `e`, where `e` itself goes elsewhere.
    #[cfg(target_os = "linux")]
    fn same_error(e: &io::Error) -> io::Error {
        e.raw_os_error()
            .map_or_else(|| io::Error::from(e.kind()), io::Error::from_raw_os_error)
    }

    fn file_truncated(&mut self, sent: u64) -> NetError {
        self.fail(
            CloseReason::Io(OsErrorClass::FileTruncated),
            NetError::FileTruncated { sent },
        )
    }

    fn fail_os(&mut self, op: &'static str, e: io::Error) -> NetError {
        self.os_error(op, e)
    }

    /// Sends every slice, advancing them in place (no copy).
    pub(crate) fn write_all_vectored(
        &mut self,
        mut bufs: &mut [IoSlice<'_>],
    ) -> Result<(), NetError> {
        IoSlice::advance_slices(&mut bufs, 0);
        while !bufs.is_empty() {
            let n = self.write_vectored(bufs)?;
            IoSlice::advance_slices(&mut bufs, n);
        }
        self.rate_out.deactivate();
        Ok(())
    }

    /// Output is flushed; the outbound rate check stops.
    pub(crate) fn output_done(&mut self) {
        self.rate_out.deactivate();
    }

    /// Half-close.
    pub(crate) fn shutdown(&mut self, how: Shutdown) -> Result<(), NetError> {
        match self.stream.shutdown(how) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == io::ErrorKind::NotConnected => Ok(()),
            Err(e) => Err(NetError::from_os("shutdown", e)),
        }
    }

    /// What the next read would find, looked at without waiting and without
    /// consuming anything: one zero-timeout wait and, when the socket is readable,
    /// a one-byte peek (TCP; other streams report `Readable`).
    pub(crate) fn probe(&mut self) -> Result<Health, NetError> {
        self.check_terminal()?;
        let held = self
            .tls
            .as_ref()
            .is_some_and(|t| t.plain_at < t.plain_end || t.start < t.cin.len());
        if self.pending.is_some() || held {
            return Ok(Health::Readable);
        }
        if self.peer_closed {
            return Ok(Health::PeerClosed);
        }
        match self.stream.wait(Interest::Read, None, Some(Duration::ZERO)) {
            Ok(Ready::Socket) => {}
            Ok(_) => {
                return match sys::take_error(self.stream.sock()) {
                    Ok(None) => Ok(Health::Open),
                    Ok(Some(e)) | Err(e) => Err(self.os_error("probe", e)),
                };
            }
            Err(e) => return Err(NetError::from_os("poll", e)),
        }
        if self.stream.tcp().is_none() {
            return Ok(Health::Readable);
        }
        let mut one = [0u8; 1];
        match self.stream.peek(&mut one) {
            Ok(0) => Ok(Health::PeerClosed),
            Ok(_) => Ok(Health::Readable),
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(Health::Open),
            Err(e) => Err(self.os_error("recv", e)),
        }
    }

    /// FIN, then reads and discards until the peer's FIN, `within`, or a kill.
    /// Returns whether the peer closed, and how many bytes were discarded.
    pub(crate) fn drain_for(&mut self, within: Duration) -> (bool, u64) {
        self.tls_close_notify();
        let _ = self.stream.shutdown(Shutdown::Write);
        if self.peer_closed {
            return (true, 0);
        }
        let deadline = self.now().checked_add(within);
        let mut discarded = 0u64;
        let mut scratch = [0u8; 4096];
        loop {
            if self.killed().is_some() {
                return (false, discarded);
            }
            let now = self.now();
            let timeout = match deadline {
                Some(d) if now >= d => return (false, discarded),
                Some(d) => d
                    .saturating_duration_since(now)
                    .max(Duration::from_millis(1)),
                None => Duration::from_secs(1),
            };
            match self.wait(Interest::Read, timeout) {
                Ok(Ready::Socket) => {}
                Ok(_) => continue,
                Err(_) => return (false, discarded),
            }
            match self.stream.read(&mut scratch) {
                Ok(0) => {
                    self.peer_closed = true;
                    return (true, discarded);
                }
                Ok(n) => discarded += n as u64,
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}
                Err(_) => return (false, discarded),
            }
        }
    }

    /// Whether bytes wait in the socket now: one zero-timeout wait. A drain leaves a
    /// connection whose next request already arrived to answer it first.
    /// A connection that has received nothing yet, within `first_request_grace` of
    /// its accept: a drain lets it bring its first request instead of closing it as
    /// idle, since a client that connected just before the drain is still writing it.
    pub(crate) fn awaits_first_request(&self) -> bool {
        self.bytes_in == 0
            && self.pending.is_none()
            && self
                .info
                .accepted_at
                .checked_add(self.limits.first_request_grace)
                .is_some_and(|until| self.now() < until)
    }

    pub(crate) fn input_waiting(&self) -> bool {
        self.pending.is_some()
            || matches!(
                self.stream.wait(Interest::Read, None, Some(Duration::ZERO)),
                Ok(Ready::Socket)
            )
    }

    /// The close reason: the first fatal condition, or `fallback`.
    pub(crate) fn reason_or(&self, fallback: CloseReason) -> CloseReason {
        match self.killed() {
            Some(k) => CloseReason::Killed(k),
            None => self.terminal.unwrap_or(fallback),
        }
    }

    // ---- the reactor: the same bookkeeping, without waiting -----------------------

    /// Puts the socket in non-blocking mode.
    #[cfg(feature = "reactor")]
    pub(crate) fn set_nonblocking(&self) -> io::Result<()> {
        self.stream.set_nonblocking(true)
    }

    /// Bytes arrived (the reactor made the call). `Err` is a peer below the minimum
    /// rate: the check runs here as well as on the timer, because a peer that sends
    /// more often than the check interval re-arms the timer before it can fire.
    #[cfg(feature = "reactor")]
    pub(crate) fn note_received(&mut self, n: usize) -> Result<(), NetError> {
        let now = self.now();
        self.bytes_in += n as u64;
        self.progress_at = now;
        if self.phase == Phase::Idle {
            self.phase = Phase::Receiving;
            self.rate_in.activate(now);
        }
        self.rate_in.record(now, n);
        self.check_rate_in(now)
    }

    /// Ciphertext arrived: it counts for the rate and the deadline; the plaintext
    /// starts the exchange when it is delivered. `Err` as for `note_received`.
    #[cfg(feature = "reactor")]
    pub(crate) fn note_cipher(&mut self, n: usize) -> Result<(), NetError> {
        let now = self.now();
        self.bytes_in += n as u64;
        self.progress_at = now;
        // As on the pool: any ciphertext starts an exchange, so records that carry no
        // plaintext fall under the read deadline and the inbound rate instead of
        // moving the idle deadline for ever.
        if self.phase == Phase::Idle {
            self.phase = Phase::Receiving;
            self.rate_in.activate(now);
        }
        self.rate_in.record(now, n);
        self.check_rate_in(now)
    }

    /// `Err(SlowPeer)` when input is below the minimum rate.
    #[cfg(feature = "reactor")]
    fn check_rate_in(&mut self, now: Instant) -> Result<(), NetError> {
        if self.rate_in.too_slow(&self.limits.min_rate, now) {
            return Err(self.fail(
                CloseReason::SlowPeer {
                    direction: Direction::In,
                },
                NetError::SlowPeer {
                    direction: Direction::In,
                },
            ));
        }
        Ok(())
    }

    /// Bytes left (the reactor made the call). `Err` is a reader below the minimum
    /// rate, checked here for the reason given at `note_received`.
    #[cfg(feature = "reactor")]
    pub(crate) fn note_sent(&mut self, n: usize) -> Result<(), NetError> {
        self.sent(n);
        let now = self.now();
        self.check_rate_out(now)
    }

    /// As `note_sent`, for records the TLS engine wrote on its own: not the
    /// session's reply, so the exchange does not end on them.
    #[cfg(feature = "reactor")]
    pub(crate) fn note_engine_sent(&mut self, n: usize) -> Result<(), NetError> {
        let (replied, spoke) = (self.replied, self.drains & SPOKE_IDLE);
        let r = self.note_sent(n);
        self.replied = replied;
        self.drains = self.drains & !SPOKE_IDLE | spoke;
        r
    }

    /// Before a send: the output deadline starts, a dead connection stops here,
    /// and the gate is asked about the bytes it has not approved.
    #[cfg(feature = "reactor")]
    pub(crate) fn check_send(&mut self, bytes: usize) -> Result<(), NetError> {
        let now = self.now();
        self.rate_out.activate(now);
        if self.phase == Phase::Idle {
            self.progress_at = now;
        }
        self.check_sendable()?;
        self.gate_check(bytes.saturating_sub(self.approved))
    }

    /// After a send of `n` out of `total` offered: the tail stays approved.
    #[cfg(feature = "reactor")]
    pub(crate) fn sent_of(&mut self, total: usize, n: usize) {
        self.approved = total.saturating_sub(n);
    }

    /// The deadline that applies to a wait for input, and its kind.
    fn read_deadline(&self) -> (Instant, TimeoutKind) {
        match (self.handshake_deadline, self.phase) {
            (Some(d), _) => (d, TimeoutKind::Handshake),
            (None, Phase::Idle) => (
                self.progress_at + self.scaled(self.idle_timeout),
                TimeoutKind::Idle,
            ),
            (None, _) => (
                self.progress_at + self.limits.read_timeout,
                TimeoutKind::Read,
            ),
        }
    }

    /// When a wait for input must look at the clock again.
    #[cfg(feature = "reactor")]
    pub(crate) fn read_timer(&self, now: Instant) -> Instant {
        let mut until = self.read_deadline().0;
        if let Some(d) = self.exchange_deadline {
            until = until.min(d);
        }
        if let Some(c) = self.rate_in.next_check(&self.limits.min_rate, now) {
            until = until.min(c);
        }
        until
    }

    /// The checks of a wait for input, at the time its timer fired.
    #[cfg(feature = "reactor")]
    pub(crate) fn read_check(&mut self, now: Instant) -> Result<(), NetError> {
        self.check_terminal()?;
        let (deadline, kind) = self.read_deadline();
        if now >= deadline {
            return Err(self.timed_out(kind));
        }
        if self.exchange_deadline.is_some_and(|d| now >= d) {
            return Err(self.timed_out(TimeoutKind::Exchange));
        }
        self.check_rate_in(now)
    }

    /// When a wait for room to write must look at the clock again.
    #[cfg(feature = "reactor")]
    pub(crate) fn write_timer(&self, now: Instant) -> Instant {
        let mut until = self.progress_at + self.limits.write_timeout;
        if let Some(d) = self.exchange_deadline {
            until = until.min(d);
        }
        if let Some(c) = self.rate_out.next_check(&self.limits.min_rate, now) {
            until = until.min(c);
        }
        if let Some(d) = self.soft_until() {
            until = until.min(d);
        }
        until
    }

    /// The checks of a wait for room to write, at the time its timer fired.
    #[cfg(feature = "reactor")]
    pub(crate) fn write_check(&mut self, now: Instant) -> Result<(), NetError> {
        self.check_sendable()?;
        if now >= self.progress_at + self.limits.write_timeout {
            return Err(self.timed_out(TimeoutKind::Write));
        }
        if self.exchange_deadline.is_some_and(|d| now >= d) {
            return Err(self.timed_out(TimeoutKind::Exchange));
        }
        self.check_rate_out(now)
    }

    /// `Err(SlowPeer)` when output is below the minimum rate.
    #[cfg(feature = "reactor")]
    fn check_rate_out(&mut self, now: Instant) -> Result<(), NetError> {
        if self.rate_out.too_slow(&self.limits.min_rate, now) {
            return Err(self.fail(
                CloseReason::SlowPeer {
                    direction: Direction::Out,
                },
                NetError::SlowPeer {
                    direction: Direction::Out,
                },
            ));
        }
        Ok(())
    }

    /// Records an OS failure class as the close reason.
    #[cfg(feature = "reactor")]
    pub(crate) fn note_failure(&mut self, class: OsErrorClass) {
        let reason = match class {
            OsErrorClass::Reset | OsErrorClass::Aborted => CloseReason::PeerReset,
            other => CloseReason::Io(other),
        };
        if self.terminal.is_none() {
            self.terminal = Some(reason);
        }
    }

    /// Whether the PROXY handshake already ran.
    #[cfg(feature = "reactor")]
    pub(crate) fn proxy_done(&self) -> bool {
        self.info.proxy.is_some()
    }

    /// Bytes read past a handshake, into `buf`; 0 when none are left.
    #[cfg(feature = "reactor")]
    pub(crate) fn take_read_ahead(&mut self, buf: &mut [u8]) -> usize {
        let n = self.read_pending(buf);
        if n > 0 {
            let now = self.now();
            self.progress_at = now;
            if self.phase == Phase::Idle {
                self.phase = Phase::Receiving;
                self.rate_in.activate(now);
            }
        }
        n
    }

    /// Whether bytes read past a handshake are waiting.
    #[cfg(feature = "reactor")]
    pub(crate) fn has_read_ahead(&self) -> bool {
        self.pending
            .as_ref()
            .is_some_and(|p| self.pending_at < p.len())
    }

    /// One turn of the TLS machine.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_next(&mut self) -> Result<TlsNext, NetError> {
        let Some(mut t) = self.tls.take() else {
            return Ok(TlsNext::Eof);
        };
        let mut r = self.tls_advance(&mut t);
        if t.held > 0 && matches!(r, Ok(TlsNext::NeedInput)) {
            // Nothing more to answer in this turn: the held records go out now, and
            // the machine asks for input again after them.
            t.event = Some(Ev::NeedInput);
            t.cout.set_len(t.held);
            r = Ok(TlsNext::Transmit);
        }
        self.tls = Some(t);
        r
    }

    /// Keeps the records in `cout` for the session's first reply instead of sending
    /// them now (D-180): `true` when they are the handshake's last records
    /// (the tickets, with the completion still to report) and the client's request
    /// is already in the input, so the client waits for nothing these records carry
    /// and the reply follows within this turn. Anything else sends them at once.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_hold(&mut self) -> bool {
        let Some(t) = self.tls.as_mut() else {
            return false;
        };
        let hold = t.held == 0
            && !t.done
            && matches!(t.event, Some(Ev::Handshaken))
            && t.start < t.cin.len()
            && !t.cout.is_empty();
        if hold {
            t.held = t.cout.len();
        }
        hold
    }

    /// The records to send; give the buffer back with [`Link::tls_put_cout`].
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_take_cout(&mut self) -> Option<Buffer> {
        let t = self.tls.as_mut()?;
        t.held = 0;
        Some(std::mem::replace(&mut t.cout, Buffer::placeholder()))
    }

    #[cfg(feature = "reactor")]
    pub(crate) fn tls_put_cout(&mut self, buffer: Buffer) {
        if let Some(t) = self.tls.as_mut() {
            t.cout = buffer;
        }
    }

    /// The ciphertext input, compacted, for a receive; `tls_put_cin` gives it back.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_take_cin(&mut self) -> Result<Option<Buffer>, NetError> {
        let Some(mut t) = self.tls.take() else {
            return Ok(None);
        };
        let r = self.tls_make_room(&mut t);
        let cin = r.map(|()| std::mem::replace(&mut t.cin, Buffer::placeholder()));
        self.tls = Some(t);
        cin.map(Some)
    }

    #[cfg(feature = "reactor")]
    pub(crate) fn tls_put_cin(&mut self, buffer: Buffer) {
        if let Some(t) = self.tls.as_mut() {
            t.cin = buffer;
        }
    }

    /// The transport ended under TLS.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_transport_closed(&mut self) {
        if let Some(t) = self.tls.as_mut() {
            let _ = t.session.on_transport_closed();
            t.eof = true;
        }
    }

    /// Copies plaintext into `buf` (the machine said `Plain`).
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_deliver(&mut self, buf: &mut [u8]) -> usize {
        let Some(t) = self.tls.as_mut() else {
            return 0;
        };
        let have = &t.cin.as_slice()[t.plain_at..t.plain_end];
        let n = have.len().min(buf.len());
        buf[..n].copy_from_slice(&have[..n]);
        t.plain_at += n;
        let now = self.now();
        self.progress_at = now;
        if self.phase == Phase::Idle {
            self.phase = Phase::Receiving;
            self.rate_in.activate(now);
        }
        n
    }

    /// Encrypts up to one budget of plaintext into the output buffer.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_seal(
        &mut self,
        bufs: &[IoSlice<'_>],
        take: usize,
    ) -> Result<usize, NetError> {
        let Some(mut t) = self.tls.take() else {
            return Ok(0);
        };
        let r = self.tls_encrypt(&mut t, bufs, take);
        self.tls = Some(t);
        r
    }

    /// After a seal that took the last of the output before a graceful close:
    /// `close_notify` joins the records in `cout`, so they leave in one send and
    /// the close sends no second one (D-180). Nothing happens when it does not fit.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_seal_close_notify(&mut self) {
        let Some(t) = self.tls.as_mut() else { return };
        if !t.done || t.eof || t.notified || t.cout.spare().len() < TLS_OVERHEAD {
            return;
        }
        let used = t.cout.len();
        if let Ok(n) = t.session.close(t.cout.spare()) {
            t.cout.set_len((used + n).min(t.cout.capacity()));
            t.notified = true;
        }
    }

    /// The plaintext one sealed write may take.
    #[cfg(feature = "reactor")]
    pub(crate) fn tls_write_budget(&self) -> usize {
        self.tls_budget()
    }

    /// The gate check for a sealed write.
    #[cfg(feature = "reactor")]
    pub(crate) fn check_seal(&mut self, bytes: usize) -> Result<(), NetError> {
        let now = self.now();
        self.rate_out.activate(now);
        self.check_sendable()?;
        self.gate_check(bytes)
    }

    /// A graceful close on the reactor. `true` when unread input may still arrive,
    /// so the socket must linger to protect the last response: FIN now, by
    /// `shutdown`. Otherwise the close that follows sends the FIN itself, behind
    /// whatever is still queued, and a `shutdown` first would change nothing on the
    /// wire: once the socket is closed, input that arrives is answered with a reset
    /// either way (D-198).
    #[cfg(feature = "reactor")]
    pub(crate) fn begin_graceful_close(&mut self, readable: bool) -> bool {
        self.tls_close_notify();
        let linger = self.stream.half_closes()
            && !self.peer_closed
            && (self.phase != Phase::Idle || readable || self.drains & SPOKE_IDLE != 0);
        if linger {
            let _ = self.stream.shutdown(Shutdown::Write);
        }
        linger
    }

    /// Closes the socket after the driver let go of it.
    #[cfg(feature = "reactor")]
    pub(crate) fn finish_reactor(mut self, reason: CloseReason) -> CloseReason {
        // A pipe (the one stream that does not half-close) has written through the
        // driver; only a denial writes through the stream itself, and a denial
        // write still pending here waits for a client that is not reading. The
        // stream would wait up to a second for it on drop, on the worker's thread:
        // drop it instead, as a reset would (D-209).
        if (reason.is_abortive() && self.soft_close().is_none()) || !self.stream.half_closes() {
            self.stream.set_abortive();
        }
        self.slot.begin_close();
        if let Some(mut gate) = self.gate.take() {
            gate.close(&self.info, reason);
        }
        let Link { stream, slot, .. } = self;
        drop(stream);
        slot.uninstall();
        reason
    }

    /// Closes the connection with `reason`, gracefully (FIN, then a bounded linger
    /// that reads and discards) or abortively (RST), and gives the gate its ticket back.
    /// Gives the socket up for `Server::adopt`: nothing is written, and a gate
    /// registered with `set_gate` gets its close with `reason`. `None` (and the
    /// connection closes) when TLS runs on it or bytes were read ahead.
    pub(crate) fn into_stream(mut self, reason: CloseReason) -> Option<sys::Stream> {
        if self.tls.is_some() || self.pending.is_some() {
            self.finish(CloseReason::SessionError);
            return None;
        }
        self.slot.begin_close();
        if let Some(mut gate) = self.gate.take() {
            gate.close(&self.info, reason);
        }
        let Link { stream, .. } = self;
        Some(stream)
    }

    pub(crate) fn finish(self, reason: CloseReason) -> CloseReason {
        self.finish_with(reason, |_| false)
    }

    /// As `finish`; `own(k)` says a kill with reason `k` was net-io's own (a drain's
    /// deadline, a stop). Such a kill during the linger ends the linger and keeps the
    /// graceful close's reason, as on the reactor; a user's kill still makes it
    /// `Killed` and a reset (D-201).
    pub(crate) fn finish_with(
        mut self,
        reason: CloseReason,
        own: impl Fn(KillReason) -> bool,
    ) -> CloseReason {
        let mut reason = reason;
        // After a denial or during a soft kill, an abortive reason still closes
        // gracefully, with the shorter linger: the peer reads what was sent.
        let soft = if reason.is_abortive() {
            self.soft_close()
        } else {
            None
        };
        let graceful = !reason.is_abortive() || soft.is_some();
        if graceful {
            self.tls_close_notify();
            let within = soft.unwrap_or(self.limits.graceful_linger);
            if self.linger_gracefully(within, soft.is_some()) {
                // A kill arrived during the linger: close abortively at once.
                if let Some(k) = self.killed().filter(|&k| !own(k)) {
                    reason = CloseReason::Killed(k);
                }
            }
        }
        let abort = if soft.is_some() {
            self.hard_killed()
        } else {
            reason.is_abortive()
        };
        if abort {
            self.stream.set_abortive();
        }
        // No kill can start after this, and one in flight finishes first.
        self.slot.begin_close();
        if let Some(mut gate) = self.gate.take() {
            gate.close(&self.info, reason);
        }
        let Link { stream, slot, .. } = self;
        drop(stream);
        slot.uninstall();
        reason
    }

    /// Closes without the linger: never blocks (used when a connection is dropped).
    pub(crate) fn finish_quick(mut self, reason: CloseReason) -> CloseReason {
        if reason.is_abortive() && self.soft_close().is_none() {
            self.stream.set_abortive();
        } else {
            let _ = self.stream.shutdown(Shutdown::Write);
        }
        self.slot.begin_close();
        if let Some(mut gate) = self.gate.take() {
            gate.close(&self.info, reason);
        }
        let Link { stream, slot, .. } = self;
        drop(stream);
        slot.uninstall();
        reason
    }

    /// A timeout the session chose to survive: clear it and restart the clock.
    pub(crate) fn rearm(&mut self) {
        if matches!(
            self.terminal,
            Some(
                CloseReason::Idle
                    | CloseReason::ReadTimeout
                    | CloseReason::WriteTimeout
                    | CloseReason::ExchangeDeadline
                    | CloseReason::ParkDeadline
            )
        ) {
            self.terminal = None;
        }
        self.progress_at = self.now();
        if self
            .exchange_deadline
            .is_some_and(|d| d <= self.progress_at)
        {
            self.exchange_deadline = None;
        }
    }

    /// One send attempt without the gate check, for the denial bytes after a denial.
    /// Under TLS the denial is a record like any other: encrypted into the output
    /// buffer and sent once, or not sent at all if the engine cannot encrypt it
    /// (the output buffer is out with a send, or the denial does not fit).
    pub(crate) fn send_denial_once(&mut self, buf: &[u8]) {
        let sent = match self.tls.as_mut() {
            Some(t) => {
                // Held records go first: the denial's record follows them in sequence.
                let held = t.held;
                t.cout.set_len(held);
                t.held = 0;
                match t.session.encrypt(buf, t.cout.spare()) {
                    Ok(n) if n > 0 => {
                        t.cout.set_len(held + n);
                        let r = sys::send(&self.stream, t.cout.as_slice());
                        t.cout.set_len(0);
                        r.ok()
                    }
                    _ => None,
                }
            }
            None => sys::send(&self.stream, buf).ok(),
        };
        if let Some(n) = sent {
            self.bytes_out += n as u64;
            self.replied = true;
            if n > 0 && !self.limits.denial_linger.is_zero() {
                self.soft.get_or_insert_with(Box::default).denial = true;
            }
        }
    }

    /// FIN, then read and discard up to the linger budget so unread input does not
    /// turn into an RST that destroys the last response, for at most `within`.
    /// Returns `true` if killed meanwhile (a soft kill does not count). `always`: a
    /// flush then close (a denial, `close_after_flush`), which lingers in any phase.
    fn linger_gracefully(&mut self, within: Duration, always: bool) -> bool {
        let _ = self.stream.shutdown(Shutdown::Write);
        if self.peer_closed || !self.stream.half_closes() {
            return false;
        }
        // Between exchanges with nothing unread there is nothing to protect from a
        // reset: close at once (one zero-timeout poll), so a drain of idle
        // connections does not wait out the linger. Not after the session spoke
        // while idle: the peer's answer may be on its way (D-192). Not for a flush
        // then close either: it ends the connection on the server's terms, and the
        // peer's request may be crossing it whatever the phase (D-182, D-202).
        if !always
            && self.phase == Phase::Idle
            && self.drains & SPOKE_IDLE == 0
            && !matches!(self.wait(Interest::Read, Duration::ZERO), Ok(Ready::Socket))
        {
            return false;
        }
        let deadline = self.now() + within;
        let mut left = self.limits.graceful_linger_bytes as usize;
        let mut scratch = [0u8; 2048];
        while left > 0 {
            if self.hard_killed() {
                return true;
            }
            let now = self.now();
            if now >= deadline {
                break;
            }
            let timeout = deadline
                .saturating_duration_since(now)
                .max(Duration::from_millis(1));
            match self.wait(Interest::Read, timeout) {
                Ok(Ready::Socket) => {}
                Ok(Ready::Woken) => continue,
                _ => break,
            }
            let take = left.min(scratch.len());
            match self.stream.read(&mut scratch[..take]) {
                Ok(0) => break,
                Ok(n) => left -= n,
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
                Err(_) => break,
            }
        }
        self.hard_killed()
    }
}

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

    /// On Windows a thread's wake outlives the thread: it goes back to the spares
    /// instead of being closed by a thread-local destructor (D-173).
    #[test]
    fn test_thread_wake_is_kept_when_its_thread_ends() {
        let weak = std::thread::spawn(|| Arc::downgrade(&thread_wake().expect("wake")))
            .join()
            .expect("thread");
        assert!(weak.upgrade().is_some(), "closed when its thread ended");
    }
}