devsandbox 0.9.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! Stream multiplexer over one frame connection, shared by the helper daemon
//! and the host bridge driver (devsbd includes it via `#[path]`, like
//! `proto.rs`). Both ends run the same routing so their close semantics can't
//! drift: whoever sees a local stream end first sends `Close`; receiving
//! `Close` shuts the local socket down without echoing one back.
//!
//! Local ends are a [`Conn`]: a unix socket (ssh-agent streams) or a TCP
//! socket (forwarded ports, docs/architecture/daemon/forwards.md). Unix-only: the Windows
//! host will need a named-pipe stream here (docs/plans/active/windows-support.md).
//!
//! Two kinds of stream share the connection:
//! - **Legacy** (`Open`, ssh-agent, notify): `Data` is written straight into the
//!   local socket on the frame-reader thread, and local EOF sends `Close`. Small
//!   request/response traffic, kept as it was, plus one addition: a peer `Eof`
//!   `shutdown(Write)`s the local socket, so a sender that writes its request
//!   with `Mux::send` and then `Eof` (the daemon's notify flush) still gets the
//!   reply. Never sent on agent streams, so their behavior is unchanged.
//! - **Flow-controlled** (`Connect`, forwarded TCP, and `Open` on a channel
//!   where `proto::channel::flows` holds, e.g. `RPC`): per-direction credit
//!   (`Window`), a per-stream write queue drained by its own thread so the
//!   reader never blocks, and half-close (`Eof`). One slow local reader can't
//!   stall the other streams or starve the keepalive.
//!
//! `Open`s come from the daemon (low ids) toward the host, and from the host
//! (high ids, `HOST_ID_BIT`) toward a daemon that registered `on_host_open`.
//!
//! Besides streams, one request/answer on stream 0: the host's `PortQuery`
//! (who listens on a port), answered with `PortInfo` by a daemon that
//! registered a lookup (`on_port_query`); the host waits for it in
//! `port_query`.

use std::collections::{HashMap, VecDeque};
use std::io::{self, Read, Write};
use std::net::{Shutdown, TcpStream};
use std::os::unix::net::UnixStream;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

use super::proto::{self, Frame, INITIAL_WINDOW};

/// Read chunk for local stream -> `Data` frames; far below `MAX_PAYLOAD`.
const CHUNK: usize = 16 * 1024;

/// Stack for the per-stream threads (`pump`, `flow_pump`, `flow_writer`), one
/// or two per live connection. Their buffers live on the heap, so the 2 MiB
/// default only reserves address space; 128 KiB still leaves room for a host
/// panic (message + backtrace) on one of them.
const STREAM_STACK: usize = 128 * 1024;

/// `std::thread::spawn` with [`STREAM_STACK`]; panics on failure like it.
fn spawn_stream_thread(f: impl FnOnce() + Send + 'static) {
    std::thread::Builder::new().stack_size(STREAM_STACK).spawn(f).expect("failed to spawn stream thread");
}

/// Keepalive `Ping` cadence and the inbound-silence window after which the
/// peer is declared dead (`on_dead`). A wedged peer that stops reading (so our
/// `Ping`s pile up unanswered) is caught within `KEEPALIVE_TIMEOUT`.
pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
pub const KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(45);

/// Pure liveness rule, split out so the timeout logic is testable with
/// injected durations: dead once no inbound frame has arrived for `timeout`.
fn is_dead(since_last_inbound: Duration, timeout: Duration) -> bool {
    since_last_inbound >= timeout
}

/// Cap on concurrently live streams per bridge. An `Open` past this is refused
/// (`Close`); ssh-agent volumes never approach it, so it's purely a bound on a
/// misbehaving or hostile peer.
const MAX_STREAMS: usize = 64;

/// Cap on live host-initiated (`Connect`) streams, enforced by the receiving
/// side. Separate from `MAX_STREAMS` and higher: a browser behind one forward
/// opens many connections at once.
const MAX_HOST_STREAMS: usize = 256;

/// Stream-id spaces: the daemon allocates ids with the high bit clear
/// (1..2^31), the host with it set (`Mux::connect`, host-opened `Open`s). The
/// host refuses a peer `Open` whose id has this bit set (it registers no
/// `on_host_open`), the daemon a `Connect` whose id doesn't
/// (docs/architecture/helper/protocol.md, _Frames_).
const HOST_ID_BIT: u32 = 1 << 31;

/// Port lookups the daemon runs at once per connection; a `PortQuery` past
/// this goes unanswered (the host's wait times out). The host asks one at a
/// time per forward, so this only bounds a misbehaving peer.
const MAX_PORT_LOOKUPS: usize = 4;

/// The daemon's answer to a `PortQuery`: the `(pid, comm)` listening on a TCP
/// port (see `Mux::on_port_query`).
pub type PortLookup = Arc<dyn Fn(u16) -> Vec<(u32, String)> + Send + Sync>;

/// The daemon's answer to a host-opened `Open` `(stream, channel)`: a local
/// end for the stream, `None` to refuse it (see `Mux::on_host_open`). Runs on
/// the frame reader: quick (hand the other end to a thread).
pub type HostOpen = Arc<dyn Fn(u32, u8) -> Option<Conn> + Send + Sync>;

/// Reason sent with the `Close` for a peer that overran its credit.
const FLOW_VIOLATION: &str = "flow control violation";

/// Pure grant rule: return credit once half the window has been consumed, so
/// a bulk transfer costs one `Window` per half-window, not one per chunk, and
/// the sender still has half a window in flight while the grant travels.
fn should_grant(ungranted: u32) -> bool {
    ungranted >= INITIAL_WINDOW / 2
}

/// Pure admission check for an inbound `Data` of `len` bytes on a
/// flow-controlled stream. `Err` is the `Close` reason: the peer sent more
/// than we granted (the queue would no longer be bounded by the window), or
/// sent data after its own `Eof`.
fn check_data(len: usize, recv_credit: u32, eof_received: bool) -> Result<(), &'static str> {
    if eof_received {
        return Err("data after eof");
    }
    if len > recv_credit as usize {
        return Err(FLOW_VIOLATION);
    }
    Ok(())
}

/// Pure teardown rule for a half-closed stream: done once we've sent our
/// `Eof`, received the peer's, and the writer has drained the queue into the
/// local socket and shut its write side. Neither side sends `Close` then;
/// both reach this state independently.
fn teardown_ready(eof_sent: bool, eof_received: bool, drained: bool) -> bool {
    eof_sent && eof_received && drained
}

/// Pure id policy for an inbound `Connect` or host-opened `Open`: host id
/// space (high bit set), not already live, and under the host-stream cap.
/// Both kinds share `MAX_HOST_STREAMS`.
fn connect_allowed(stream: u32, live: bool, live_host_streams: usize) -> bool {
    stream & HOST_ID_BIT != 0 && !live && live_host_streams < MAX_HOST_STREAMS
}

/// Next host-allocated id: `HOST_ID_BIT | n`, `n` counting up monotonically
/// through 1..2^31 and wrapping back to 1, skipping live ids. Monotonic rather
/// than lowest-free because right after a clean both-`Eof` teardown the peer
/// may not have processed our last frame for that id yet; reusing it at once
/// could graft stale frames onto a new stream.
fn next_host_id(next: &mut u32, is_live: impl Fn(u32) -> bool) -> u32 {
    loop {
        let n = *next;
        *next = if n + 1 >= HOST_ID_BIT { 1 } else { n + 1 };
        let id = HOST_ID_BIT | n;
        if !is_live(id) {
            return id;
        }
    }
}

/// Validate a `Connect` target before it hits the wire: the frame encodes the
/// host length as one byte, and the peer rejects an empty host or port 0 as
/// malformed (which ends the whole connection, not just the stream).
fn validate_connect_target(host: &str, port: u16) -> io::Result<()> {
    let bad = |msg: &str| Err(io::Error::new(io::ErrorKind::InvalidInput, msg.to_string()));
    if host.is_empty() {
        return bad("connect: empty host");
    }
    if host.len() > u8::MAX as usize {
        return bad("connect: host longer than 255 bytes");
    }
    if port == 0 {
        return bad("connect: port 0");
    }
    Ok(())
}

/// A stream's local socket. An enum rather than a trait object keeps the mux
/// std-only and monomorphic; both variants share the same read/write/shutdown
/// surface, so routing doesn't care which one it holds.
#[derive(Debug)]
pub enum Conn {
    Unix(UnixStream),
    Tcp(TcpStream),
}

impl Conn {
    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        match self {
            Conn::Unix(s) => s.shutdown(how),
            Conn::Tcp(s) => s.shutdown(how),
        }
    }

    pub fn try_clone(&self) -> io::Result<Conn> {
        Ok(match self {
            Conn::Unix(s) => Conn::Unix(s.try_clone()?),
            Conn::Tcp(s) => Conn::Tcp(s.try_clone()?),
        })
    }
}

impl From<UnixStream> for Conn {
    fn from(s: UnixStream) -> Conn {
        Conn::Unix(s)
    }
}

impl From<TcpStream> for Conn {
    fn from(s: TcpStream) -> Conn {
        Conn::Tcp(s)
    }
}

/// `&Conn` like `&UnixStream`/`&TcpStream`: lets the `Data` arm write through
/// a shared `Arc<Conn>` without a lock.
impl Read for &Conn {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match *self {
            Conn::Unix(s) => (&*s).read(buf),
            Conn::Tcp(s) => (&*s).read(buf),
        }
    }
}

impl Write for &Conn {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match *self {
            Conn::Unix(s) => (&*s).write(buf),
            Conn::Tcp(s) => (&*s).write(buf),
        }
    }
    fn flush(&mut self) -> io::Result<()> {
        match *self {
            Conn::Unix(s) => (&*s).flush(),
            Conn::Tcp(s) => (&*s).flush(),
        }
    }
}

impl Read for Conn {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        (&*self).read(buf)
    }
}

impl Write for Conn {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        (&*self).write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        (&*self).flush()
    }
}

/// Called once when a host-initiated stream ends, with the reason: the peer's
/// `Close` reason (e.g. `connection refused`), our own local error, `"bridge
/// closed"` when the connection went away, or empty for a clean close. Runs on
/// a mux thread, possibly the frame reader: keep it quick (e.g. send on a
/// channel), or every stream on the connection waits.
pub type OnClose = Box<dyn FnOnce(String) + Send>;

/// A registered stream.
enum Entry {
    /// `Open` stream on a legacy channel (ssh-agent, notify, control): the
    /// original unbuffered path.
    Legacy(Arc<Conn>),
    /// `Connect` stream or `Open` on a flowing channel: credit, write queue,
    /// half-close.
    Flow(Arc<Flow>),
}

impl Entry {
    fn end(self, reason: String) {
        match self {
            Entry::Legacy(conn) => {
                let _ = conn.shutdown(Shutdown::Both);
            }
            Entry::Flow(flow) => flow.end(reason),
        }
    }
}

/// Shared state of one flow-controlled stream. One condvar serves both waiters
/// (the pump waiting for credit, the writer waiting for queued data); every
/// change is announced with `notify_all`, so neither can miss its wake-up.
struct Flow {
    state: Mutex<FlowState>,
    cv: Condvar,
}

struct FlowState {
    /// The local socket; `None` while the daemon's dial is still pending.
    conn: Option<Arc<Conn>>,
    /// Bytes we may still send (granted by the peer's `Window`s).
    send_credit: u32,
    /// Bytes the peer may still send us; mirrors the peer's own credit, so an
    /// inbound `Data` beyond it is an overrun. Bounds `queue` by construction.
    recv_credit: u32,
    /// Inbound `Data` waiting for the writer thread.
    queue: VecDeque<Vec<u8>>,
    /// Bytes written to the local socket but not yet granted back.
    ungranted: u32,
    eof_sent: bool,
    eof_received: bool,
    /// The writer drained the queue after the peer's `Eof` and shut the local
    /// write side down.
    drained: bool,
    /// Torn down: threads exit, late events are ignored.
    closed: bool,
    on_close: Option<OnClose>,
}

impl Flow {
    fn new(conn: Option<Arc<Conn>>, on_close: Option<OnClose>) -> Arc<Flow> {
        Arc::new(Flow {
            state: Mutex::new(FlowState {
                conn,
                send_credit: INITIAL_WINDOW,
                recv_credit: INITIAL_WINDOW,
                queue: VecDeque::new(),
                ungranted: 0,
                eof_sent: false,
                eof_received: false,
                drained: false,
                closed: false,
                on_close,
            }),
            cv: Condvar::new(),
        })
    }

    /// Mark closed (once), wake both threads, shut the local socket (which
    /// unblocks a pending read or write) and report `reason`. Callers
    /// unregister the stream first; nothing here touches the stream map.
    fn end(&self, reason: String) {
        let (conn, on_close) = {
            let mut st = self.state.lock().unwrap();
            if st.closed {
                return;
            }
            st.closed = true;
            st.queue.clear();
            (st.conn.clone(), st.on_close.take())
        };
        self.cv.notify_all();
        if let Some(conn) = conn {
            let _ = conn.shutdown(Shutdown::Both);
        }
        if let Some(f) = on_close {
            f(reason);
        }
    }
}

/// Answer to an inbound `Connect`, handed to `serve_with`'s `on_connect`.
/// `finish(Ok(conn))` attaches the dialed socket, `finish(Err(reason))` refuses
/// the stream with `Close { reason }`. Dropping it unfinished refuses too, so a
/// forgotten reply can't leave a stream pending forever.
pub struct ConnectReply {
    mux: Arc<Mux>,
    stream: u32,
    flow: Option<Arc<Flow>>,
}

impl ConnectReply {
    pub fn finish(mut self, result: Result<Conn, String>) {
        let flow = self.flow.take().expect("finish runs once");
        self.mux.complete_connect(self.stream, &flow, result);
    }
}

impl Drop for ConnectReply {
    fn drop(&mut self) {
        if let Some(flow) = self.flow.take() {
            self.mux.complete_connect(self.stream, &flow, Err("dial abandoned".into()));
        }
    }
}

/// Control frames queued by the frame reader for the control writer thread.
struct Ctl {
    queue: VecDeque<Frame>,
    /// A writer thread is running (spawned on demand, exits once the mux has
    /// ended and the queue is empty).
    writer: bool,
}

pub struct Mux {
    out: Mutex<Box<dyn Write + Send>>,
    /// Frames the reader must send without touching `out` (see `send_ctl`).
    ctl: Mutex<Ctl>,
    ctl_cv: Condvar,
    // Entries hold `Arc`s so the frame reader can clone a handle and drop the
    // guard before touching the stream, instead of holding the map lock.
    streams: Mutex<HashMap<u32, Entry>>,
    /// Counter behind `next_host_id`; only read/written under `streams`.
    next_host: AtomicU32,
    /// When `serve` last saw any inbound frame; the keepalive thread reads it
    /// to decide liveness. Initialised at construction so a peer that never
    /// sends a frame is still declared dead after `KEEPALIVE_TIMEOUT`.
    last_inbound: Mutex<Instant>,
    /// Set when `serve` returns, so the keepalive thread stops instead of
    /// leaking (and pinging a dead connection) once the bridge is gone.
    ended: AtomicBool,
    /// The peer's capabilities, learned from its `Caps` frame (docs/
    /// port-forwarding.md). `None` until one arrives: an older peer never sends
    /// it, so the daemon treats `None` as agent-capable. The host reads it to
    /// know the daemon's caps before opening a forward stream.
    peer_caps: Mutex<Option<u32>>,
    /// Called once with the peer's caps when a `Caps` frame arrives, so the
    /// daemon can wake agent clients held while no agent-capable bridge existed
    /// (a bridge becomes capable only after it advertises `SSH_AGENT`).
    on_caps: Mutex<Option<Box<dyn FnMut(u32) + Send>>>,
    /// Answers inbound `PortQuery`s (the daemon's); `None` leaves them
    /// unanswered.
    port_lookup: Mutex<Option<PortLookup>>,
    /// Accepts host-opened `Open`s (the daemon's); `None` refuses them all.
    host_open: Mutex<Option<HostOpen>>,
    /// Lookups running now, capped at `MAX_PORT_LOOKUPS`.
    port_lookups: AtomicUsize,
    /// Our outstanding `PortQuery`s by id, each waiting in `port_query` for
    /// its `PortInfo`. Cleared when `serve` returns, which wakes the waiters.
    queries: Mutex<HashMap<u32, mpsc::SyncSender<Vec<(u32, String)>>>>,
    next_query: AtomicU32,
}

impl Mux {
    pub fn new(out: impl Write + Send + 'static) -> Arc<Mux> {
        Arc::new(Mux {
            out: Mutex::new(Box::new(out)),
            ctl: Mutex::new(Ctl { queue: VecDeque::new(), writer: false }),
            ctl_cv: Condvar::new(),
            streams: Mutex::new(HashMap::new()),
            next_host: AtomicU32::new(1),
            last_inbound: Mutex::new(Instant::now()),
            ended: AtomicBool::new(false),
            peer_caps: Mutex::new(None),
            on_caps: Mutex::new(None),
            port_lookup: Mutex::new(None),
            host_open: Mutex::new(None),
            port_lookups: AtomicUsize::new(0),
            queries: Mutex::new(HashMap::new()),
            next_query: AtomicU32::new(1),
        })
    }

    /// Register how this side answers the peer's `PortQuery` (the daemon's
    /// `/proc` lookup). Each lookup runs on its own thread, so a slow one never
    /// holds the frame reader.
    #[allow(dead_code)] // used by the daemon (devsbd crate) only
    pub fn on_port_query(&self, lookup: PortLookup) {
        *self.port_lookup.lock().unwrap() = Some(lookup);
    }

    /// Register how this side answers `Open`s with host-allocated ids (the
    /// daemon's `RPC` server). Admitted under the same id policy as `Connect`
    /// (`connect_allowed`); without a handler every one is refused.
    #[allow(dead_code)] // used by the daemon (devsbd crate) only
    pub fn on_host_open(&self, accept: HostOpen) {
        *self.host_open.lock().unwrap() = Some(accept);
    }

    /// Ask the peer (a daemon advertising `caps::PORT_INFO`) who listens on TCP
    /// `port` in the container, waiting up to `timeout`. Queued through
    /// `send_ctl`, so a wedged pipe can't block the caller past `timeout`
    /// either. `TimedOut` when no answer came, `BrokenPipe` when the
    /// connection ended first.
    #[allow(dead_code)] // host forwarder (docs/architecture/daemon/forwards.md)
    pub fn port_query(self: &Arc<Self>, port: u16, timeout: Duration) -> io::Result<Vec<(u32, String)>> {
        let (tx, rx) = mpsc::sync_channel(1);
        let id = self.next_query.fetch_add(1, Ordering::Relaxed);
        self.queries.lock().unwrap().insert(id, tx);
        // After the insert: `serve` sets `ended` before clearing `queries`, so
        // either the clear drops our sender or we see `ended` here.
        let got = if self.ended.load(Ordering::Relaxed) {
            Err(mpsc::RecvTimeoutError::Disconnected)
        } else {
            self.send_ctl(Frame::PortQuery { id, port });
            rx.recv_timeout(timeout)
        };
        self.queries.lock().unwrap().remove(&id);
        match got {
            Ok(procs) => Ok(procs),
            Err(mpsc::RecvTimeoutError::Timeout) => {
                Err(io::Error::new(io::ErrorKind::TimedOut, "no answer to the port query"))
            }
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                Err(io::Error::new(io::ErrorKind::BrokenPipe, "bridge closed"))
            }
        }
    }

    /// An inbound `PortQuery`: run the registered lookup on its own thread
    /// (it reads `/proc`) and send the `PortInfo` back, or drop the query when
    /// there's no lookup or `MAX_PORT_LOOKUPS` already run.
    fn answer_port_query(self: &Arc<Self>, id: u32, port: u16) {
        let Some(lookup) = self.port_lookup.lock().unwrap().clone() else { return };
        let admitted = self
            .port_lookups
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < MAX_PORT_LOOKUPS).then_some(n + 1))
            .is_ok();
        if !admitted {
            return;
        }
        let mux = Arc::clone(self);
        spawn_stream_thread(move || {
            let procs = lookup(port);
            mux.port_lookups.fetch_sub(1, Ordering::AcqRel);
            mux.send_ctl(Frame::PortInfo { id, procs });
        });
    }

    /// The peer's advertised capabilities, or `None` if it never sent `Caps`
    /// (an older peer). The host reads the daemon's caps here after the
    /// handshake to decide whether a forward is possible.
    #[allow(dead_code)] // daemon routing (devsbd); the host reads `Bridge::peer_caps`
    pub fn peer_caps(&self) -> Option<u32> {
        *self.peer_caps.lock().unwrap()
    }

    /// Register a callback run once with the peer's caps when its `Caps` frame
    /// arrives during `serve_with`. The daemon uses it to wake agent clients
    /// held while no agent-capable bridge existed.
    #[allow(dead_code)] // used by the daemon (devsbd crate) only
    pub fn on_caps(&self, f: impl FnMut(u32) + Send + 'static) {
        *self.on_caps.lock().unwrap() = Some(Box::new(f));
    }

    /// Spawn the keepalive thread: send `Ping` every `interval` and, once
    /// `timeout` passes with no inbound frame, call `on_dead` once and stop.
    /// Also stops (without calling `on_dead`) once `serve` has returned, so a
    /// thread never outlives its bridge. `on_dead` typically tears the
    /// connection down (shutdown/kill), which unblocks the `serve` read.
    pub fn keepalive(
        self: &Arc<Self>,
        interval: Duration,
        timeout: Duration,
        on_dead: impl FnOnce() + Send + 'static,
    ) {
        let mux = Arc::clone(self);
        std::thread::spawn(move || {
            let mut on_dead = Some(on_dead);
            while !mux.ended.load(Ordering::Relaxed) {
                std::thread::sleep(interval);
                if mux.ended.load(Ordering::Relaxed) {
                    return;
                }
                let idle = mux.last_inbound.lock().unwrap().elapsed();
                if is_dead(idle, timeout) {
                    if let Some(f) = on_dead.take() {
                        f();
                    }
                    return;
                }
                // `try_lock`: a writer stuck on a wedged peer holds `out`;
                // queuing behind it would park this thread and the silence
                // check above would never fire. Skip this tick's ping instead.
                if let Ok(mut out) = mux.out.try_lock() {
                    let _ = proto::write_frame(&mut *out, &Frame::Ping(Vec::new()));
                }
            }
        });
    }

    pub fn send(&self, frame: &Frame) -> io::Result<()> {
        proto::write_frame(&mut *self.out.lock().unwrap(), frame)
    }

    /// Send `frame` without blocking: queue it for the control writer thread.
    /// The frame reader must never wait on `out`: a pump can hold it while
    /// blocked on a full pipe that only the peer's reader drains, and if the
    /// peer's reader is in the same spot, neither pipe drains again. Any frame
    /// sent from the reader (or from code it calls) goes through here. Identical
    /// queued `Pong`s are coalesced, so a peer flooding `Ping`s while not
    /// reading can't grow the queue without bound.
    fn send_ctl(self: &Arc<Self>, frame: Frame) {
        let mut ctl = self.ctl.lock().unwrap();
        if matches!(frame, Frame::Pong(_)) && ctl.queue.contains(&frame) {
            return;
        }
        ctl.queue.push_back(frame);
        if !ctl.writer {
            ctl.writer = true;
            let mux = Arc::clone(self);
            std::thread::spawn(move || mux.ctl_writer());
        }
        drop(ctl);
        self.ctl_cv.notify_all();
    }

    /// Drain the control queue into `out`. Exits once `serve` has ended and the
    /// queue is empty (frames queued before the end still go out, best effort),
    /// so it never outlives the connection except while stuck in a write, like
    /// any other sender.
    fn ctl_writer(self: Arc<Self>) {
        loop {
            let frame = {
                let mut ctl = self.ctl.lock().unwrap();
                loop {
                    if let Some(frame) = ctl.queue.pop_front() {
                        break frame;
                    }
                    if self.ended.load(Ordering::Relaxed) {
                        ctl.writer = false;
                        return;
                    }
                    ctl = self.ctl_cv.wait(ctl).unwrap();
                }
            };
            let _ = self.send(&frame);
        }
    }

    /// Register `conn` as `stream` and pump its reads into `Data` frames on a
    /// new thread, sending `Close` when it ends (unless the peer closed it
    /// first). With `open`, announces the stream with `Open { channel }` before
    /// any data can flow; on a flowing channel (`channel::flows`) the stream
    /// is flow-controlled, as the peer's end will be.
    pub fn attach(self: &Arc<Self>, stream: u32, conn: impl Into<Conn>, open: Option<u8>) -> io::Result<()> {
        let conn = conn.into();
        if open.is_some_and(proto::channel::flows) {
            return self.attach_flow(stream, conn, open);
        }
        let reader = conn.try_clone()?;
        self.streams.lock().unwrap().insert(stream, Entry::Legacy(Arc::new(conn)));
        if let Some(channel) = open {
            if let Err(e) = self.send(&Frame::Open { stream, channel }) {
                self.streams.lock().unwrap().remove(&stream);
                return Err(e);
            }
        }
        let mux = Arc::clone(self);
        spawn_stream_thread(move || mux.pump(stream, reader));
        Ok(())
    }

    /// `attach` for a flowing channel: registered as a flow stream before
    /// `Open` goes out (so the peer's answer always finds it), threads started
    /// after (so no `Data` precedes the `Open`), like `connect`.
    fn attach_flow(self: &Arc<Self>, stream: u32, conn: Conn, open: Option<u8>) -> io::Result<()> {
        let reader = conn.try_clone()?;
        let flow = Flow::new(None, None);
        self.streams.lock().unwrap().insert(stream, Entry::Flow(Arc::clone(&flow)));
        if let Some(channel) = open {
            if let Err(e) = self.send(&Frame::Open { stream, channel }) {
                self.unregister(stream, &flow);
                return Err(e);
            }
        }
        self.start_flow(stream, &flow, conn, reader);
        Ok(())
    }

    /// Register an accepted peer `Open`'s local end: flow-controlled on a
    /// flowing channel, legacy otherwise. Sends nothing.
    fn accept_open(self: &Arc<Self>, stream: u32, channel: u8, conn: Conn) -> bool {
        if proto::channel::flows(channel) {
            self.attach_flow(stream, conn, None).is_ok()
        } else {
            self.attach(stream, conn, None).is_ok()
        }
    }

    fn pump(&self, stream: u32, mut conn: Conn) {
        let mut buf = vec![0u8; CHUNK];
        loop {
            match conn.read(&mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    if self.send(&Frame::Data { stream, bytes: buf[..n].to_vec() }).is_err() {
                        break;
                    }
                }
            }
        }
        // Still registered = we ended first, so the peer needs to hear it.
        if self.drop_stream(stream) {
            let _ = self.send(&Frame::Close { stream, reason: String::new() });
        }
    }

    /// Unregister and shut down `stream`; `false` when it was already gone.
    fn drop_stream(&self, stream: u32) -> bool {
        let entry = self.streams.lock().unwrap().remove(&stream);
        match entry {
            Some(entry) => {
                entry.end(String::new());
                true
            }
            None => false,
        }
    }

    /// Open a flow-controlled stream to `host:port` on the peer's side (the
    /// daemon dials it inside the container) and relay `conn` over it. Returns
    /// the allocated host id. `on_close` runs once when the stream ends, with
    /// the reason (see [`OnClose`]); it isn't called when this returns `Err`.
    #[allow(dead_code)] // host forwarder (docs/architecture/daemon/forwards.md)
    pub fn connect(
        self: &Arc<Self>,
        conn: impl Into<Conn>,
        host: &str,
        port: u16,
        on_close: impl FnOnce(String) + Send + 'static,
    ) -> io::Result<u32> {
        validate_connect_target(host, port)?;
        let conn = conn.into();
        let reader = conn.try_clone()?;
        let flow = Flow::new(None, Some(Box::new(on_close)));
        let stream = {
            let mut live = self.streams.lock().unwrap();
            let mut next = self.next_host.load(Ordering::Relaxed);
            let id = next_host_id(&mut next, |id| live.contains_key(&id));
            self.next_host.store(next, Ordering::Relaxed);
            live.insert(id, Entry::Flow(Arc::clone(&flow)));
            id
        };
        // Registered before `Connect` goes out, so the peer's answer (Data,
        // Window, Close) always finds the stream; threads start after it, so
        // no `Data` can precede the `Connect`.
        if let Err(e) = self.send(&Frame::Connect { stream, host: host.to_string(), port }) {
            self.unregister(stream, &flow);
            return Err(e);
        }
        self.start_flow(stream, &flow, conn, reader);
        Ok(stream)
    }

    /// Open a flow-controlled stream on flowing `channel` toward the peer (a
    /// daemon that registered `on_host_open`; the host's `RPC` calls), the
    /// sibling of [`connect`](Self::connect): a high-bit id, registered before
    /// the `Open` goes out. Returns the id and the caller's end of a socket
    /// pair whose other end the mux relays: write to send, read until EOF to
    /// receive, `shutdown(Write)` to send `Eof`. `on_close` runs once when the
    /// stream ends (both `Eof`s: empty reason; else the peer's `Close`
    /// reason, ours from [`close_stream`](Self::close_stream), or `"bridge
    /// closed"`); it isn't called when this returns `Err`, which it does for a
    /// legacy channel or a connection already gone.
    #[allow(dead_code)] // host side (`serve::helper`)
    pub fn open_host(
        self: &Arc<Self>,
        channel: u8,
        on_close: impl FnOnce(String) + Send + 'static,
    ) -> io::Result<(u32, Conn)> {
        if !proto::channel::flows(channel) {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("channel {channel} is not a flowing channel")));
        }
        let gone = || io::Error::new(io::ErrorKind::BrokenPipe, "bridge closed");
        if self.ended.load(Ordering::Relaxed) {
            return Err(gone());
        }
        let (ours, theirs) = UnixStream::pair()?;
        let conn = Conn::from(ours);
        let reader = conn.try_clone()?;
        let flow = Flow::new(None, Some(Box::new(on_close)));
        let stream = {
            let mut live = self.streams.lock().unwrap();
            let mut next = self.next_host.load(Ordering::Relaxed);
            let id = next_host_id(&mut next, |id| live.contains_key(&id));
            self.next_host.store(next, Ordering::Relaxed);
            live.insert(id, Entry::Flow(Arc::clone(&flow)));
            id
        };
        // `serve` sets `ended` before `close_all`: past the insert, either we
        // see it here or `close_all` drains (and reports) our entry.
        if self.ended.load(Ordering::Relaxed) && self.unregister(stream, &flow) {
            return Err(gone());
        }
        if let Err(e) = self.send(&Frame::Open { stream, channel }) {
            if self.unregister(stream, &flow) {
                return Err(e);
            }
        }
        self.start_flow(stream, &flow, conn, reader);
        Ok((stream, Conn::from(theirs)))
    }

    /// End flow-controlled `stream` from this side: unregister it, shut its
    /// local socket (the caller's end then reads EOF), run its `on_close`
    /// with `reason`, and send the peer `Close { reason }`. How a host
    /// cancels an `RPC` call. `false` when the stream is already gone (or is
    /// legacy).
    #[allow(dead_code)] // host side (`serve::helper`)
    pub fn close_stream(self: &Arc<Self>, stream: u32, reason: &str) -> bool {
        let Some(flow) = self.flow(stream) else { return false };
        let live = self.unregister(stream, &flow);
        if live {
            flow.end(reason.to_string());
            self.send_ctl(Frame::Close { stream, reason: reason.to_string() });
        }
        live
    }

    /// Settle a pending inbound `Connect`. A stream that was closed (or whose
    /// id was replaced) while the dial ran is no longer registered: the late
    /// socket is dropped silently, the peer already knows the stream is gone.
    fn complete_connect(self: &Arc<Self>, stream: u32, flow: &Arc<Flow>, result: Result<Conn, String>) {
        match result.and_then(|conn| {
            let reader = conn.try_clone().map_err(|e| format!("clone socket: {e}"))?;
            Ok((conn, reader))
        }) {
            Ok((conn, reader)) => self.start_flow(stream, flow, conn, reader),
            Err(reason) => self.close_flow(stream, flow, reason),
        }
    }

    /// Attach the local socket to a registered flow stream and start its
    /// writer and pump. Checked under the flow lock against `closed`, so a
    /// `Close` racing the attach either sees the socket (and shuts it) or makes
    /// us drop it here — never a socket with no owner.
    fn start_flow(self: &Arc<Self>, stream: u32, flow: &Arc<Flow>, conn: Conn, reader: Conn) {
        let conn = Arc::new(conn);
        {
            let mut st = flow.state.lock().unwrap();
            if st.closed {
                return;
            }
            st.conn = Some(Arc::clone(&conn));
        }
        // Data queued before the attach needs no wake-up: the writer checks
        // the queue before its first wait.
        let (mux, f) = (Arc::clone(self), Arc::clone(flow));
        spawn_stream_thread(move || mux.flow_writer(stream, f, conn));
        let (mux, f) = (Arc::clone(self), Arc::clone(flow));
        spawn_stream_thread(move || mux.flow_pump(stream, f, reader));
    }

    /// Local socket -> `Data`, never more than the peer granted: reads at most
    /// `min(CHUNK, credit)` and parks on the condvar at zero credit. Local EOF
    /// sends `Eof` (after all our `Data`, same thread) and stops this
    /// direction only; the other keeps flowing until the peer's `Eof`.
    fn flow_pump(self: Arc<Self>, stream: u32, flow: Arc<Flow>, mut conn: Conn) {
        let mut buf = vec![0u8; CHUNK];
        loop {
            let want = {
                let mut st = flow.state.lock().unwrap();
                loop {
                    if st.closed {
                        return;
                    }
                    if st.send_credit > 0 {
                        break (st.send_credit as usize).min(CHUNK);
                    }
                    st = flow.cv.wait(st).unwrap();
                }
            };
            match conn.read(&mut buf[..want]) {
                Ok(0) => {
                    if flow.state.lock().unwrap().closed || self.send(&Frame::Eof { stream }).is_err() {
                        return;
                    }
                    let ready = {
                        let mut st = flow.state.lock().unwrap();
                        st.eof_sent = true;
                        !st.closed && teardown_ready(st.eof_sent, st.eof_received, st.drained)
                    };
                    if ready {
                        self.finish_flow(stream, &flow);
                    }
                    return;
                }
                Ok(n) => {
                    {
                        let mut st = flow.state.lock().unwrap();
                        if st.closed {
                            return;
                        }
                        // Only this thread spends credit, and `n <= want <= credit`.
                        st.send_credit -= n as u32;
                    }
                    if self.send(&Frame::Data { stream, bytes: buf[..n].to_vec() }).is_err() {
                        return;
                    }
                }
                Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => {
                    self.close_flow(stream, &flow, format!("read: {e}"));
                    return;
                }
            }
        }
    }

    /// Queue -> local socket, off the frame-reader thread: a slow local reader
    /// only backs up this stream's queue (bounded by the window). Credit goes
    /// back once bytes are actually written, batched by `should_grant`. After
    /// the peer's `Eof` and an empty queue, shuts the local write side down.
    fn flow_writer(self: Arc<Self>, stream: u32, flow: Arc<Flow>, conn: Arc<Conn>) {
        loop {
            let next = {
                let mut st = flow.state.lock().unwrap();
                loop {
                    if st.closed {
                        return;
                    }
                    if let Some(bytes) = st.queue.pop_front() {
                        break Some(bytes);
                    }
                    if st.eof_received {
                        break None;
                    }
                    st = flow.cv.wait(st).unwrap();
                }
            };
            let Some(bytes) = next else {
                let _ = conn.shutdown(Shutdown::Write);
                let ready = {
                    let mut st = flow.state.lock().unwrap();
                    st.drained = true;
                    !st.closed && teardown_ready(st.eof_sent, st.eof_received, st.drained)
                };
                if ready {
                    self.finish_flow(stream, &flow);
                }
                return;
            };
            if let Err(e) = (&*conn).write_all(&bytes) {
                self.close_flow(stream, &flow, format!("write: {e}"));
                return;
            }
            let grant = {
                let mut st = flow.state.lock().unwrap();
                if st.closed {
                    return;
                }
                st.ungranted += bytes.len() as u32;
                // After the peer's `Eof` it sends nothing more: no point granting.
                (should_grant(st.ungranted) && !st.eof_received).then(|| {
                    let credit = std::mem::take(&mut st.ungranted);
                    st.recv_credit += credit;
                    credit
                })
            };
            if let Some(credit) = grant {
                let _ = self.send(&Frame::Window { stream, credit });
            }
        }
    }

    /// Remove `stream` from the map only if it still maps to `flow` (the id may
    /// have been closed and reused meanwhile).
    fn unregister(&self, stream: u32, flow: &Arc<Flow>) -> bool {
        let mut live = self.streams.lock().unwrap();
        match live.get(&stream) {
            Some(Entry::Flow(f)) if Arc::ptr_eq(f, flow) => {
                live.remove(&stream);
                true
            }
            _ => false,
        }
    }

    /// We end the stream: tear down and tell the peer why (`Close { reason }`).
    /// A no-op when it's already gone (peer `Close`, teardown, mux end). The
    /// `Close` goes through `send_ctl` because the reader calls this (credit
    /// overrun, an inline `ConnectReply`); order still holds for pump/writer
    /// callers, since every `Data` they sent was written before they got here.
    fn close_flow(self: &Arc<Self>, stream: u32, flow: &Arc<Flow>, reason: String) {
        if self.unregister(stream, flow) {
            flow.end(reason.clone());
            self.send_ctl(Frame::Close { stream, reason });
        }
    }

    /// Clean end after both `Eof`s: each side reaches this on its own, so no
    /// `Close` is sent.
    fn finish_flow(&self, stream: u32, flow: &Arc<Flow>) {
        if self.unregister(stream, flow) {
            flow.end(String::new());
        }
    }

    fn flow(&self, stream: u32) -> Option<Arc<Flow>> {
        match self.streams.lock().unwrap().get(&stream) {
            Some(Entry::Flow(f)) => Some(Arc::clone(f)),
            _ => None,
        }
    }

    /// `serve_with` for a peer that never accepts `Connect` (the host side):
    /// each one is refused with `Close`.
    #[allow(dead_code)] // devsbd only uses `serve_with`
    pub fn serve(self: &Arc<Self>, reader: impl Read, on_open: impl Fn(u32, u8) -> Option<Conn>) {
        self.serve_with(reader, on_open, |_, _, _, reply: ConnectReply| {
            reply.finish(Err("port forwarding not accepted by this peer".into()))
        });
    }

    /// Route frames from `reader` until it ends: `Data` to its stream,
    /// `Close` shuts it, `Ping` gets a `Pong`, and `Open` asks `on_open` for a
    /// local connection (`None` refuses the stream with `Close`), or the
    /// `on_host_open` handler for a host-allocated id. `Connect`
    /// registers a pending flow stream (so `Data` racing the dial is queued,
    /// bounded by credit) and hands a [`ConnectReply`] to `on_connect`, which
    /// must return at once and dial elsewhere. This thread never blocks on a
    /// flow stream's local socket, nor on `out` (its replies go through
    /// `send_ctl`), which keeps the pipe draining and `last_inbound` truthful
    /// for the keepalive. It still runs `on_open`, `on_connect` and `on_close`
    /// callbacks inline: they must be quick. Every stream is shut down on
    /// return, since the peer can no longer see it.
    pub fn serve_with(
        self: &Arc<Self>,
        mut reader: impl Read,
        on_open: impl Fn(u32, u8) -> Option<Conn>,
        on_connect: impl Fn(u32, String, u16, ConnectReply),
    ) {
        while let Ok(Some(frame)) = proto::read_frame(&mut reader) {
            *self.last_inbound.lock().unwrap() = Instant::now();
            match frame {
                Frame::Data { stream, bytes } => {
                    let conn = match self.streams.lock().unwrap().get(&stream) {
                        Some(Entry::Legacy(conn)) => Ok(Arc::clone(conn)),
                        Some(Entry::Flow(flow)) => Err(Arc::clone(flow)),
                        // Raced a local close; its `Close` is already on the way.
                        None => continue,
                    };
                    match conn {
                        // Legacy: write inline, after dropping the guard, so a
                        // slow local socket can't stall other streams' routing.
                        Ok(conn) => {
                            if (&*conn).write_all(&bytes).is_err() && self.drop_stream(stream) {
                                self.send_ctl(Frame::Close { stream, reason: String::new() });
                            }
                        }
                        Err(flow) => self.queue_data(stream, &flow, bytes),
                    }
                }
                Frame::Window { stream, credit } => {
                    if let Some(flow) = self.flow(stream) {
                        let mut st = flow.state.lock().unwrap();
                        st.send_credit = st.send_credit.saturating_add(credit);
                        drop(st);
                        flow.cv.notify_all();
                    }
                }
                Frame::Eof { stream } => {
                    let entry = match self.streams.lock().unwrap().get(&stream) {
                        Some(Entry::Legacy(conn)) => Ok(Arc::clone(conn)),
                        Some(Entry::Flow(flow)) => Err(Arc::clone(flow)),
                        None => continue,
                    };
                    match entry {
                        // Legacy half-close: the request is complete, the
                        // reply direction stays open (see the module doc).
                        Ok(conn) => {
                            let _ = conn.shutdown(Shutdown::Write);
                        }
                        Err(flow) => {
                            flow.state.lock().unwrap().eof_received = true;
                            flow.cv.notify_all();
                        }
                    }
                }
                Frame::Close { stream, reason } => {
                    let entry = self.streams.lock().unwrap().remove(&stream);
                    if let Some(entry) = entry {
                        entry.end(reason);
                    }
                }
                Frame::Ping(payload) => self.send_ctl(Frame::Pong(payload)),
                Frame::Open { stream, channel } => {
                    // Host-side policy for peer-allocated stream ids. The
                    // high bit is reserved for host-allocated ids, so a peer
                    // `Open` must have it clear; refuse a duplicate id or one
                    // past the stream cap (counting peer-allocated streams
                    // only, so forwarded connections can't crowd out the
                    // agent). Sending `Close` for a duplicate makes a
                    // misbehaving peer drop its *existing* stream with that
                    // id — acceptable, since only a broken or hostile peer
                    // reuses a live id. The daemon side passes
                    // `on_open = |_,_| None` and never reaches that path.
                    //
                    // A high-bit id is a host-opened stream: admitted only
                    // with an `on_host_open` handler (the daemon's), under
                    // `Connect`'s policy and cap.
                    let host_open = self.host_open.lock().unwrap().clone();
                    let attached = {
                        let live = self.streams.lock().unwrap();
                        let allowed = if stream & HOST_ID_BIT == 0 {
                            let peer_streams = live.keys().filter(|&&id| id & HOST_ID_BIT == 0).count();
                            !live.contains_key(&stream) && peer_streams < MAX_STREAMS
                        } else {
                            let host_streams = live.keys().filter(|&&id| id & HOST_ID_BIT != 0).count();
                            host_open.is_some() && connect_allowed(stream, live.contains_key(&stream), host_streams)
                        };
                        drop(live);
                        let conn = match &host_open {
                            _ if !allowed => None,
                            Some(accept) if stream & HOST_ID_BIT != 0 => accept(stream, channel),
                            _ => on_open(stream, channel),
                        };
                        conn.is_some_and(|conn| self.accept_open(stream, channel, conn))
                    };
                    if !attached {
                        self.send_ctl(Frame::Close { stream, reason: String::new() });
                    }
                }
                Frame::Connect { stream, host, port } => {
                    // Same duplicate caveat as `Open`: refusing a live id makes
                    // the peer drop its own stream with it.
                    let flow = {
                        let mut live = self.streams.lock().unwrap();
                        let host_streams = live.keys().filter(|&&id| id & HOST_ID_BIT != 0).count();
                        connect_allowed(stream, live.contains_key(&stream), host_streams).then(|| {
                            let flow = Flow::new(None, None);
                            live.insert(stream, Entry::Flow(Arc::clone(&flow)));
                            flow
                        })
                    };
                    match flow {
                        Some(flow) => {
                            on_connect(stream, host, port, ConnectReply { mux: Arc::clone(self), stream, flow: Some(flow) })
                        }
                        None => self.send_ctl(Frame::Close { stream, reason: "stream refused".into() }),
                    }
                }
                // The peer's capabilities (docs/architecture/helper/protocol.md): record them
                // and wake anything waiting on them (the daemon's held agent
                // clients). Arrives once on stream 0 right after the handshake.
                Frame::Caps(c) => {
                    *self.peer_caps.lock().unwrap() = Some(c);
                    if let Some(f) = self.on_caps.lock().unwrap().as_mut() {
                        f(c);
                    }
                }
                // `Quit` only means something as a control socket's first
                // frame, which the daemon reads before handing over to `serve`.
                Frame::PortQuery { id, port } => self.answer_port_query(id, port),
                // A late answer (its query timed out) finds no waiter: dropped.
                Frame::PortInfo { id, procs } => {
                    if let Some(tx) = self.queries.lock().unwrap().remove(&id) {
                        let _ = tx.try_send(procs);
                    }
                }
                Frame::Hello { .. } | Frame::Pong(_) | Frame::Quit => {}
            }
        }
        self.ended.store(true, Ordering::Relaxed);
        // Wakes every `port_query` waiter (its sender is dropped).
        self.queries.lock().unwrap().clear();
        // Taking the lock orders this after a writer's `ended` check, so its
        // wait can't miss the wake-up.
        drop(self.ctl.lock().unwrap());
        self.ctl_cv.notify_all();
        self.close_all();
    }

    /// Enqueue inbound `Data` for a flow stream's writer, or close the stream
    /// if the peer overran its credit. Never blocks: the queue is bounded by
    /// the credit we granted.
    fn queue_data(self: &Arc<Self>, stream: u32, flow: &Arc<Flow>, bytes: Vec<u8>) {
        let verdict = {
            let mut st = flow.state.lock().unwrap();
            if st.closed {
                return;
            }
            let verdict = check_data(bytes.len(), st.recv_credit, st.eof_received);
            if verdict.is_ok() {
                st.recv_credit -= bytes.len() as u32;
                st.queue.push_back(bytes);
            }
            verdict
        };
        match verdict {
            Ok(()) => flow.cv.notify_all(),
            Err(reason) => self.close_flow(stream, flow, reason.to_string()),
        }
    }

    /// Tear down every stream (the connection is gone): shuts local sockets,
    /// wakes and stops every flow thread, reports `"bridge closed"`.
    pub fn close_all(&self) {
        let entries: Vec<Entry> = self.streams.lock().unwrap().drain().map(|(_, e)| e).collect();
        for entry in entries {
            entry.end("bridge closed".into());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proto::channel;
    use std::io::{BufRead, BufReader};
    use std::time::Duration;

    /// Fake agent: answers each line with `re:<line>`.
    fn echo_agent(conn: UnixStream) {
        std::thread::spawn(move || {
            let mut w = conn.try_clone().unwrap();
            for line in BufReader::new(conn).lines() {
                let Ok(line) = line else { break };
                if writeln!(w, "re:{line}").is_err() {
                    break;
                }
            }
        });
    }

    /// A daemon-side mux and a host-side mux joined by OS pipes, the host
    /// connecting each `Open` to a fresh echo agent.
    fn pair() -> Arc<Mux> {
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        let host = Mux::new(h_w);
        let d = Arc::clone(&daemon);
        std::thread::spawn(move || d.serve(d_r, |_, _| None));
        std::thread::spawn(move || {
            host.serve(h_r, |_, ch| {
                (ch == channel::SSH_AGENT).then(|| {
                    let (ours, agent) = UnixStream::pair().unwrap();
                    echo_agent(agent);
                    ours.into()
                })
            })
        });
        daemon
    }

    fn client(daemon: &Arc<Mux>, stream: u32, channel: u8) -> BufReader<UnixStream> {
        let (ours, theirs) = UnixStream::pair().unwrap();
        daemon.attach(stream, theirs, Some(channel)).unwrap();
        ours.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        BufReader::new(ours)
    }

    #[test]
    fn streams_relay_independently() {
        let daemon = pair();
        let mut a = client(&daemon, 1, channel::SSH_AGENT);
        let mut b = client(&daemon, 2, channel::SSH_AGENT);
        let roundtrip = |c: &mut BufReader<UnixStream>, msg: &str| {
            writeln!(c.get_mut(), "{msg}").unwrap();
            let mut line = String::new();
            c.read_line(&mut line).unwrap();
            assert_eq!(line, format!("re:{msg}\n"));
        };
        roundtrip(&mut a, "one");
        roundtrip(&mut b, "two");
        roundtrip(&mut a, "three");
    }

    /// Same relay as `streams_relay_independently`, but with TCP on both local
    /// ends: the daemon attaches a loopback client, the host's `on_open` dials a
    /// loopback echo server. Exercises every `Conn::Tcp` arm.
    #[test]
    fn tcp_conns_relay_through_the_mux() {
        use std::net::{TcpListener, TcpStream};
        let echo = TcpListener::bind("127.0.0.1:0").unwrap();
        let echo_addr = echo.local_addr().unwrap();
        std::thread::spawn(move || {
            for conn in echo.incoming() {
                let conn = conn.unwrap();
                std::thread::spawn(move || {
                    let mut w = conn.try_clone().unwrap();
                    for line in BufReader::new(conn).lines() {
                        let Ok(line) = line else { break };
                        if writeln!(w, "re:{line}").is_err() {
                            break;
                        }
                    }
                });
            }
        });

        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        let host = Mux::new(h_w);
        let d = Arc::clone(&daemon);
        std::thread::spawn(move || d.serve(d_r, |_, _| None));
        std::thread::spawn(move || host.serve(h_r, |_, _| TcpStream::connect(echo_addr).ok().map(Into::into)));

        let front = TcpListener::bind("127.0.0.1:0").unwrap();
        let ours = TcpStream::connect(front.local_addr().unwrap()).unwrap();
        let (theirs, _) = front.accept().unwrap();
        daemon.attach(1, theirs, Some(channel::SSH_AGENT)).unwrap();
        ours.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        let mut c = BufReader::new(ours);
        for msg in ["one", "two"] {
            writeln!(c.get_mut(), "{msg}").unwrap();
            let mut line = String::new();
            c.read_line(&mut line).unwrap();
            assert_eq!(line, format!("re:{msg}\n"));
        }
    }

    #[test]
    fn refused_open_closes_the_client() {
        let daemon = pair();
        // Host only serves SSH_AGENT: any other channel is refused.
        let mut c = client(&daemon, 1, channel::HTTP_PROXY);
        let mut buf = String::new();
        assert_eq!(c.read_line(&mut buf).unwrap(), 0, "EOF after refusal");
        assert!(daemon.streams.lock().unwrap().is_empty());
    }

    #[test]
    fn client_close_is_forwarded_and_unregistered() {
        let daemon = pair();
        let c = client(&daemon, 1, channel::SSH_AGENT);
        drop(c);
        for _ in 0..100 {
            if daemon.streams.lock().unwrap().is_empty() {
                return;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        panic!("stream still registered after client closed");
    }

    /// Legacy half-close: a request sent as `Data` + `Eof` reaches the host's
    /// local end as bytes then EOF, and the reply still flows back — the notify
    /// exchange (the local-EOF path would send `Close` and lose the reply).
    #[test]
    fn eof_half_closes_a_legacy_stream_and_the_reply_flows_back() {
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        let host = Mux::new(h_w);
        let d = Arc::clone(&daemon);
        std::thread::spawn(move || d.serve(d_r, |_, _| None));
        std::thread::spawn(move || {
            host.serve(h_r, |_, _| {
                let (ours, mut handler) = UnixStream::pair().unwrap();
                std::thread::spawn(move || {
                    let mut req = Vec::new();
                    handler.read_to_end(&mut req).unwrap();
                    handler.write_all(format!("got {}", req.len()).as_bytes()).unwrap();
                });
                Some(ours.into())
            })
        });
        let (mut ours, theirs) = UnixStream::pair().unwrap();
        ours.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        daemon.attach(1, theirs, Some(channel::NOTIFY)).unwrap();
        daemon.send(&Frame::Data { stream: 1, bytes: b"hello".to_vec() }).unwrap();
        daemon.send(&Frame::Eof { stream: 1 }).unwrap();
        let mut reply = String::new();
        ours.read_to_string(&mut reply).unwrap();
        assert_eq!(reply, "got 5");
    }

    #[test]
    fn peer_loss_shuts_every_stream() {
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (_h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        let mut c = client(&daemon, 1, channel::SSH_AGENT);
        drop(h_w); // host went away
        daemon.serve(d_r, |_, _| None);
        let mut buf = String::new();
        assert_eq!(c.read_line(&mut buf).unwrap(), 0);
    }

    /// Reader-sent frames go out on the control writer thread; once `serve`
    /// has returned, wait for it to flush them and exit before inspecting `out`.
    fn wait_ctl_drained(mux: &Mux) {
        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            let ctl = mux.ctl.lock().unwrap();
            if ctl.queue.is_empty() && !ctl.writer {
                return;
            }
            drop(ctl);
            assert!(Instant::now() < deadline, "control writer never drained");
            std::thread::sleep(Duration::from_millis(1));
        }
    }

    /// A `Write` that appends to a shared buffer, so a test can read back the
    /// frames a `Mux` emitted on its `out` side.
    #[derive(Clone)]
    struct Sink(Arc<Mutex<Vec<u8>>>);
    impl Write for Sink {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// Drive a host-side `Mux::serve` with `opens`, always granting a live
    /// socket, and return the stream ids it refused with `Close`.
    fn refused_opens(opens: &[u32]) -> Vec<u32> {
        let mut wire = Vec::new();
        for &stream in opens {
            proto::write_frame(&mut wire, &Frame::Open { stream, channel: channel::SSH_AGENT }).unwrap();
        }
        let out = Arc::new(Mutex::new(Vec::new()));
        let mux = Mux::new(Sink(Arc::clone(&out)));
        // Grant every Open a fresh socket; the policy inside `serve` decides.
        // Retain each peer end so an accepted stream's pump never sees EOF and
        // emits its own `Close` — only the policy's refusals reach `out`.
        let peers = Mutex::new(Vec::new());
        mux.serve(io::Cursor::new(wire), |_, _| {
            let (ours, theirs) = UnixStream::pair().unwrap();
            peers.lock().unwrap().push(theirs);
            Some(ours.into())
        });
        wait_ctl_drained(&mux);
        let mut r = io::Cursor::new(std::mem::take(&mut *out.lock().unwrap()));
        let mut closed = Vec::new();
        while let Ok(Some(frame)) = proto::read_frame(&mut r) {
            if let Frame::Close { stream, .. } = frame {
                closed.push(stream);
            }
        }
        closed
    }

    #[test]
    fn is_dead_fires_only_after_the_timeout() {
        let timeout = Duration::from_secs(45);
        assert!(!is_dead(Duration::from_secs(0), timeout));
        assert!(!is_dead(Duration::from_secs(44), timeout));
        // The window is inclusive at the boundary.
        assert!(is_dead(Duration::from_secs(45), timeout));
        assert!(is_dead(Duration::from_secs(90), timeout));
    }

    #[test]
    fn keepalive_calls_on_dead_when_peer_stops_answering() {
        // A live peer that reads our frames but never replies: inbound stays
        // silent, so `on_dead` fires once the tiny timeout elapses.
        let (mux_r, peer_w) = std::io::pipe().unwrap();
        let (peer_r, mux_w) = std::io::pipe().unwrap();
        let mux = Mux::new(mux_w);
        // Drain the peer's read end so our `Ping`s never block on a full pipe.
        std::thread::spawn(move || {
            let mut sink = peer_r;
            let mut buf = [0u8; 256];
            while let Ok(n) = sink.read(&mut buf) {
                if n == 0 {
                    break;
                }
            }
        });
        let (tx, rx) = std::sync::mpsc::channel();
        mux.keepalive(Duration::from_millis(5), Duration::from_millis(30), move || {
            let _ = tx.send(());
        });
        let m = Arc::clone(&mux);
        std::thread::spawn(move || m.serve(mux_r, |_, _| None));
        rx.recv_timeout(Duration::from_secs(2)).expect("on_dead fired");
        // Keep the peer's write end alive until on_dead so `serve` doesn't end
        // (and set `ended`) before liveness is judged.
        drop(peer_w);
    }

    #[test]
    fn keepalive_stops_once_serve_returns_without_calling_on_dead() {
        let (mux_r, peer_w) = std::io::pipe().unwrap();
        let (_peer_r, mux_w) = std::io::pipe().unwrap();
        let mux = Mux::new(mux_w);
        let fired = Arc::new(AtomicBool::new(false));
        let f = Arc::clone(&fired);
        mux.keepalive(Duration::from_millis(5), Duration::from_secs(30), move || {
            f.store(true, Ordering::Relaxed);
        });
        // Peer vanishes: `serve` returns and flips `ended`.
        drop(peer_w);
        mux.serve(mux_r, |_, _| None);
        std::thread::sleep(Duration::from_millis(40));
        assert!(!fired.load(Ordering::Relaxed), "on_dead must not fire after serve ended");
    }

    #[test]
    fn open_with_high_bit_is_refused() {
        assert_eq!(refused_opens(&[HOST_ID_BIT, HOST_ID_BIT | 5]), vec![HOST_ID_BIT, HOST_ID_BIT | 5]);
    }

    #[test]
    fn duplicate_open_id_is_refused() {
        // First Open for id 1 is accepted (no Close), the second refused.
        assert_eq!(refused_opens(&[1, 1]), vec![1]);
    }

    #[test]
    fn opens_past_the_stream_cap_are_refused() {
        // 1..=MAX_STREAMS accepted, then two more refused.
        let opens: Vec<u32> = (1..=(MAX_STREAMS as u32 + 2)).collect();
        let over = vec![MAX_STREAMS as u32 + 1, MAX_STREAMS as u32 + 2];
        assert_eq!(refused_opens(&opens), over);
    }

    // ---- flow-controlled (`Connect`) streams ----

    use std::sync::mpsc;

    #[test]
    fn grant_rule_batches_to_half_a_window() {
        assert!(!should_grant(0));
        assert!(!should_grant(INITIAL_WINDOW / 2 - 1));
        assert!(should_grant(INITIAL_WINDOW / 2));
        assert!(should_grant(INITIAL_WINDOW));
    }

    #[test]
    fn data_admission_enforces_credit_and_eof() {
        assert_eq!(check_data(10, 10, false), Ok(()), "exactly the credit is fine");
        assert_eq!(check_data(0, 0, false), Ok(()));
        assert_eq!(check_data(11, 10, false), Err(FLOW_VIOLATION));
        assert_eq!(check_data(1, 10, true), Err("data after eof"));
    }

    #[test]
    fn teardown_needs_both_eofs_and_a_drained_queue() {
        assert!(teardown_ready(true, true, true));
        for (sent, received, drained) in [(false, true, true), (true, false, true), (true, true, false), (false, false, false)] {
            assert!(!teardown_ready(sent, received, drained), "{sent} {received} {drained}");
        }
    }

    #[test]
    fn connect_id_rule() {
        assert!(connect_allowed(HOST_ID_BIT | 1, false, 0));
        assert!(!connect_allowed(1, false, 0), "daemon id space");
        assert!(!connect_allowed(HOST_ID_BIT | 1, true, 0), "live id");
        assert!(connect_allowed(HOST_ID_BIT | 1, false, MAX_HOST_STREAMS - 1));
        assert!(!connect_allowed(HOST_ID_BIT | 1, false, MAX_HOST_STREAMS), "cap");
    }

    #[test]
    fn host_ids_are_monotonic_skip_live_and_wrap() {
        let mut next = 1;
        assert_eq!(next_host_id(&mut next, |_| false), HOST_ID_BIT | 1);
        assert_eq!(next_host_id(&mut next, |_| false), HOST_ID_BIT | 2);
        assert_eq!(next_host_id(&mut next, |id| id == HOST_ID_BIT | 3), HOST_ID_BIT | 4);
        // A freed id is not handed out again right away.
        assert_eq!(next_host_id(&mut next, |_| false), HOST_ID_BIT | 5);
        let mut next = HOST_ID_BIT - 1;
        assert_eq!(next_host_id(&mut next, |_| false), u32::MAX);
        assert_eq!(next_host_id(&mut next, |_| false), HOST_ID_BIT | 1, "wraps to 1, never HOST_ID_BIT | 0");
    }

    #[test]
    fn connect_rejects_bad_targets_before_the_wire() {
        let out = Arc::new(Mutex::new(Vec::new()));
        let mux = Mux::new(Sink(Arc::clone(&out)));
        let long = "h".repeat(256);
        for (host, port) in [("", 80), (long.as_str(), 80), ("db", 0)] {
            let (a, _b) = UnixStream::pair().unwrap();
            let err = mux.connect(a, host, port, |_| {}).unwrap_err();
            assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{host:?}:{port}");
        }
        assert!(out.lock().unwrap().is_empty());
        assert!(mux.streams.lock().unwrap().is_empty());
        // 255 bytes is the most one length byte can carry.
        let (a, _b) = UnixStream::pair().unwrap();
        mux.connect(a, &"h".repeat(255), 80, |_| {}).unwrap();
    }

    /// Host and daemon muxes over OS pipes; the daemon settles each `Connect`
    /// with `dial`, inline (standing in for the daemon's dial thread).
    fn flow_pair_with(dial: impl Fn(&str, u16) -> Result<Conn, String> + Send + 'static) -> (Arc<Mux>, Arc<Mux>) {
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        let host = Mux::new(h_w);
        let d = Arc::clone(&daemon);
        std::thread::spawn(move || d.serve_with(d_r, |_, _| None, move |_, h, p, reply| reply.finish(dial(&h, p))));
        let h = Arc::clone(&host);
        std::thread::spawn(move || h.serve(h_r, |_, _| None));
        (host, daemon)
    }

    struct Flows {
        host: Arc<Mux>,
        daemon: Arc<Mux>,
        /// The "container" end of each dialed stream, in `Connect` order.
        servers: mpsc::Receiver<UnixStream>,
    }

    fn flow_pair() -> Flows {
        let (tx, servers) = mpsc::channel();
        let (host, daemon) = flow_pair_with(move |_, _| {
            let (ours, theirs) = UnixStream::pair().map_err(|e| e.to_string())?;
            tx.send(theirs).unwrap();
            Ok(ours.into())
        });
        Flows { host, daemon, servers }
    }

    /// Forward one stream: (client end on the host, server end in the
    /// container, host id, the host's `on_close` reasons).
    fn open(f: &Flows) -> (UnixStream, UnixStream, u32, mpsc::Receiver<String>) {
        let (client, theirs) = UnixStream::pair().unwrap();
        let (tx, closed) = mpsc::channel();
        let id = f
            .host
            .connect(theirs, "svc", 80, move |reason| {
                let _ = tx.send(reason);
            })
            .unwrap();
        let server = f.servers.recv_timeout(Duration::from_secs(10)).unwrap();
        for s in [&client, &server] {
            s.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
            s.set_write_timeout(Some(Duration::from_secs(30))).unwrap();
        }
        (client, server, id, closed)
    }

    fn wait_until(what: &str, mut cond: impl FnMut() -> bool) {
        let deadline = Instant::now() + Duration::from_secs(10);
        while !cond() {
            assert!(Instant::now() < deadline, "timed out waiting for {what}");
            std::thread::sleep(Duration::from_millis(5));
        }
    }

    fn both_unregistered(f: &Flows) -> bool {
        f.host.streams.lock().unwrap().is_empty() && f.daemon.streams.lock().unwrap().is_empty()
    }

    /// Deterministic, non-repeating-per-chunk byte pattern.
    fn pat(i: usize) -> u8 {
        (i ^ (i >> 8) ^ (i >> 17)).wrapping_mul(31) as u8
    }

    fn write_pattern(mut w: impl Write, n: usize) -> io::Result<()> {
        let mut buf = vec![0u8; 64 * 1024];
        let mut off = 0;
        while off < n {
            let len = buf.len().min(n - off);
            for (j, b) in buf[..len].iter_mut().enumerate() {
                *b = pat(off + j);
            }
            w.write_all(&buf[..len])?;
            off += len;
        }
        Ok(())
    }

    /// Read to EOF, checking every byte against `pat`; returns the count.
    fn read_check(mut r: impl Read) -> usize {
        let mut buf = vec![0u8; 64 * 1024];
        let mut off = 0;
        loop {
            let n = r.read(&mut buf).unwrap();
            if n == 0 {
                return off;
            }
            for (j, &b) in buf[..n].iter().enumerate() {
                assert_eq!(b, pat(off + j), "byte {} differs", off + j);
            }
            off += n;
        }
    }

    #[test]
    fn bulk_transfer_is_byte_identical_both_ways() {
        const N: usize = 64 << 20;
        let f = flow_pair();
        let (client, server, _, closed) = open(&f);
        let (cw, sw) = (client.try_clone().unwrap(), server.try_clone().unwrap());
        let up = std::thread::spawn(move || {
            write_pattern(&cw, N).unwrap();
            cw.shutdown(Shutdown::Write).unwrap();
        });
        let down = std::thread::spawn(move || {
            write_pattern(&sw, N).unwrap();
            sw.shutdown(Shutdown::Write).unwrap();
        });
        let received_up = std::thread::spawn(move || read_check(&server));
        assert_eq!(read_check(&client), N);
        assert_eq!(received_up.join().unwrap(), N);
        up.join().unwrap();
        down.join().unwrap();
        // Both directions hit EOF: a clean teardown on both sides, no Close.
        assert_eq!(closed.recv_timeout(Duration::from_secs(10)).unwrap(), "");
        wait_until("both sides to unregister", || both_unregistered(&f));
    }

    /// Regression: the frame reader used to write `Pong`/`Close` inline on
    /// `out`. With bulk traffic both ways, each side's pump could hold `out`
    /// while blocked on a full pipe that only the *other* side's reader drains,
    /// and that reader was itself waiting on its own `out` to send a `Pong`: a
    /// cycle. 1 ms pings on both sides make the collision near-certain; the
    /// keepalive timeout sits past the test bound, so a hang shows up as a
    /// timeout here rather than as `on_dead`.
    #[test]
    fn bidirectional_bulk_with_pings_does_not_deadlock() {
        const N: usize = 32 << 20;
        const STREAMS: usize = 8;
        let f = flow_pair();
        let fired = Arc::new(AtomicBool::new(false));
        for mux in [&f.host, &f.daemon] {
            let fired = Arc::clone(&fired);
            mux.keepalive(Duration::from_millis(1), Duration::from_secs(60), move || {
                fired.store(true, Ordering::Relaxed);
            });
        }
        let (done_tx, done) = mpsc::channel();
        for _ in 0..STREAMS {
            let (client, server, _, _) = open(&f);
            let done_tx = done_tx.clone();
            std::thread::spawn(move || {
                let (cw, sw) = (client.try_clone().unwrap(), server.try_clone().unwrap());
                std::thread::spawn(move || {
                    let _ = write_pattern(&cw, N).and_then(|_| cw.shutdown(Shutdown::Write));
                });
                std::thread::spawn(move || {
                    let _ = write_pattern(&sw, N).and_then(|_| sw.shutdown(Shutdown::Write));
                });
                let up = std::thread::spawn(move || read_check(&server));
                let down = read_check(&client);
                let _ = done_tx.send((up.join().unwrap(), down));
            });
        }
        drop(done_tx);
        let deadline = Instant::now() + Duration::from_secs(20);
        for _ in 0..STREAMS {
            let left = deadline.saturating_duration_since(Instant::now());
            let got = done.recv_timeout(left).expect("bulk transfer wedged: mux deadlock");
            assert_eq!(got, (N, N));
        }
        assert!(!fired.load(Ordering::Relaxed), "keepalive declared a live peer dead");
    }

    #[test]
    fn half_close_still_delivers_the_response() {
        let f = flow_pair();
        let (mut client, mut server, _, closed) = open(&f);
        client.write_all(b"GET /").unwrap();
        client.shutdown(Shutdown::Write).unwrap();
        let mut req = Vec::new();
        server.read_to_end(&mut req).unwrap();
        assert_eq!(req, b"GET /");
        // Bigger than the window + socket buffers, so it needs Window grants
        // flowing while the client's write side is already shut.
        let response: Vec<u8> = (0..1 << 20).map(pat).collect();
        let expected = response.clone();
        std::thread::spawn(move || {
            server.write_all(&response).unwrap();
            // Dropping closes our end: the daemon pump sees EOF.
        });
        let mut got = Vec::new();
        client.read_to_end(&mut got).unwrap();
        assert!(got == expected, "response differs ({} of {} bytes)", got.len(), expected.len());
        assert_eq!(closed.recv_timeout(Duration::from_secs(10)).unwrap(), "");
        wait_until("both sides to unregister", || both_unregistered(&f));
    }

    /// Stream A backed up (its server end never reads, and the host has spent
    /// all its credit), plus an idle stream B. Returns A's server end (keep it
    /// alive, unread) and B's two ends.
    fn stalled(f: &Flows) -> (UnixStream, UnixStream, UnixStream) {
        let (a_client, a_server, a_id, _) = open(f);
        // Blocks once everything between it and the unread server is full.
        std::thread::spawn(move || {
            let _ = write_pattern(&a_client, 64 << 20);
        });
        wait_until("A to exhaust its credit", || {
            f.host.flow(a_id).is_some_and(|fl| fl.state.lock().unwrap().send_credit == 0)
        });
        let (b_client, b_server, _, _) = open(f);
        (a_server, b_client, b_server)
    }

    fn echo(s: UnixStream) {
        std::thread::spawn(move || {
            let mut w = s.try_clone().unwrap();
            let _ = io::copy(&mut &s, &mut w);
        });
    }

    #[test]
    fn stalled_stream_does_not_delay_others() {
        let f = flow_pair();
        let (_a_server, b_client, b_server) = stalled(&f);
        echo(b_server);
        let mut b = BufReader::new(b_client);
        for i in 0..20 {
            let t = Instant::now();
            writeln!(b.get_mut(), "ping {i}").unwrap();
            let mut line = String::new();
            b.read_line(&mut line).unwrap();
            assert_eq!(line, format!("ping {i}\n"));
            assert!(t.elapsed() < Duration::from_secs(2), "B round-trip took {:?}", t.elapsed());
        }
    }

    #[test]
    fn keepalive_holds_while_a_stream_is_stalled() {
        let f = flow_pair();
        let fired = Arc::new(AtomicBool::new(false));
        for mux in [&f.host, &f.daemon] {
            let fired = Arc::clone(&fired);
            mux.keepalive(Duration::from_millis(5), Duration::from_millis(300), move || {
                fired.store(true, Ordering::Relaxed);
            });
        }
        let _ends = stalled(&f);
        std::thread::sleep(Duration::from_secs(1));
        assert!(!fired.load(Ordering::Relaxed), "keepalive declared a live peer dead");
    }

    #[test]
    fn dial_failure_reaches_the_host_with_its_reason() {
        let (host, _daemon) = flow_pair_with(|_, _| Err("connection refused".into()));
        let (mut client, theirs) = UnixStream::pair().unwrap();
        client.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
        let (tx, rx) = mpsc::channel();
        host.connect(theirs, "db", 5432, move |reason| {
            let _ = tx.send(reason);
        })
        .unwrap();
        assert_eq!(rx.recv_timeout(Duration::from_secs(10)).unwrap(), "connection refused");
        let mut buf = [0u8; 1];
        assert_eq!(client.read(&mut buf).unwrap(), 0, "client sees EOF");
        assert!(host.streams.lock().unwrap().is_empty());
    }

    /// Plain `serve` (the host side) refuses every `Connect`, with a reason.
    #[test]
    fn plain_serve_refuses_connect() {
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let (a, b) = (Mux::new(d_w), Mux::new(h_w));
        let a2 = Arc::clone(&a);
        std::thread::spawn(move || a2.serve(d_r, |_, _| None));
        std::thread::spawn(move || b.serve(h_r, |_, _| None));
        let (_client, theirs) = UnixStream::pair().unwrap();
        let (tx, rx) = mpsc::channel();
        a.connect(theirs, "svc", 80, move |reason| {
            let _ = tx.send(reason);
        })
        .unwrap();
        assert_eq!(rx.recv_timeout(Duration::from_secs(10)).unwrap(), "port forwarding not accepted by this peer");
    }

    /// A daemon-side `serve_with` fed frames through a pipe, so the test
    /// controls timing; each `Connect`'s reply is handed to the test unsettled.
    fn pending_daemon() -> (Arc<Mux>, Arc<Mutex<Vec<u8>>>, std::io::PipeWriter, mpsc::Receiver<ConnectReply>) {
        let (r, w) = std::io::pipe().unwrap();
        let out = Arc::new(Mutex::new(Vec::new()));
        let mux = Mux::new(Sink(Arc::clone(&out)));
        let (tx, replies) = mpsc::channel();
        let m = Arc::clone(&mux);
        std::thread::spawn(move || m.serve_with(r, |_, _| None, move |_, _, _, reply| tx.send(reply).unwrap()));
        (mux, out, w, replies)
    }

    #[test]
    fn data_racing_the_dial_is_queued_and_delivered() {
        let (_mux, _out, mut w, replies) = pending_daemon();
        let id = HOST_ID_BIT | 1;
        proto::write_frame(&mut w, &Frame::Connect { stream: id, host: "svc".into(), port: 80 }).unwrap();
        proto::write_frame(&mut w, &Frame::Data { stream: id, bytes: b"early".to_vec() }).unwrap();
        proto::write_frame(&mut w, &Frame::Eof { stream: id }).unwrap();
        let reply = replies.recv_timeout(Duration::from_secs(10)).unwrap();
        let (ours, mut theirs) = UnixStream::pair().unwrap();
        theirs.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
        // Give serve time to queue the Data and Eof before the dial "completes".
        std::thread::sleep(Duration::from_millis(50));
        reply.finish(Ok(ours.into()));
        let mut got = Vec::new();
        theirs.read_to_end(&mut got).unwrap();
        assert_eq!(got, b"early");
    }

    #[test]
    fn close_while_dialing_drops_the_late_socket() {
        let (mux, out, mut w, replies) = pending_daemon();
        let id = HOST_ID_BIT | 1;
        proto::write_frame(&mut w, &Frame::Connect { stream: id, host: "svc".into(), port: 80 }).unwrap();
        let reply = replies.recv_timeout(Duration::from_secs(10)).unwrap();
        proto::write_frame(&mut w, &Frame::Data { stream: id, bytes: b"early".to_vec() }).unwrap();
        proto::write_frame(&mut w, &Frame::Close { stream: id, reason: String::new() }).unwrap();
        wait_until("the pending stream to unregister", || mux.streams.lock().unwrap().is_empty());
        let (ours, mut theirs) = UnixStream::pair().unwrap();
        theirs.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
        reply.finish(Ok(ours.into()));
        let mut got = Vec::new();
        assert_eq!(theirs.read_to_end(&mut got).unwrap(), 0, "late socket dropped, nothing delivered");
        assert!(mux.streams.lock().unwrap().is_empty());
        assert!(out.lock().unwrap().is_empty(), "no Close echoed, nothing sent");
    }

    /// Feed `wire` to a daemon-side `serve_with` and return the frames it sent.
    /// With `dial`, every `Connect` gets a live socket (peer ends retained, so
    /// no pump sees EOF); without, replies stay pending until serve returns.
    fn daemon_frames(wire: Vec<u8>, dial: bool) -> Vec<Frame> {
        let out = Arc::new(Mutex::new(Vec::new()));
        let mux = Mux::new(Sink(Arc::clone(&out)));
        let peers = Mutex::new(Vec::new());
        let pending = Mutex::new(Vec::new());
        mux.serve_with(io::Cursor::new(wire), |_, _| None, |_, _, _, reply| {
            if dial {
                let (ours, theirs) = UnixStream::pair().unwrap();
                peers.lock().unwrap().push(theirs);
                reply.finish(Ok(ours.into()));
            } else {
                pending.lock().unwrap().push(reply);
            }
        });
        wait_ctl_drained(&mux);
        let mut r = io::Cursor::new(std::mem::take(&mut *out.lock().unwrap()));
        let mut frames = Vec::new();
        while let Ok(Some(frame)) = proto::read_frame(&mut r) {
            frames.push(frame);
        }
        frames
    }

    fn closes(frames: &[Frame]) -> Vec<(u32, String)> {
        frames
            .iter()
            .filter_map(|f| match f {
                Frame::Close { stream, reason } => Some((*stream, reason.clone())),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn credit_overrun_closes_only_that_stream() {
        let (a, b) = (HOST_ID_BIT | 1, HOST_ID_BIT | 2);
        let mut wire = Vec::new();
        for frame in [
            Frame::Connect { stream: a, host: "svc".into(), port: 80 },
            Frame::Connect { stream: b, host: "svc".into(), port: 80 },
            Frame::Data { stream: a, bytes: vec![0; INITIAL_WINDOW as usize + 1] },
            Frame::Data { stream: b, bytes: vec![0; 10] },
            Frame::Ping(b"alive".to_vec()),
        ] {
            proto::write_frame(&mut wire, &frame).unwrap();
        }
        let frames = daemon_frames(wire, true);
        assert_eq!(closes(&frames), [(a, FLOW_VIOLATION.to_string())]);
        assert!(frames.contains(&Frame::Pong(b"alive".to_vec())), "connection stays up");
    }

    fn refused_connects(ids: &[u32]) -> Vec<u32> {
        let mut wire = Vec::new();
        for &stream in ids {
            proto::write_frame(&mut wire, &Frame::Connect { stream, host: "svc".into(), port: 80 }).unwrap();
        }
        let frames = daemon_frames(wire, false);
        let closes = closes(&frames);
        assert!(closes.iter().all(|(_, r)| r == "stream refused"), "{closes:?}");
        closes.into_iter().map(|(s, _)| s).collect()
    }

    #[test]
    fn connect_id_policy() {
        let h = |n: u32| HOST_ID_BIT | n;
        // Daemon id space refused; a duplicate of a live (pending) id refused.
        assert_eq!(refused_connects(&[5, h(1), h(1)]), [5, h(1)]);
        // Up to MAX_HOST_STREAMS accepted (well past MAX_STREAMS), then refused.
        let ids: Vec<u32> = (1..=MAX_HOST_STREAMS as u32 + 2).map(h).collect();
        assert_eq!(refused_connects(&ids), [h(MAX_HOST_STREAMS as u32 + 1), h(MAX_HOST_STREAMS as u32 + 2)]);
    }

    // ---- flow-controlled `Open` (flowing channels) and host-opened `Open` ----

    /// A daemon-side hook accepting host `Open`s on `RPC` only, handing out
    /// one end of a socket pair; the other end goes to `peers`.
    fn rpc_only(peers: mpsc::Sender<UnixStream>) -> HostOpen {
        let peers = Mutex::new(peers);
        Arc::new(move |_, ch| {
            (ch == channel::RPC).then(|| {
                let (ours, theirs) = UnixStream::pair().unwrap();
                peers.lock().unwrap().send(theirs).unwrap();
                ours.into()
            })
        })
    }

    /// Feed `wire` to a daemon-side `serve_with` whose `on_host_open` is
    /// `rpc_only` (peer ends retained, so no stream ends on its own) and
    /// return the frames it sent.
    fn host_open_frames(wire: Vec<u8>) -> Vec<Frame> {
        let out = Arc::new(Mutex::new(Vec::new()));
        let mux = Mux::new(Sink(Arc::clone(&out)));
        let (tx, _peers) = mpsc::channel();
        mux.on_host_open(rpc_only(tx));
        mux.serve_with(io::Cursor::new(wire), |_, _| None, |_, _, _, reply: ConnectReply| reply.finish(Err("no".into())));
        wait_ctl_drained(&mux);
        let mut r = io::Cursor::new(std::mem::take(&mut *out.lock().unwrap()));
        let mut frames = Vec::new();
        while let Ok(Some(frame)) = proto::read_frame(&mut r) {
            frames.push(frame);
        }
        frames
    }

    fn refused_host_opens(opens: &[(u32, u8)]) -> Vec<u32> {
        let mut wire = Vec::new();
        for &(stream, channel) in opens {
            proto::write_frame(&mut wire, &Frame::Open { stream, channel }).unwrap();
        }
        closes(&host_open_frames(wire)).into_iter().map(|(s, _)| s).collect()
    }

    #[test]
    fn flowing_channels() {
        assert!(channel::flows(channel::RPC));
        for ch in [channel::SSH_AGENT, channel::HTTP_PROXY, channel::NOTIFY, channel::CONTROL] {
            assert!(!channel::flows(ch), "{ch} stays legacy");
        }
    }

    /// The daemon-side counterpart of `open_with_high_bit_is_refused`: with
    /// an `on_host_open` handler, a high-bit `Open` is admitted per channel
    /// (the handler's call) and per id (`Connect`'s policy); the daemon's own
    /// id space stays refused (`on_open` = none).
    #[test]
    fn host_open_id_and_channel_policy() {
        let h = |n: u32| HOST_ID_BIT | n;
        let opens = [(h(1), channel::RPC), (h(2), channel::SSH_AGENT), (h(1), channel::RPC), (3, channel::RPC)];
        assert_eq!(refused_host_opens(&opens), [h(2), h(1), 3]);
        // Up to MAX_HOST_STREAMS accepted, then refused.
        let opens: Vec<(u32, u8)> = (1..=MAX_HOST_STREAMS as u32 + 2).map(|n| (h(n), channel::RPC)).collect();
        assert_eq!(refused_host_opens(&opens), [h(MAX_HOST_STREAMS as u32 + 1), h(MAX_HOST_STREAMS as u32 + 2)]);
    }

    /// Without a handler (the host side, or a daemon that serves no RPC),
    /// a high-bit `Open` on a flowing channel is refused like any other.
    #[test]
    fn host_open_without_a_handler_is_refused() {
        let mut wire = Vec::new();
        proto::write_frame(&mut wire, &Frame::Open { stream: HOST_ID_BIT | 1, channel: channel::RPC }).unwrap();
        let frames = daemon_frames(wire, false);
        assert_eq!(closes(&frames), [(HOST_ID_BIT | 1, String::new())]);
    }

    /// `Connect`s and host `Open`s share one `MAX_HOST_STREAMS` budget.
    #[test]
    fn host_opens_count_against_the_connect_cap() {
        let h = |n: u32| HOST_ID_BIT | n;
        let mut wire = Vec::new();
        for n in 1..=MAX_HOST_STREAMS as u32 {
            proto::write_frame(&mut wire, &Frame::Open { stream: h(n), channel: channel::RPC }).unwrap();
        }
        let over = h(MAX_HOST_STREAMS as u32 + 1);
        proto::write_frame(&mut wire, &Frame::Connect { stream: over, host: "svc".into(), port: 80 }).unwrap();
        assert_eq!(closes(&host_open_frames(wire)), [(over, "stream refused".to_string())]);
    }

    /// `credit_overrun_closes_only_that_stream` for a flowing `Open`.
    #[test]
    fn credit_overrun_on_a_flowing_open_closes_only_that_stream() {
        let (a, b) = (HOST_ID_BIT | 1, HOST_ID_BIT | 2);
        let mut wire = Vec::new();
        for frame in [
            Frame::Open { stream: a, channel: channel::RPC },
            Frame::Open { stream: b, channel: channel::RPC },
            Frame::Data { stream: a, bytes: vec![0; INITIAL_WINDOW as usize + 1] },
            Frame::Data { stream: b, bytes: vec![0; 10] },
            Frame::Ping(b"alive".to_vec()),
        ] {
            proto::write_frame(&mut wire, &frame).unwrap();
        }
        let frames = host_open_frames(wire);
        assert_eq!(closes(&frames), [(a, FLOW_VIOLATION.to_string())]);
        assert!(frames.contains(&Frame::Pong(b"alive".to_vec())), "connection stays up");
    }

    fn is_flow(mux: &Mux, stream: u32) -> Option<bool> {
        mux.streams.lock().unwrap().get(&stream).map(|e| matches!(e, Entry::Flow(_)))
    }

    /// `flow_pair_with` for `Open`: a host-opened `RPC` stream is a flow
    /// stream on both ends and moves more than a window each way with a
    /// clean both-`Eof` teardown; a daemon-opened `CONTROL` stream on the
    /// same connection stays legacy on both ends.
    #[test]
    fn flowing_open_is_flow_controlled_on_both_ends_and_legacy_stays_legacy() {
        const N: usize = 1 << 20;
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        let host = Mux::new(h_w);
        let (tx, servers) = mpsc::channel();
        daemon.on_host_open(rpc_only(tx));
        let d = Arc::clone(&daemon);
        std::thread::spawn(move || d.serve(d_r, |_, _| None));
        let h = Arc::clone(&host);
        std::thread::spawn(move || {
            h.serve(h_r, |_, ch| {
                (ch == channel::CONTROL).then(|| {
                    let (ours, agent) = UnixStream::pair().unwrap();
                    echo_agent(agent);
                    ours.into()
                })
            })
        });

        let id = HOST_ID_BIT | 1;
        let (caller, theirs) = UnixStream::pair().unwrap();
        host.attach(id, theirs, Some(channel::RPC)).unwrap();
        assert_eq!(is_flow(&host, id), Some(true), "opener's end");
        let server = servers.recv_timeout(Duration::from_secs(10)).unwrap();
        // The hook hands `server` out before `accept_open` registers it.
        wait_until("the accepting end's flow", || is_flow(&daemon, id) == Some(true));
        for s in [&caller, &server] {
            s.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
        }
        let (cw, sw) = (caller.try_clone().unwrap(), server.try_clone().unwrap());
        let up = std::thread::spawn(move || {
            write_pattern(&cw, N).unwrap();
            cw.shutdown(Shutdown::Write).unwrap();
        });
        let down = std::thread::spawn(move || {
            write_pattern(&sw, N).unwrap();
            sw.shutdown(Shutdown::Write).unwrap();
        });
        let received_up = std::thread::spawn(move || read_check(&server));
        assert_eq!(read_check(&caller), N);
        assert_eq!(received_up.join().unwrap(), N);
        up.join().unwrap();
        down.join().unwrap();
        wait_until("both sides to unregister", || {
            host.streams.lock().unwrap().is_empty() && daemon.streams.lock().unwrap().is_empty()
        });

        let mut c = client(&daemon, 1, channel::CONTROL);
        writeln!(c.get_mut(), "ping").unwrap();
        let mut line = String::new();
        c.read_line(&mut line).unwrap();
        assert_eq!(line, "re:ping\n");
        assert_eq!(is_flow(&daemon, 1), Some(false), "legacy on the opener");
        assert_eq!(is_flow(&host, 1), Some(false), "legacy on the acceptor");
    }

    /// A host and a daemon mux over pipes, the daemon serving host `Open`s on
    /// `RPC` with `respond` (on a thread per stream, like `rpc_server`).
    fn rpc_pair(respond: fn(UnixStream)) -> (Arc<Mux>, Arc<Mux>) {
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        let host = Mux::new(h_w);
        daemon.on_host_open(Arc::new(move |_, ch| {
            (ch == channel::RPC).then(|| {
                let (ours, theirs) = UnixStream::pair().unwrap();
                std::thread::spawn(move || respond(theirs));
                ours.into()
            })
        }));
        let d = Arc::clone(&daemon);
        std::thread::spawn(move || d.serve(d_r, |_, _| None));
        let h = Arc::clone(&host);
        std::thread::spawn(move || h.serve(h_r, |_, _| None));
        (host, daemon)
    }

    /// A test responder over the shared codec, shaped like `rpc_server`'s
    /// `serve`: read the `call`, answer `result {method}` (or, for `hang`,
    /// a `stdout` and nothing more until the stream goes), half-close,
    /// drain the caller's input.
    fn responder(s: UnixStream) {
        use super::super::rpc::{self, Obj, Record};
        let mut r = &s;
        let Ok(Some(Record::Call(call))) = rpc::read_record(&mut r) else { return };
        let mut w = &s;
        if call.method == "hang" {
            let _ = rpc::write_record(&mut w, &Record::Stdout(b"working".to_vec()));
            let _ = io::copy(&mut r, &mut io::sink());
            return;
        }
        let _ = rpc::write_record(&mut w, &Record::Result(Obj::new().with("method", call.method.as_str())));
        let _ = s.shutdown(Shutdown::Write);
        let _ = io::copy(&mut r, &mut io::sink());
    }

    fn rpc_call(host: &Arc<Mux>, method: &str) -> (u32, Conn, mpsc::Receiver<String>) {
        use super::super::rpc::{self, Call, Record};
        let (tx, closed) = mpsc::channel();
        let (id, mut conn) = host
            .open_host(channel::RPC, move |reason| {
                let _ = tx.send(reason);
            })
            .unwrap();
        let Conn::Unix(s) = &conn else { unreachable!() };
        s.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
        rpc::write_record(&mut conn, &Record::Call(Call { method: method.into(), ..Call::default() })).unwrap();
        (id, conn, closed)
    }

    /// `open_host`: a high-bit flow stream on both ends; a call and its
    /// answer round-trip, and once both sides half-close it tears down
    /// cleanly (`on_close` with no reason). Ids stay monotonic.
    #[test]
    fn open_host_round_trips_a_call_and_tears_down_on_both_eofs() {
        use super::super::rpc::{self, Obj, Record};
        let (host, daemon) = rpc_pair(responder);
        let (id, mut conn, closed) = rpc_call(&host, "rpc.methods");
        assert_ne!(id & HOST_ID_BIT, 0);
        assert_eq!(is_flow(&host, id), Some(true));
        conn.shutdown(Shutdown::Write).unwrap();
        let rec = rpc::read_record(&mut conn).unwrap();
        assert_eq!(rec, Some(Record::Result(Obj::new().with("method", "rpc.methods"))));
        assert_eq!(rpc::read_record(&mut conn).unwrap(), None, "the daemon's Eof");
        assert_eq!(closed.recv_timeout(Duration::from_secs(10)).unwrap(), "");
        wait_until("both sides to unregister", || {
            host.streams.lock().unwrap().is_empty() && daemon.streams.lock().unwrap().is_empty()
        });
        let (next, _conn, _closed) = rpc_call(&host, "x");
        assert!(next > id, "monotonic: {next:#x} after {id:#x}");
    }

    /// `close_stream` cancels a call in flight: the caller's end reads EOF,
    /// `on_close` gets the reason, the daemon's end is shut, both sides
    /// unregister; other streams and a closed id are unaffected.
    #[test]
    fn close_stream_cancels_one_call() {
        use super::super::rpc::{self, Record};
        let (host, daemon) = rpc_pair(responder);
        let (id, mut conn, closed) = rpc_call(&host, "hang");
        assert_eq!(rpc::read_record(&mut conn).unwrap(), Some(Record::Stdout(b"working".to_vec())));
        let (other, mut other_conn, _other_closed) = rpc_call(&host, "hang");
        assert!(host.close_stream(id, "cancelled"));
        assert_eq!(closed.recv_timeout(Duration::from_secs(10)).unwrap(), "cancelled");
        assert_eq!(rpc::read_record(&mut conn).unwrap(), None);
        wait_until("the daemon to drop it", || !daemon.streams.lock().unwrap().contains_key(&id));
        assert!(!host.close_stream(id, "again"), "already gone");
        assert_eq!(rpc::read_record(&mut other_conn).unwrap(), Some(Record::Stdout(b"working".to_vec())));
        assert!(host.streams.lock().unwrap().contains_key(&other));
    }

    /// `open_host` refuses a legacy channel and a connection that ended.
    #[test]
    fn open_host_refuses_legacy_channels_and_ended_connections() {
        let mux = Mux::new(io::sink());
        let err = mux.open_host(channel::CONTROL, |_| {}).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
        mux.serve(io::empty(), |_, _| None);
        let err = mux.open_host(channel::RPC, |_| panic!("not reported")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::BrokenPipe);
        assert!(mux.streams.lock().unwrap().is_empty());
    }

    /// A host and a daemon mux over pipes; the daemon answers `PortQuery`s
    /// with `lookup` when given one. Returns the host side.
    fn port_pair(lookup: Option<PortLookup>) -> Arc<Mux> {
        let (d_r, h_w) = std::io::pipe().unwrap();
        let (h_r, d_w) = std::io::pipe().unwrap();
        let daemon = Mux::new(d_w);
        if let Some(lookup) = lookup {
            daemon.on_port_query(lookup);
        }
        let host = Mux::new(h_w);
        std::thread::spawn(move || daemon.serve(d_r, |_, _| None));
        let h = Arc::clone(&host);
        std::thread::spawn(move || h.serve(h_r, |_, _| None));
        host
    }

    #[test]
    fn port_query_round_trips_concurrently() {
        let host = port_pair(Some(Arc::new(|port| vec![(u32::from(port), format!("p{port}"))])));
        let handles: Vec<_> = (1..=4u16)
            .map(|port| {
                let host = Arc::clone(&host);
                std::thread::spawn(move || (port, host.port_query(port, Duration::from_secs(5)).unwrap()))
            })
            .collect();
        for h in handles {
            let (port, procs) = h.join().unwrap();
            assert_eq!(procs, [(u32::from(port), format!("p{port}"))]);
        }
        assert!(host.queries.lock().unwrap().is_empty(), "answered queries are unregistered");
    }

    /// A daemon without a lookup leaves the query unanswered: the host's wait
    /// is bounded by its timeout, and the connection stays usable.
    #[test]
    fn unanswered_port_query_times_out() {
        let host = port_pair(None);
        let start = Instant::now();
        let err = host.port_query(80, Duration::from_millis(200)).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
        assert!(start.elapsed() < Duration::from_secs(2));
        assert!(host.queries.lock().unwrap().is_empty());
    }

    /// The connection ending wakes a waiting query at once (`BrokenPipe`), and
    /// a query after the end fails without waiting.
    #[test]
    fn port_query_fails_fast_when_the_connection_ends() {
        let (h_r, d_w) = std::io::pipe().unwrap();
        let (_d_r, h_w) = std::io::pipe().unwrap();
        let host = Mux::new(h_w);
        let h = Arc::clone(&host);
        let served = std::thread::spawn(move || h.serve(h_r, |_, _| None));
        let waiter = {
            let host = Arc::clone(&host);
            std::thread::spawn(move || host.port_query(80, Duration::from_secs(30)))
        };
        std::thread::sleep(Duration::from_millis(100));
        drop(d_w); // peer gone: `serve` returns
        served.join().unwrap();
        let start = Instant::now();
        assert_eq!(waiter.join().unwrap().unwrap_err().kind(), io::ErrorKind::BrokenPipe);
        let err = host.port_query(80, Duration::from_secs(30)).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::BrokenPipe);
        assert!(start.elapsed() < Duration::from_secs(5));
    }
}