puressh 0.1.3

A pure-Rust SSH (Secure Shell) protocol library, in the spirit of libssh, built on purecrypto.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
//! `ssh_config(5)` parsing — see [`SshClientConfig`].
//!
//! Only the keywords the puressh client binaries actually consume today are
//! recognised; any other keyword is rejected as
//! [`ConfigError::UnknownKeyword`]. This is deliberate: the scope is "config
//! values that change observable behaviour", and silently dropping an
//! unrecognised knob is worse than failing loudly.
//!
//! The file is a sequence of blocks. `Host <pattern>` opens a host-pattern
//! block, `Match <criteria>` opens a Match block, and everything before the
//! first block belongs to an implicit "global" Host * block. Settings inside a
//! block apply when the block's selector matches the lookup target;
//! [`SshClientConfig::lookup`] walks the blocks in order with OpenSSH's
//! first-match-wins precedence (scalars) and cumulative-concatenation
//! semantics (`IdentityFile`, `LocalForward`, `RemoteForward`).

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use super::ConfigError;
use super::algos::{AlgoCategory, resolve_algo_list};
use super::glob::{HostPattern, host_matches};
use super::match_block::{ExecPolicy, MatchCondition, MatchContext, all_match, parse_match_line};
use super::parser::{ParsedLine, tokenize};

/// `StrictHostKeyChecking` value — maps OpenSSH's keyword set to puressh's
/// TOFU policy. Re-exported as `puressh::config::StrictMode` and re-exported
/// once more from `src/bin/common.rs` so existing binaries keep compiling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StrictMode {
    /// `yes`: refuse Unknown; reject Mismatch.
    Yes,
    /// `no`: accept Unknown silently AND tolerate Mismatch (insecure).
    No,
    /// `accept-new`: silently accept Unknown; still reject Mismatch.
    AcceptNew,
    /// `ask` (OpenSSH default): prompt on Unknown; reject Mismatch.
    Ask,
}

/// `RequestTTY` value. Distinct from a CLI bool: `Auto` means "PTY if local
/// stdin is a tty" — the binary needs the original token so it can decide
/// late.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RequestTty {
    /// `no`: never allocate.
    No,
    /// `yes`: allocate when there's an interactive session (default for
    /// interactive shells).
    Yes,
    /// `force`: always allocate.
    Force,
    /// `auto`: allocate iff local stdin is a tty.
    Auto,
}

/// `AddressFamily` value — filters the addresses a hostname resolves to
/// before we attempt a connection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AddressFamily {
    /// `any`: no filtering (default).
    Any,
    /// `inet`: IPv4 only.
    Inet,
    /// `inet6`: IPv6 only.
    Inet6,
}

/// `GatewayPorts` value — controls the bind address of client-side
/// `-L` / `-D` listeners.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GatewayPorts {
    /// `no`: bind loopback (`127.0.0.1`) only (default).
    No,
    /// `yes`: bind all interfaces (`0.0.0.0`).
    Yes,
    /// `clientspecified`: honour the bind address spelled out in the
    /// forward spec; fall back to loopback when none was given.
    ClientSpecified,
}

/// `IdentityAgent` value — overrides which ssh-agent socket the client
/// talks to.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IdentityAgent {
    /// `none`: never consult an agent.
    None,
    /// A filesystem path to the agent socket. The literal token
    /// `SSH_AUTH_SOCK` (and `$SSH_AUTH_SOCK`) is preserved verbatim here
    /// and expanded against the environment at the honoring site.
    Path(String),
}

/// `ControlMaster` value — controls connection-multiplexing role.
///
/// `ask` / `autoask` would prompt the user for permission before
/// reusing/establishing a master. puressh has no interactive confirmation
/// path for this decision, so both are rejected at parse time as
/// [`ConfigError::Unsupported`] rather than silently downgraded to `yes`
/// (which would defeat the user's explicit request to be asked).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ControlMaster {
    /// `no` (default): never multiplex. Open a fresh connection.
    No,
    /// `yes`: become the master. Fails if the `ControlPath` socket already
    /// has a live master answering.
    Yes,
    /// `auto`: reuse an existing master if the socket answers; otherwise
    /// connect normally and become the master.
    Auto,
}

/// `ControlPersist` value — how long a master lingers after its foreground
/// session ends.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ControlPersist {
    /// `no`: the master exits as soon as its own foreground session ends
    /// (still serving any clients that attached, but tearing down once the
    /// initiating session finishes — matches OpenSSH `no`).
    No,
    /// `yes`: the master persists indefinitely after the foreground session
    /// ends, until explicitly stopped (or the process exits).
    Yes,
    /// `<N>` (or `<N>[smh]`): linger N seconds after the last client
    /// detaches, then unlink the socket and exit.
    Seconds(u64),
}

/// `ObscureKeystrokeTiming` value (OpenSSH 9.5+). Controls keystroke-timing
/// obfuscation on interactive (pty) sessions: when on, the client releases
/// keystrokes on a fixed cadence and pads idle gaps with `ping@openssh.com`
/// chaff so the on-wire packet rate is constant while typing.
///
/// OpenSSH syntax: `yes` (on, default interval 20 ms), `no`, or
/// `interval:<spec>` where `<spec>` is a millisecond count (`interval:80`) or
/// an OpenSSH time value with unit suffixes (`interval:1s`). The OpenSSH
/// default when the option is unset is `yes` at 20 ms.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ObscureKeystrokeTiming {
    /// `no`: disabled — keystrokes are sent immediately as today.
    Off,
    /// `yes` / `interval:<spec>`: enabled with the given cadence in
    /// milliseconds. `yes` ⇒ `On { interval_ms: 20 }`.
    On {
        /// Cadence between cadence ticks, in milliseconds.
        interval_ms: u32,
    },
}

impl ObscureKeystrokeTiming {
    /// OpenSSH's default cadence interval (20 ms) used by bare `yes`.
    pub const DEFAULT_INTERVAL_MS: u32 = 20;

    /// The effective default when the option is unset: on at 20 ms, matching
    /// OpenSSH's compiled-in default.
    pub fn default_on() -> Self {
        ObscureKeystrokeTiming::On {
            interval_ms: Self::DEFAULT_INTERVAL_MS,
        }
    }

    /// `true` if obfuscation is enabled.
    pub fn is_on(&self) -> bool {
        matches!(self, ObscureKeystrokeTiming::On { .. })
    }

    /// The cadence interval in milliseconds when on; `None` when off.
    pub fn interval_ms(&self) -> Option<u32> {
        match self {
            ObscureKeystrokeTiming::On { interval_ms } => Some(*interval_ms),
            ObscureKeystrokeTiming::Off => None,
        }
    }
}

/// One `DynamicForward` entry — a local SOCKS proxy listener. Wire form
/// `[bind:]port`, e.g. `1080` or `127.0.0.1:1080`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DynamicForwardSpec {
    /// Local bind address; `None` ⇒ loopback (subject to `GatewayPorts`).
    pub bind_addr: Option<String>,
    /// Local port the SOCKS listener binds.
    pub listen_port: u16,
}

/// One `LocalForward` entry. Wire form `[bind:]port host:hostport`, e.g.
/// `8080 example.com:80` or `127.0.0.1:8080 example.com:80`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LocalForwardSpec {
    /// Local bind address; `None` ⇒ loopback (`127.0.0.1`).
    pub bind_addr: Option<String>,
    /// Local port to listen on.
    pub listen_port: u16,
    /// Remote destination host (resolved server-side).
    pub remote_host: String,
    /// Remote destination port.
    pub remote_port: u16,
}

/// One `RemoteForward` entry. Wire form `[bind:]port host:hostport`, e.g.
/// `8080 127.0.0.1:8080`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteForwardSpec {
    /// Remote bind address; `None` ⇒ loopback on the server side.
    pub bind_addr: Option<String>,
    /// Remote port the server should bind.
    pub remote_port: u16,
    /// Local destination host (resolved client-side).
    pub local_host: String,
    /// Local destination port.
    pub local_port: u16,
}

/// Per-host options. Every field is `Option`-typed so callers can distinguish
/// "not set" from "set to default" and apply OpenSSH precedence (CLI > file >
/// built-in default) via a `pick(cli, cfg, default)` helper.
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct ClientOptions {
    /// `HostName`: real hostname to connect to (the `Host` block name is just a label).
    pub host_name: Option<String>,
    /// `Port`: TCP port for the SSH session.
    pub port: Option<u16>,
    /// `User`: remote username.
    pub user: Option<String>,
    /// `IdentityFile` (cumulative across matching blocks).
    pub identity_files: Vec<String>,
    /// `CertificateFile` (cumulative across matching blocks) — paths to user
    /// certificates (`*-cert.pub`) to offer, each paired at load time with the
    /// `IdentityFile` private key whose embedded key it certifies.
    pub certificate_files: Vec<String>,
    /// `IdentitiesOnly` (yes/no).
    pub identities_only: Option<bool>,
    /// `StrictHostKeyChecking`.
    pub strict_host_key: Option<StrictMode>,
    /// `UserKnownHostsFile`.
    pub user_known_hosts: Option<String>,
    /// `HashKnownHosts` (yes/no).
    pub hash_known_hosts: Option<bool>,
    /// `LocalForward` entries (cumulative).
    pub local_forwards: Vec<LocalForwardSpec>,
    /// `RemoteForward` entries (cumulative).
    pub remote_forwards: Vec<RemoteForwardSpec>,
    /// `ForwardAgent` (yes/no).
    pub forward_agent: Option<bool>,
    /// `ForwardX11` (yes/no).
    pub forward_x11: Option<bool>,
    /// `ForwardX11Trusted` (yes/no).
    pub forward_x11_trusted: Option<bool>,
    /// `RequestTTY` (yes/no/force/auto).
    pub request_tty: Option<RequestTty>,
    /// `LogLevel`: 0 = QUIET/INFO, 1 = VERBOSE/DEBUG1, 2 = DEBUG2, 3 = DEBUG3.
    pub log_level: Option<u8>,
    /// `Ciphers` — resolved cipher preference list (strict-validated, with
    /// list modifiers already applied). `None` ⇒ built-in default.
    pub ciphers: Option<Vec<String>>,
    /// `MACs` — resolved MAC preference list.
    pub macs: Option<Vec<String>>,
    /// `KexAlgorithms` — resolved key-exchange preference list (no markers).
    pub kex_algorithms: Option<Vec<String>>,
    /// `HostKeyAlgorithms` — resolved server host-key preference list.
    pub host_key_algorithms: Option<Vec<String>>,
    /// `PubkeyAcceptedAlgorithms` — resolved publickey-auth signature list.
    pub pubkey_accepted_algorithms: Option<Vec<String>>,
    /// `CASignatureAlgorithms` — resolved set of signature algorithms accepted
    /// from a CA when verifying a host certificate. `None` ⇒ built-in default
    /// ([`super::algos::CA_SIGNATURE_DEFAULTS`]).
    pub ca_signature_algorithms: Option<Vec<String>>,
    /// `ProxyCommand` — shell command (with `%h`/`%p`/`%r`/`%%` tokens
    /// un-expanded) to spawn and use as the connection transport. The
    /// literal `none` clears it back to `None`.
    pub proxy_command: Option<String>,
    /// `ProxyJump` — comma-separated `[user@]host[:port]` jump-host chain
    /// to tunnel the connection through. The literal `none` clears it.
    /// Takes precedence over [`Self::proxy_command`] when both are set.
    pub proxy_jump: Option<String>,
    /// `Compression` (yes/no). `Some(true)` advertises
    /// `zlib@openssh.com` ahead of `none`. Requires the `compress`
    /// feature at honoring time.
    pub compression: Option<bool>,
    /// `SetEnv` — literal `NAME=VALUE` pairs to send via `env` requests
    /// (cumulative across matching blocks; later duplicates of a name are
    /// dropped at honoring time per first-wins).
    pub set_env: Vec<(String, String)>,
    /// `SendEnv` — environment-variable name patterns; matching local env
    /// vars are forwarded via `env` requests (cumulative).
    pub send_env: Vec<String>,
    /// `ConnectTimeout` — TCP connect timeout in seconds. `0` is rejected.
    pub connect_timeout: Option<u32>,
    /// `ServerAliveInterval` — seconds between keepalive probes when the
    /// connection is otherwise idle. `0` (or unset) ⇒ disabled.
    pub server_alive_interval: Option<u32>,
    /// `ServerAliveCountMax` — number of unanswered keepalives tolerated
    /// before the connection is torn down (default 3 at honoring time).
    pub server_alive_count_max: Option<u32>,
    /// `TCPKeepAlive` (yes/no) — toggles SO_KEEPALIVE on the socket.
    pub tcp_keep_alive: Option<bool>,
    /// `AddKeysToAgent` — `Some(true)`/`Some(false)`. `confirm`/`ask` are
    /// rejected at parse time (Unsupported).
    pub add_keys_to_agent: Option<bool>,
    /// `PreferredAuthentications` — ordered, comma-separated auth-method
    /// list. Only `publickey`/`password`/`keyboard-interactive`/`none`
    /// are accepted; a list naming none of the implementable methods is
    /// rejected at parse time.
    pub preferred_authentications: Option<Vec<String>>,
    /// `PubkeyAuthentication` (yes/no) — gates publickey credentials.
    pub pubkey_authentication: Option<bool>,
    /// `NumberOfPasswordPrompts` — cap on interactive password attempts
    /// (default 3). `0` disables password auth.
    pub number_of_password_prompts: Option<u32>,
    /// `BatchMode` (yes/no) — never prompt; treat `ask` strict policy as
    /// `yes` and disable password auth.
    pub batch_mode: Option<bool>,
    /// `ExitOnForwardFailure` (yes/no) — abort the connection if any
    /// requested forward fails to bind / be granted.
    pub exit_on_forward_failure: Option<bool>,
    /// `ClearAllForwardings` (yes/no) — discard all local/remote/dynamic
    /// forwards collected so far before connecting.
    pub clear_all_forwardings: Option<bool>,
    /// `DynamicForward` entries — SOCKS proxy listeners (cumulative).
    pub dynamic_forwards: Vec<DynamicForwardSpec>,
    /// `GatewayPorts` — bind-address policy for `-L`/`-D` listeners.
    pub gateway_ports: Option<GatewayPorts>,
    /// `AddressFamily` — restrict resolved addresses to a family.
    pub address_family: Option<AddressFamily>,
    /// `BindAddress` — local source address to bind before connecting.
    pub bind_address: Option<String>,
    /// `IdentityAgent` — agent-socket override (or `none`).
    pub identity_agent: Option<IdentityAgent>,
    /// `ControlMaster` — connection-multiplexing role (no/yes/auto).
    pub control_master: Option<ControlMaster>,
    /// `ControlPath` — Unix-domain control-socket path with `%`-token and
    /// `~` expansion deferred to the honoring site. The literal `none`
    /// (case-insensitive) is stored as `None` to disable multiplexing.
    pub control_path: Option<String>,
    /// `ControlPersist` — how long the master lingers after its foreground
    /// session ends (no/yes/`<N>[smh]`).
    pub control_persist: Option<ControlPersist>,
    /// `ObscureKeystrokeTiming` — keystroke-timing obfuscation for
    /// interactive sessions (`yes`/`no`/`interval:<spec>`). Unset ⇒ honoring
    /// site applies the OpenSSH default (`yes` at 20 ms).
    pub obscure_keystroke_timing: Option<ObscureKeystrokeTiming>,
}

/// One block in a parsed `ssh_config` — either a `Host` block or a `Match`
/// block. Pre-block lines go into an implicit `Host *` block at index 0.
#[derive(Clone, Debug)]
pub(crate) enum Block {
    Host {
        patterns: Vec<HostPattern>,
        opts: ClientOptions,
    },
    Match {
        conditions: Vec<MatchCondition>,
        opts: ClientOptions,
    },
}

impl Block {
    fn opts(&self) -> &ClientOptions {
        match self {
            Block::Host { opts, .. } | Block::Match { opts, .. } => opts,
        }
    }
    fn opts_mut(&mut self) -> &mut ClientOptions {
        match self {
            Block::Host { opts, .. } | Block::Match { opts, .. } => opts,
        }
    }
}

/// A parsed `ssh_config(5)` file.
///
/// Use [`SshClientConfig::parse`] to construct one from text, then
/// [`SshClientConfig::lookup`] (or [`SshClientConfig::lookup_with`] for full
/// `Match` evaluation) to flatten the matching blocks for a target host.
/// Pre-`Host` lines form an implicit "global" block applied to every host
/// (OpenSSH's documented behaviour).
#[derive(Clone, Debug, Default)]
pub struct SshClientConfig {
    pub(crate) blocks: Vec<Block>,
    /// Whether `Match exec` criteria are allowed to execute. Default `false`
    /// (deny). Toggle with [`Self::enable_match_exec`].
    enable_match_exec: bool,
}

impl SshClientConfig {
    /// Parse `src` (the contents of a `ssh_config` file) into an
    /// [`SshClientConfig`]. `Match exec` evaluation is **off** by default;
    /// see [`Self::enable_match_exec`].
    ///
    /// `Include` directives are not resolved by this entry point because
    /// inline parsing has no filesystem context to anchor relative paths to.
    /// Use [`Self::load`] (or [`Self::load_with_base`]) to parse a file with
    /// Include support.
    pub fn parse(src: &str) -> Result<Self, ConfigError> {
        let lines = tokenize(src)?;
        let blocks = parse_blocks(lines)?;
        Ok(SshClientConfig {
            blocks,
            enable_match_exec: false,
        })
    }

    /// Read `path` from disk and parse it, resolving `Include` directives
    /// recursively. Relative paths inside `Include` are anchored to the
    /// directory of the file containing the directive; `~` expands to
    /// `$HOME`; `*` / `?` globs are expanded against the filesystem.
    /// Recursion is capped at [`super::include::MAX_INCLUDE_DEPTH`] hops.
    #[cfg(feature = "std")]
    pub fn load<P: AsRef<std::path::Path>>(path: P) -> Result<Self, ConfigError> {
        let lines = super::include::tokenize_file_with_includes(path.as_ref(), 0)?;
        let blocks = parse_blocks(lines)?;
        Ok(SshClientConfig {
            blocks,
            enable_match_exec: false,
        })
    }

    /// Like [`Self::load`] but parses an in-memory `src` while still
    /// honouring `Include` directives relative to `base_dir`. Useful when
    /// the config has been pre-read (e.g. from a memfd) but you still want
    /// Include semantics anchored at a known directory.
    #[cfg(feature = "std")]
    pub fn load_with_base<P: AsRef<std::path::Path>>(
        src: &str,
        base_dir: P,
    ) -> Result<Self, ConfigError> {
        let lines = tokenize(src)?;
        let expanded = super::include::expand_includes(lines, base_dir.as_ref(), 0)?;
        let blocks = parse_blocks(expanded)?;
        Ok(SshClientConfig {
            blocks,
            enable_match_exec: false,
        })
    }

    /// Append every block of `other` after this config's own, preserving
    /// source order.
    ///
    /// Used to layer a lower-precedence config (e.g. the system-wide
    /// `/etc/ssh/ssh_config`) beneath a higher-precedence one (the user's
    /// `~/.ssh/config`). Because [`lookup`](Self::lookup) is first-match-wins
    /// for scalars, `self`'s blocks keep winning while `other` still
    /// contributes to the cumulative list fields — the same result as
    /// concatenating the two files' text, but with each file's `Include`
    /// directives already resolved relative to its own directory. Both
    /// implicit `Host *` globals survive; `self`'s comes first, so it wins
    /// scalar options.
    pub fn append(&mut self, other: SshClientConfig) {
        self.blocks.extend(other.blocks);
    }

    /// Permit `Match exec <cmd>` criteria to run `/bin/sh -c <cmd>` during
    /// lookup. Off by default because evaluating arbitrary shell commands
    /// during config resolution is a confused-deputy hazard: a config loaded
    /// from an untrusted location could trigger arbitrary commands at the
    /// privilege level of whoever called `lookup`. Callers that fully trust
    /// the config source (e.g. a CLI tool loading the local user's
    /// `~/.ssh/config`) can opt in.
    pub fn enable_match_exec(mut self, allow: bool) -> Self {
        self.enable_match_exec = allow;
        self
    }

    /// `true` iff `Match exec` is currently permitted on this config.
    pub fn is_match_exec_enabled(&self) -> bool {
        self.enable_match_exec
    }

    /// Resolve the effective options for `host`, walking every matching
    /// block in source order with OpenSSH **first-match-wins** semantics for
    /// scalars and **concatenation** for cumulative list fields
    /// (`IdentityFile`, `LocalForward`, `RemoteForward`).
    ///
    /// `Match` blocks that need a username (`Match user …` / `Match localuser
    /// …`) will not match through this entry point — they require fields the
    /// bare `host`-only API doesn't carry. Use [`Self::lookup_with`] when you
    /// have that context.
    pub fn lookup(&self, host: &str) -> ClientOptions {
        self.lookup_with(MatchContext {
            host,
            original_host: None,
            user: None,
            local_user: None,
            ..MatchContext::default()
        })
    }

    /// Like [`Self::lookup`] but supplies a full [`MatchContext`] so `Match`
    /// blocks with `user` / `localuser` / `originalhost` criteria can match.
    pub fn lookup_with(&self, ctx: MatchContext<'_>) -> ClientOptions {
        let policy = if self.enable_match_exec {
            ExecPolicy::Allow
        } else {
            ExecPolicy::Deny
        };
        let mut out = ClientOptions::default();
        for block in &self.blocks {
            let matches = match block {
                Block::Host { patterns, .. } => host_matches(patterns, ctx.host),
                Block::Match { conditions, .. } => all_match(conditions, &ctx, policy),
            };
            if matches {
                merge_into(&mut out, block.opts());
            }
        }
        out
    }
}

/// Walk the tokenised stream and split it into [`Block`]s. Lines outside any
/// explicit `Host` / `Match` block accumulate into the implicit `Host *`
/// block at index 0.
pub(crate) fn parse_blocks(lines: Vec<ParsedLine>) -> Result<Vec<Block>, ConfigError> {
    let mut blocks: Vec<Block> = vec![Block::Host {
        patterns: vec![HostPattern::Any],
        opts: ClientOptions::default(),
    }];
    for line in lines {
        match line.keyword.as_str() {
            "host" => {
                if line.args.is_empty() {
                    return Err(ConfigError::BadValue {
                        line: line.line_no,
                        keyword: "host".to_string(),
                        msg: "Host requires at least one pattern".into(),
                    });
                }
                blocks.push(Block::Host {
                    patterns: HostPattern::parse_all(&line.args),
                    opts: ClientOptions::default(),
                });
            }
            "match" => {
                let conditions = parse_match_line(&line.args, line.line_no)?;
                blocks.push(Block::Match {
                    conditions,
                    opts: ClientOptions::default(),
                });
            }
            "include" => {
                // The Include-expansion pass runs before us when the caller
                // uses SshClientConfig::load* (the std-only entry points). If
                // we see an Include here, the user reached us via
                // SshClientConfig::parse(&str), which has no filesystem
                // context — refuse rather than silently drop.
                return Err(ConfigError::Unsupported {
                    line: line.line_no,
                    msg: "Include requires file-based loading; use SshClientConfig::load() instead"
                        .into(),
                });
            }
            _ => {
                let current = blocks.last_mut().expect("global block always present");
                apply_keyword(current.opts_mut(), &line)?;
            }
        }
    }
    Ok(blocks)
}

/// Apply one parsed line to the in-progress [`ClientOptions`] of the current
/// block.
fn apply_keyword(opts: &mut ClientOptions, line: &ParsedLine) -> Result<(), ConfigError> {
    let kw = line.keyword.as_str();
    let args = &line.args;
    match kw {
        "hostname" => {
            opts.host_name = Some(one_arg(line)?);
        }
        "port" => {
            opts.port = Some(parse_u16(line)?);
        }
        "user" => {
            opts.user = Some(one_arg(line)?);
        }
        "identityfile" => {
            opts.identity_files.push(one_arg(line)?);
        }
        "certificatefile" => {
            opts.certificate_files.push(one_arg(line)?);
        }
        "identitiesonly" => {
            opts.identities_only = Some(parse_yes_no(line)?);
        }
        "stricthostkeychecking" => {
            opts.strict_host_key = Some(parse_strict(line)?);
        }
        "userknownhostsfile" => {
            opts.user_known_hosts = Some(one_arg(line)?);
        }
        "hashknownhosts" => {
            opts.hash_known_hosts = Some(parse_yes_no(line)?);
        }
        "localforward" => {
            opts.local_forwards.push(parse_local_forward(line)?);
        }
        "remoteforward" => {
            opts.remote_forwards.push(parse_remote_forward(line)?);
        }
        "forwardagent" => {
            opts.forward_agent = Some(parse_yes_no(line)?);
        }
        "forwardx11" => {
            opts.forward_x11 = Some(parse_yes_no(line)?);
        }
        "forwardx11trusted" => {
            opts.forward_x11_trusted = Some(parse_yes_no(line)?);
        }
        "requesttty" => {
            opts.request_tty = Some(parse_request_tty(line)?);
        }
        "loglevel" => {
            opts.log_level = Some(parse_log_level(line)?);
        }
        "ciphers" => {
            opts.ciphers = Some(resolve_algo_list(
                AlgoCategory::Cipher,
                args,
                line.line_no,
                "Ciphers",
            )?);
        }
        "macs" => {
            opts.macs = Some(resolve_algo_list(
                AlgoCategory::Mac,
                args,
                line.line_no,
                "MACs",
            )?);
        }
        "kexalgorithms" => {
            opts.kex_algorithms = Some(resolve_algo_list(
                AlgoCategory::Kex,
                args,
                line.line_no,
                "KexAlgorithms",
            )?);
        }
        "hostkeyalgorithms" => {
            opts.host_key_algorithms = Some(resolve_algo_list(
                AlgoCategory::HostKey,
                args,
                line.line_no,
                "HostKeyAlgorithms",
            )?);
        }
        "pubkeyacceptedalgorithms" | "pubkeyacceptedkeytypes" => {
            opts.pubkey_accepted_algorithms = Some(resolve_algo_list(
                AlgoCategory::PubkeyAccepted,
                args,
                line.line_no,
                "PubkeyAcceptedAlgorithms",
            )?);
        }
        "proxycommand" => {
            // The whole rest of the line is the command. The literal `none`
            // (case-insensitive) disables any inherited ProxyCommand.
            if args.is_empty() {
                return Err(ConfigError::BadValue {
                    line: line.line_no,
                    keyword: line.keyword.clone(),
                    msg: "ProxyCommand requires a command (or 'none')".into(),
                });
            }
            if args.len() == 1 && args[0].eq_ignore_ascii_case("none") {
                opts.proxy_command = None;
            } else {
                opts.proxy_command = Some(args.join(" "));
            }
        }
        "proxyjump" => {
            let v = one_arg(line)?;
            if v.eq_ignore_ascii_case("none") {
                opts.proxy_jump = None;
            } else {
                opts.proxy_jump = Some(v);
            }
        }
        "compression" => {
            let on = parse_yes_no(line)?;
            // `Compression yes` requires the `compress` feature: without it
            // the codec has no zlib implementation, so honouring the keyword
            // is impossible. Reject at parse time rather than silently
            // advertising `none` (strict mode — no parse-and-ignore).
            if on && !cfg!(feature = "compress") {
                return Err(ConfigError::Unsupported {
                    line: line.line_no,
                    msg: "Compression yes requires the `compress` feature, which is not \
                          compiled in"
                        .into(),
                });
            }
            opts.compression = Some(on);
        }
        "setenv" => {
            // OpenSSH accepts one or more NAME=VALUE tokens on a SetEnv line.
            if args.is_empty() {
                return Err(ConfigError::BadValue {
                    line: line.line_no,
                    keyword: line.keyword.clone(),
                    msg: "SetEnv requires at least one NAME=VALUE".into(),
                });
            }
            for tok in args {
                let (name, value) = tok.split_once('=').ok_or_else(|| ConfigError::BadValue {
                    line: line.line_no,
                    keyword: line.keyword.clone(),
                    msg: format!("expected NAME=VALUE, got {tok:?}"),
                })?;
                if name.is_empty() {
                    return Err(ConfigError::BadValue {
                        line: line.line_no,
                        keyword: line.keyword.clone(),
                        msg: format!("empty variable name in {tok:?}"),
                    });
                }
                opts.set_env.push((name.to_string(), value.to_string()));
            }
        }
        "sendenv" => {
            if args.is_empty() {
                return Err(ConfigError::BadValue {
                    line: line.line_no,
                    keyword: line.keyword.clone(),
                    msg: "SendEnv requires at least one pattern".into(),
                });
            }
            for pat in args {
                opts.send_env.push(pat.clone());
            }
        }
        "connecttimeout" => {
            let secs = parse_u32(line)?;
            if secs == 0 {
                return Err(ConfigError::BadValue {
                    line: line.line_no,
                    keyword: line.keyword.clone(),
                    msg: "ConnectTimeout must be a positive number of seconds".into(),
                });
            }
            opts.connect_timeout = Some(secs);
        }
        "serveraliveinterval" => {
            opts.server_alive_interval = Some(parse_u32(line)?);
        }
        "serveralivecountmax" => {
            opts.server_alive_count_max = Some(parse_u32(line)?);
        }
        "tcpkeepalive" => {
            opts.tcp_keep_alive = Some(parse_yes_no(line)?);
        }
        "addkeystoagent" => {
            // OpenSSH accepts yes/no/confirm/ask. We can honour yes/no
            // (push or don't push the loaded key to the agent); the
            // interactive confirm/ask variants need a UI we don't have,
            // so reject rather than silently downgrade.
            let s = one_arg(line)?.to_ascii_lowercase();
            match s.as_str() {
                "yes" | "true" | "on" => opts.add_keys_to_agent = Some(true),
                "no" | "false" | "off" => opts.add_keys_to_agent = Some(false),
                "confirm" | "ask" => {
                    return Err(ConfigError::Unsupported {
                        line: line.line_no,
                        msg: "AddKeysToAgent confirm/ask requires interactive confirmation, \
                              which is not implemented"
                            .into(),
                    });
                }
                other => {
                    return Err(ConfigError::BadValue {
                        line: line.line_no,
                        keyword: line.keyword.clone(),
                        msg: format!("expected yes/no/confirm/ask, got {other:?}"),
                    });
                }
            }
        }
        "preferredauthentications" => {
            opts.preferred_authentications = Some(parse_preferred_auth(line)?);
        }
        "pubkeyauthentication" => {
            opts.pubkey_authentication = Some(parse_yes_no(line)?);
        }
        "numberofpasswordprompts" => {
            opts.number_of_password_prompts = Some(parse_u32(line)?);
        }
        "batchmode" => {
            opts.batch_mode = Some(parse_yes_no(line)?);
        }
        "exitonforwardfailure" => {
            opts.exit_on_forward_failure = Some(parse_yes_no(line)?);
        }
        "clearallforwardings" => {
            opts.clear_all_forwardings = Some(parse_yes_no(line)?);
        }
        "dynamicforward" => {
            opts.dynamic_forwards.push(parse_dynamic_forward(line)?);
        }
        "gatewayports" => {
            let s = one_arg(line)?.to_ascii_lowercase();
            opts.gateway_ports = Some(match s.as_str() {
                "no" | "false" | "off" => GatewayPorts::No,
                "yes" | "true" | "on" => GatewayPorts::Yes,
                "clientspecified" => GatewayPorts::ClientSpecified,
                other => {
                    return Err(ConfigError::BadValue {
                        line: line.line_no,
                        keyword: line.keyword.clone(),
                        msg: format!("expected no/yes/clientspecified, got {other:?}"),
                    });
                }
            });
        }
        "addressfamily" => {
            let s = one_arg(line)?.to_ascii_lowercase();
            opts.address_family = Some(match s.as_str() {
                "any" => AddressFamily::Any,
                "inet" => AddressFamily::Inet,
                "inet6" => AddressFamily::Inet6,
                other => {
                    return Err(ConfigError::BadValue {
                        line: line.line_no,
                        keyword: line.keyword.clone(),
                        msg: format!("expected any/inet/inet6, got {other:?}"),
                    });
                }
            });
        }
        "bindaddress" => {
            opts.bind_address = Some(one_arg(line)?);
        }
        "identityagent" => {
            let v = one_arg(line)?;
            opts.identity_agent = Some(if v.eq_ignore_ascii_case("none") {
                IdentityAgent::None
            } else {
                IdentityAgent::Path(v)
            });
        }
        "controlmaster" => {
            let s = one_arg(line)?.to_ascii_lowercase();
            opts.control_master = Some(match s.as_str() {
                "no" | "false" | "off" => ControlMaster::No,
                "yes" | "true" | "on" => ControlMaster::Yes,
                "auto" => ControlMaster::Auto,
                // `ask` / `autoask` need an interactive confirmation path
                // we don't have. Reject rather than silently treat as
                // `yes` — the user explicitly asked to be prompted.
                "ask" | "autoask" => {
                    return Err(ConfigError::Unsupported {
                        line: line.line_no,
                        msg: "ControlMaster ask/autoask requires interactive confirmation, \
                              which is not implemented"
                            .into(),
                    });
                }
                other => {
                    return Err(ConfigError::BadValue {
                        line: line.line_no,
                        keyword: line.keyword.clone(),
                        msg: format!("expected no/yes/auto, got {other:?}"),
                    });
                }
            });
        }
        "controlpath" => {
            // The whole rest of the line (after token re-join) is the path;
            // `%`-token and `~` expansion happen at the honoring site.
            // `none` (case-insensitive) disables multiplexing.
            let v = one_arg(line)?;
            if v.eq_ignore_ascii_case("none") {
                opts.control_path = None;
            } else {
                opts.control_path = Some(v);
            }
        }
        "controlpersist" => {
            opts.control_persist = Some(parse_control_persist(line)?);
        }
        "obscurekeystroketiming" => {
            opts.obscure_keystroke_timing = Some(parse_obscure_keystroke_timing(line)?);
        }
        "casignaturealgorithms" => {
            opts.ca_signature_algorithms = Some(resolve_algo_list(
                AlgoCategory::CaSignature,
                args,
                line.line_no,
                &line.keyword,
            )?);
        }
        _ => {
            return Err(ConfigError::UnknownKeyword {
                line: line.line_no,
                keyword: kw.to_string(),
            });
        }
    }
    let _ = args;
    Ok(())
}

/// First-match-wins merge of `src` over `dst`. Scalars only overwrite if
/// `dst` had `None`; list fields concatenate.
fn merge_into(dst: &mut ClientOptions, src: &ClientOptions) {
    macro_rules! take_scalar {
        ($field:ident) => {
            if dst.$field.is_none() {
                dst.$field = src.$field.clone();
            }
        };
    }
    take_scalar!(host_name);
    take_scalar!(port);
    take_scalar!(user);
    take_scalar!(identities_only);
    take_scalar!(strict_host_key);
    take_scalar!(user_known_hosts);
    take_scalar!(hash_known_hosts);
    take_scalar!(forward_agent);
    take_scalar!(forward_x11);
    take_scalar!(forward_x11_trusted);
    take_scalar!(request_tty);
    take_scalar!(log_level);
    // Algorithm overrides are first-match-wins scalars: the whole resolved
    // list from the earliest matching block wins (OpenSSH semantics — a
    // later block's Ciphers does not append to an earlier block's).
    take_scalar!(ciphers);
    take_scalar!(macs);
    take_scalar!(kex_algorithms);
    take_scalar!(host_key_algorithms);
    take_scalar!(pubkey_accepted_algorithms);
    take_scalar!(ca_signature_algorithms);
    take_scalar!(proxy_command);
    take_scalar!(proxy_jump);
    take_scalar!(compression);
    take_scalar!(connect_timeout);
    take_scalar!(server_alive_interval);
    take_scalar!(server_alive_count_max);
    take_scalar!(tcp_keep_alive);
    take_scalar!(add_keys_to_agent);
    take_scalar!(preferred_authentications);
    take_scalar!(pubkey_authentication);
    take_scalar!(number_of_password_prompts);
    take_scalar!(batch_mode);
    take_scalar!(exit_on_forward_failure);
    take_scalar!(clear_all_forwardings);
    take_scalar!(gateway_ports);
    take_scalar!(address_family);
    take_scalar!(bind_address);
    take_scalar!(identity_agent);
    take_scalar!(control_master);
    take_scalar!(control_path);
    take_scalar!(control_persist);
    take_scalar!(obscure_keystroke_timing);
    dst.identity_files
        .extend(src.identity_files.iter().cloned());
    dst.certificate_files
        .extend(src.certificate_files.iter().cloned());
    dst.local_forwards
        .extend(src.local_forwards.iter().cloned());
    dst.remote_forwards
        .extend(src.remote_forwards.iter().cloned());
    dst.dynamic_forwards
        .extend(src.dynamic_forwards.iter().cloned());
    dst.set_env.extend(src.set_env.iter().cloned());
    dst.send_env.extend(src.send_env.iter().cloned());
}

fn one_arg(line: &ParsedLine) -> Result<String, ConfigError> {
    if line.args.len() != 1 {
        return Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected 1 value, got {}", line.args.len()),
        });
    }
    Ok(line.args[0].clone())
}

fn parse_u16(line: &ParsedLine) -> Result<u16, ConfigError> {
    let s = one_arg(line)?;
    s.parse::<u16>().map_err(|_| ConfigError::BadValue {
        line: line.line_no,
        keyword: line.keyword.clone(),
        msg: format!("expected a port number, got {s:?}"),
    })
}

fn parse_u32(line: &ParsedLine) -> Result<u32, ConfigError> {
    let s = one_arg(line)?;
    s.parse::<u32>().map_err(|_| ConfigError::BadValue {
        line: line.line_no,
        keyword: line.keyword.clone(),
        msg: format!("expected a non-negative integer, got {s:?}"),
    })
}

/// Parse a `PreferredAuthentications` list. OpenSSH takes a comma-separated
/// list of method names. We recognise the standard set but only honour the
/// ones the client implements; a list that names *none* of the
/// implementable methods is rejected so the directive can never look like it
/// took effect while silently leaving no usable method.
fn parse_preferred_auth(line: &ParsedLine) -> Result<Vec<String>, ConfigError> {
    // The list may arrive as one comma-joined token or several whitespace-
    // separated tokens; normalise both.
    let mut methods: Vec<String> = Vec::new();
    for tok in &line.args {
        for m in tok.split(',') {
            let m = m.trim();
            if !m.is_empty() {
                methods.push(m.to_ascii_lowercase());
            }
        }
    }
    if methods.is_empty() {
        return Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: "PreferredAuthentications requires at least one method".into(),
        });
    }
    // Known OpenSSH method names. `gssapi-with-mic` / `hostbased` are
    // understood-but-unimplemented: we tolerate them in the list (so a
    // shared config doesn't break) but they contribute nothing usable.
    const KNOWN: &[&str] = &[
        "publickey",
        "password",
        "keyboard-interactive",
        "none",
        "gssapi-with-mic",
        "hostbased",
    ];
    const IMPLEMENTED: &[&str] = &["publickey", "password", "none"];
    for m in &methods {
        if !KNOWN.contains(&m.as_str()) {
            return Err(ConfigError::BadValue {
                line: line.line_no,
                keyword: line.keyword.clone(),
                msg: format!("unknown authentication method {m:?}"),
            });
        }
    }
    if !methods.iter().any(|m| IMPLEMENTED.contains(&m.as_str())) {
        return Err(ConfigError::Unsupported {
            line: line.line_no,
            msg: "PreferredAuthentications names only methods this client does not \
                  implement (publickey/password are the supported methods)"
                .into(),
        });
    }
    Ok(methods)
}

/// Parse a `DynamicForward` argument: a single `[bind:]port` token.
fn parse_dynamic_forward(line: &ParsedLine) -> Result<DynamicForwardSpec, ConfigError> {
    if line.args.len() != 1 {
        return Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected 1 token ([bind:]port), got {}", line.args.len()),
        });
    }
    let (bind_addr, listen_port) = split_bind_port(&line.args[0], line)?;
    Ok(DynamicForwardSpec {
        bind_addr,
        listen_port,
    })
}

/// Parse a `ControlPersist` value: `yes` / `no` / `<N>` / `<N>[smh]`.
///
/// A bare integer is seconds. A trailing `s`/`m`/`h` suffix scales to
/// seconds (`m` ⇒ ×60, `h` ⇒ ×3600). A literal `0` means "no persist"
/// (≡ `no`), matching OpenSSH. Overflow on the multiply is rejected.
fn parse_control_persist(line: &ParsedLine) -> Result<ControlPersist, ConfigError> {
    let s = one_arg(line)?.to_ascii_lowercase();
    match s.as_str() {
        "no" | "false" | "off" => return Ok(ControlPersist::No),
        "yes" | "true" | "on" => return Ok(ControlPersist::Yes),
        _ => {}
    }
    let bad = |msg: String| ConfigError::BadValue {
        line: line.line_no,
        keyword: line.keyword.clone(),
        msg,
    };
    let (digits, scale): (&str, u64) = match s.as_bytes().last() {
        Some(b's') => (&s[..s.len() - 1], 1),
        Some(b'm') => (&s[..s.len() - 1], 60),
        Some(b'h') => (&s[..s.len() - 1], 3600),
        _ => (s.as_str(), 1),
    };
    if digits.is_empty() {
        return Err(bad(format!("expected yes/no/<N>[smh], got {s:?}")));
    }
    let n: u64 = digits
        .parse()
        .map_err(|_| bad(format!("expected yes/no/<N>[smh], got {s:?}")))?;
    let secs = n
        .checked_mul(scale)
        .ok_or_else(|| bad("ControlPersist duration overflows".into()))?;
    if secs == 0 {
        Ok(ControlPersist::No)
    } else {
        Ok(ControlPersist::Seconds(secs))
    }
}

/// Parse an `ObscureKeystrokeTiming` value: `yes` / `no` / `interval:<spec>`.
///
/// `yes` ⇒ on at the OpenSSH default (20 ms). `no` ⇒ off. `interval:<spec>`
/// ⇒ on with `<spec>` resolved to milliseconds: either a bare integer
/// (milliseconds, `interval:80`) or an OpenSSH time value with a unit suffix
/// (`interval:1s`, `interval:500ms`). A zero interval is rejected. STRICT:
/// anything malformed is a [`ConfigError::BadValue`].
fn parse_obscure_keystroke_timing(
    line: &ParsedLine,
) -> Result<ObscureKeystrokeTiming, ConfigError> {
    let raw = one_arg(line)?;
    let s = raw.to_ascii_lowercase();
    let bad = |msg: String| ConfigError::BadValue {
        line: line.line_no,
        keyword: line.keyword.clone(),
        msg,
    };
    match s.as_str() {
        "no" | "false" | "off" => return Ok(ObscureKeystrokeTiming::Off),
        "yes" | "true" | "on" => return Ok(ObscureKeystrokeTiming::default_on()),
        _ => {}
    }
    let Some(spec) = s.strip_prefix("interval:") else {
        return Err(bad(format!("expected yes/no/interval:<spec>, got {raw:?}")));
    };
    if spec.is_empty() {
        return Err(bad("interval: requires a value".into()));
    }
    // Resolve <spec> to milliseconds. Bare integer ⇒ ms. `ms` suffix ⇒ ms.
    // `s`/`m`/`h` suffixes ⇒ seconds/minutes/hours scaled to ms.
    let (digits, scale_ms): (&str, u64) = if let Some(d) = spec.strip_suffix("ms") {
        (d, 1)
    } else if let Some(d) = spec.strip_suffix('s') {
        (d, 1000)
    } else if let Some(d) = spec.strip_suffix('m') {
        (d, 60_000)
    } else if let Some(d) = spec.strip_suffix('h') {
        (d, 3_600_000)
    } else {
        (spec, 1)
    };
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return Err(bad(format!(
            "interval: expected <ms> or <N>[ms|s|m|h], got {spec:?}"
        )));
    }
    let n: u64 = digits
        .parse()
        .map_err(|_| bad(format!("interval: invalid number {spec:?}")))?;
    let ms = n
        .checked_mul(scale_ms)
        .ok_or_else(|| bad("interval: duration overflows".into()))?;
    if ms == 0 {
        return Err(bad("interval: must be greater than zero".into()));
    }
    let interval_ms = u32::try_from(ms).map_err(|_| bad("interval: too large".into()))?;
    Ok(ObscureKeystrokeTiming::On { interval_ms })
}

fn parse_yes_no(line: &ParsedLine) -> Result<bool, ConfigError> {
    let s = one_arg(line)?.to_ascii_lowercase();
    match s.as_str() {
        "yes" | "true" | "on" => Ok(true),
        "no" | "false" | "off" => Ok(false),
        _ => Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected yes/no, got {s:?}"),
        }),
    }
}

fn parse_strict(line: &ParsedLine) -> Result<StrictMode, ConfigError> {
    let s = one_arg(line)?.to_ascii_lowercase();
    match s.as_str() {
        "yes" => Ok(StrictMode::Yes),
        "no" | "off" => Ok(StrictMode::No),
        "accept-new" => Ok(StrictMode::AcceptNew),
        "ask" => Ok(StrictMode::Ask),
        _ => Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected yes/no/accept-new/ask/off, got {s:?}"),
        }),
    }
}

fn parse_request_tty(line: &ParsedLine) -> Result<RequestTty, ConfigError> {
    let s = one_arg(line)?.to_ascii_lowercase();
    match s.as_str() {
        "no" => Ok(RequestTty::No),
        "yes" => Ok(RequestTty::Yes),
        "force" => Ok(RequestTty::Force),
        "auto" => Ok(RequestTty::Auto),
        _ => Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected no/yes/force/auto, got {s:?}"),
        }),
    }
}

fn parse_log_level(line: &ParsedLine) -> Result<u8, ConfigError> {
    let s = one_arg(line)?.to_ascii_uppercase();
    match s.as_str() {
        "QUIET" | "FATAL" | "ERROR" | "INFO" => Ok(0),
        "VERBOSE" | "DEBUG" | "DEBUG1" => Ok(1),
        "DEBUG2" => Ok(2),
        "DEBUG3" => Ok(3),
        _ => Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected QUIET..DEBUG3, got {s:?}"),
        }),
    }
}

/// Parse a `LocalForward` argument list. OpenSSH accepts two whitespace-
/// separated tokens: `[bind:]port host:hostport`.
fn parse_local_forward(line: &ParsedLine) -> Result<LocalForwardSpec, ConfigError> {
    if line.args.len() != 2 {
        return Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected 2 tokens, got {}", line.args.len()),
        });
    }
    let (bind_addr, listen_port) = split_bind_port(&line.args[0], line)?;
    let (remote_host, remote_port) = split_host_port(&line.args[1], line)?;
    Ok(LocalForwardSpec {
        bind_addr,
        listen_port,
        remote_host,
        remote_port,
    })
}

/// Parse a `RemoteForward` argument list. Same shape as `LocalForward`.
fn parse_remote_forward(line: &ParsedLine) -> Result<RemoteForwardSpec, ConfigError> {
    if line.args.len() != 2 {
        return Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected 2 tokens, got {}", line.args.len()),
        });
    }
    let (bind_addr, remote_port) = split_bind_port(&line.args[0], line)?;
    let (local_host, local_port) = split_host_port(&line.args[1], line)?;
    Ok(RemoteForwardSpec {
        bind_addr,
        remote_port,
        local_host,
        local_port,
    })
}

/// `[bind:]port` → `(Some("bind"), port)` or `(None, port)`. IPv6 literal
/// addresses must be bracketed (`[::1]:port`).
fn split_bind_port(s: &str, line: &ParsedLine) -> Result<(Option<String>, u16), ConfigError> {
    if let Some(rest) = s.strip_prefix('[') {
        // `[addr]:port`
        if let Some((addr, port)) = rest.split_once("]:") {
            let port = port.parse::<u16>().map_err(|_| ConfigError::BadValue {
                line: line.line_no,
                keyword: line.keyword.clone(),
                msg: format!("bad port in {s:?}"),
            })?;
            return Ok((Some(addr.to_string()), port));
        }
        return Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("malformed bracketed bind:port {s:?}"),
        });
    }
    match s.rsplit_once(':') {
        Some((addr, port)) => {
            let port = port.parse::<u16>().map_err(|_| ConfigError::BadValue {
                line: line.line_no,
                keyword: line.keyword.clone(),
                msg: format!("bad port in {s:?}"),
            })?;
            Ok((Some(addr.to_string()), port))
        }
        None => {
            let port = s.parse::<u16>().map_err(|_| ConfigError::BadValue {
                line: line.line_no,
                keyword: line.keyword.clone(),
                msg: format!("expected port or addr:port, got {s:?}"),
            })?;
            Ok((None, port))
        }
    }
}

/// `host:port` or `[host]:port`.
fn split_host_port(s: &str, line: &ParsedLine) -> Result<(String, u16), ConfigError> {
    if let Some(rest) = s.strip_prefix('[') {
        if let Some((addr, port)) = rest.split_once("]:") {
            let port = port.parse::<u16>().map_err(|_| ConfigError::BadValue {
                line: line.line_no,
                keyword: line.keyword.clone(),
                msg: format!("bad port in {s:?}"),
            })?;
            return Ok((addr.to_string(), port));
        }
        return Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("malformed bracketed host:port {s:?}"),
        });
    }
    match s.rsplit_once(':') {
        Some((host, port)) => {
            let port = port.parse::<u16>().map_err(|_| ConfigError::BadValue {
                line: line.line_no,
                keyword: line.keyword.clone(),
                msg: format!("bad port in {s:?}"),
            })?;
            Ok((host.to_string(), port))
        }
        None => Err(ConfigError::BadValue {
            line: line.line_no,
            keyword: line.keyword.clone(),
            msg: format!("expected host:port, got {s:?}"),
        }),
    }
}

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

    #[test]
    fn parse_minimal() {
        let src = "\
Host gw
  HostName 198.51.100.7
  User admin
  Port 2222
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(eff.host_name.as_deref(), Some("198.51.100.7"));
        assert_eq!(eff.port, Some(2222));
        assert_eq!(eff.user.as_deref(), Some("admin"));
    }

    #[test]
    fn algorithm_keywords_parse() {
        let src = "\
Host gw
  Ciphers aes128-ctr,aes256-ctr
  MACs hmac-sha2-256
  KexAlgorithms curve25519-sha256
  HostKeyAlgorithms ssh-ed25519
  PubkeyAcceptedAlgorithms ssh-ed25519,rsa-sha2-512
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(
            eff.ciphers.as_deref(),
            Some(&["aes128-ctr".to_string(), "aes256-ctr".to_string()][..])
        );
        assert_eq!(
            eff.macs.as_deref(),
            Some(&["hmac-sha2-256".to_string()][..])
        );
        assert_eq!(
            eff.kex_algorithms.as_deref(),
            Some(&["curve25519-sha256".to_string()][..])
        );
        assert_eq!(
            eff.host_key_algorithms.as_deref(),
            Some(&["ssh-ed25519".to_string()][..])
        );
        assert_eq!(
            eff.pubkey_accepted_algorithms.as_deref(),
            Some(&["ssh-ed25519".to_string(), "rsa-sha2-512".to_string()][..])
        );
    }

    #[test]
    fn host_key_algorithms_plus_ssh_rsa_accepted() {
        // `HostKeyAlgorithms +ssh-rsa` used to be rejected; it now resolves to
        // the defaults plus the legacy SHA-1 name appended (opt-in).
        let src = "Host legacy\n  HostKeyAlgorithms +ssh-rsa\n";
        let cfg = SshClientConfig::parse(src).expect("+ssh-rsa must parse");
        let eff = cfg.lookup("legacy");
        let list = eff
            .host_key_algorithms
            .as_deref()
            .expect("host_key_algorithms set");
        assert!(
            list.iter().any(|n| n == "ssh-rsa"),
            "+ssh-rsa must appear in the resolved list: {list:?}"
        );
        assert!(
            list.iter().any(|n| n == "ssh-ed25519"),
            "defaults must be preserved ahead of the appended legacy name"
        );
    }

    #[test]
    fn host_key_algorithms_bare_ssh_rsa_accepted() {
        // A bare replace naming only ssh-rsa is also accepted (explicit opt-in).
        let src = "Host legacy\n  HostKeyAlgorithms ssh-rsa\n";
        let cfg = SshClientConfig::parse(src).expect("bare ssh-rsa must parse");
        let eff = cfg.lookup("legacy");
        assert_eq!(
            eff.host_key_algorithms.as_deref(),
            Some(&["ssh-rsa".to_string()][..])
        );
    }

    #[test]
    fn pubkey_accepted_ssh_rsa_still_rejected() {
        // The SHA-1 opt-in is HostKey-only; pubkey auth must still reject it.
        let src = "Host legacy\n  PubkeyAcceptedAlgorithms +ssh-rsa\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }

    #[test]
    fn unknown_cipher_rejected_with_line() {
        let src = "Host gw\n  Ciphers totally-bogus\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        match err {
            ConfigError::BadValue { line, keyword, msg } => {
                assert_eq!(line, 2);
                assert_eq!(keyword, "Ciphers");
                assert!(msg.contains("totally-bogus"));
            }
            other => panic!("expected BadValue, got {other:?}"),
        }
    }

    #[test]
    fn proxy_command_parses() {
        let src = "\
Host gw
  ProxyCommand /usr/bin/nc -X connect -x proxy:3128 %h %p
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(
            eff.proxy_command.as_deref(),
            Some("/usr/bin/nc -X connect -x proxy:3128 %h %p")
        );
    }

    #[test]
    fn proxy_command_none_clears() {
        let src = "\
Host gw
  ProxyCommand none
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("gw").proxy_command, None);
    }

    #[test]
    fn proxy_command_empty_errors() {
        // `ProxyCommand` with no argument is a config error.
        let src = "ProxyCommand\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        match err {
            ConfigError::BadValue { line, keyword, .. } => {
                assert_eq!(line, 1);
                assert_eq!(keyword, "proxycommand");
            }
            other => panic!("expected BadValue, got {other:?}"),
        }
    }

    #[test]
    fn proxy_jump_parses() {
        let src = "\
Host target
  ProxyJump user@bastion:2222,hop2
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(
            cfg.lookup("target").proxy_jump.as_deref(),
            Some("user@bastion:2222,hop2")
        );
    }

    #[test]
    fn proxy_jump_none_clears() {
        let src = "\
Host target
  ProxyJump none
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("target").proxy_jump, None);
    }

    #[test]
    fn casignaturealgorithms_accepted() {
        let src = "Host gw\n  CASignatureAlgorithms ssh-ed25519,rsa-sha2-512\n";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(
            eff.ca_signature_algorithms.as_deref(),
            Some(["ssh-ed25519".to_string(), "rsa-sha2-512".to_string()].as_slice())
        );
    }

    #[test]
    fn casignaturealgorithms_rejects_plain_ssh_rsa() {
        // Plain SHA-1 ssh-rsa is not a valid CA signature algorithm.
        let src = "Host gw\n  CASignatureAlgorithms ssh-rsa\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { line: 2, .. }));
    }

    #[test]
    fn algorithms_first_match_wins() {
        // First matching block's Ciphers wins; a later block does not append.
        let src = "\
Host gw
  Ciphers aes128-ctr
Host *
  Ciphers aes256-ctr
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(
            eff.ciphers.as_deref(),
            Some(&["aes128-ctr".to_string()][..])
        );
    }

    #[test]
    fn global_block_applies() {
        let src = "\
User globaluser
IdentitiesOnly yes
Host gw
  Port 2222
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(eff.user.as_deref(), Some("globaluser"));
        assert_eq!(eff.port, Some(2222));
        assert_eq!(eff.identities_only, Some(true));
    }

    #[test]
    fn first_match_wins_for_scalars() {
        // Two matching blocks; the FIRST set wins.
        let src = "\
Host *.example.com
  User firstuser
Host *
  User otheruser
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("host.example.com");
        assert_eq!(eff.user.as_deref(), Some("firstuser"));
    }

    #[test]
    fn identity_files_cumulative() {
        let src = "\
Host *
  IdentityFile ~/.ssh/id_a
Host gw
  IdentityFile ~/.ssh/id_b
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(eff.identity_files, vec!["~/.ssh/id_a", "~/.ssh/id_b"]);
    }

    #[test]
    fn local_forward_parses() {
        let src = "\
Host gw
  LocalForward 8080 example.com:80
  LocalForward 127.0.0.1:9090 backend:443
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(eff.local_forwards.len(), 2);
        assert_eq!(eff.local_forwards[0].bind_addr, None);
        assert_eq!(eff.local_forwards[0].listen_port, 8080);
        assert_eq!(eff.local_forwards[0].remote_host, "example.com");
        assert_eq!(eff.local_forwards[0].remote_port, 80);
        assert_eq!(
            eff.local_forwards[1].bind_addr.as_deref(),
            Some("127.0.0.1")
        );
        assert_eq!(eff.local_forwards[1].listen_port, 9090);
    }

    #[test]
    fn ipv6_bracketed_bind() {
        let src = "\
Host gw
  LocalForward [::1]:8080 example.com:80
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(eff.local_forwards[0].bind_addr.as_deref(), Some("::1"));
        assert_eq!(eff.local_forwards[0].listen_port, 8080);
    }

    #[test]
    fn negated_host_excludes() {
        let src = "\
Host *.example.com !secret.example.com
  User foo
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("ok.example.com").user.as_deref(), Some("foo"));
        assert_eq!(cfg.lookup("secret.example.com").user, None);
    }

    #[test]
    fn unknown_keyword_errors() {
        let src = "Host gw\n  CompressionLevel 9\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        match err {
            ConfigError::UnknownKeyword { keyword, line } => {
                assert_eq!(keyword, "compressionlevel");
                assert_eq!(line, 2);
            }
            _ => panic!("wrong error: {err:?}"),
        }
    }

    #[test]
    fn strict_host_key_values() {
        for (s, want) in [
            ("yes", StrictMode::Yes),
            ("no", StrictMode::No),
            ("off", StrictMode::No),
            ("accept-new", StrictMode::AcceptNew),
            ("ask", StrictMode::Ask),
        ] {
            let src = format!("StrictHostKeyChecking {s}\n");
            let cfg = SshClientConfig::parse(&src).unwrap();
            assert_eq!(cfg.lookup("anything").strict_host_key, Some(want));
        }
    }

    #[test]
    fn request_tty_values() {
        for (s, want) in [
            ("no", RequestTty::No),
            ("yes", RequestTty::Yes),
            ("force", RequestTty::Force),
            ("auto", RequestTty::Auto),
        ] {
            let src = format!("RequestTTY {s}\n");
            let cfg = SshClientConfig::parse(&src).unwrap();
            assert_eq!(cfg.lookup("anything").request_tty, Some(want));
        }
    }

    #[test]
    fn equals_separator_accepted() {
        let src = "Host gw\n  Port=2222\n";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("gw").port, Some(2222));
    }

    // ----- W4 modern-keyword tests --------------------------------------

    #[cfg(feature = "compress")]
    #[test]
    fn compression_parses_with_feature() {
        let cfg = SshClientConfig::parse("Compression yes\n").unwrap();
        assert_eq!(cfg.lookup("h").compression, Some(true));
        let cfg = SshClientConfig::parse("Compression no\n").unwrap();
        assert_eq!(cfg.lookup("h").compression, Some(false));
    }

    #[cfg(not(feature = "compress"))]
    #[test]
    fn compression_yes_unsupported_without_feature() {
        // `Compression no` still parses (nothing to honour); `yes` rejects.
        let cfg = SshClientConfig::parse("Compression no\n").unwrap();
        assert_eq!(cfg.lookup("h").compression, Some(false));
        let err = SshClientConfig::parse("Compression yes\n").unwrap_err();
        assert!(matches!(err, ConfigError::Unsupported { .. }));
    }

    #[test]
    fn set_env_parses_multiple() {
        let src = "Host gw\n  SetEnv FOO=bar BAZ=qux\n  SetEnv LANG=C\n";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(
            eff.set_env,
            vec![
                ("FOO".to_string(), "bar".to_string()),
                ("BAZ".to_string(), "qux".to_string()),
                ("LANG".to_string(), "C".to_string()),
            ]
        );
    }

    #[test]
    fn set_env_rejects_missing_equals() {
        let err = SshClientConfig::parse("SetEnv NOTANENV\n").unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }

    #[test]
    fn send_env_parses() {
        let src = "Host gw\n  SendEnv LANG LC_*\n  SendEnv TERM\n";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("gw").send_env, vec!["LANG", "LC_*", "TERM"]);
    }

    #[test]
    fn connect_timeout_parses_and_rejects_zero() {
        let cfg = SshClientConfig::parse("ConnectTimeout 10\n").unwrap();
        assert_eq!(cfg.lookup("h").connect_timeout, Some(10));
        let err = SshClientConfig::parse("ConnectTimeout 0\n").unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }

    #[test]
    fn server_alive_parses() {
        let src = "ServerAliveInterval 15\nServerAliveCountMax 4\n";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("h");
        assert_eq!(eff.server_alive_interval, Some(15));
        assert_eq!(eff.server_alive_count_max, Some(4));
    }

    #[test]
    fn tcp_keep_alive_parses() {
        let cfg = SshClientConfig::parse("TCPKeepAlive no\n").unwrap();
        assert_eq!(cfg.lookup("h").tcp_keep_alive, Some(false));
    }

    #[test]
    fn add_keys_to_agent_yes_no() {
        assert_eq!(
            SshClientConfig::parse("AddKeysToAgent yes\n")
                .unwrap()
                .lookup("h")
                .add_keys_to_agent,
            Some(true)
        );
        assert_eq!(
            SshClientConfig::parse("AddKeysToAgent no\n")
                .unwrap()
                .lookup("h")
                .add_keys_to_agent,
            Some(false)
        );
    }

    #[test]
    fn add_keys_to_agent_confirm_unsupported() {
        for v in ["confirm", "ask"] {
            let err = SshClientConfig::parse(&format!("AddKeysToAgent {v}\n")).unwrap_err();
            assert!(
                matches!(err, ConfigError::Unsupported { .. }),
                "expected Unsupported for {v}, got {err:?}"
            );
        }
    }

    #[test]
    fn preferred_authentications_parses_and_orders() {
        let cfg = SshClientConfig::parse("PreferredAuthentications password,publickey\n").unwrap();
        assert_eq!(
            cfg.lookup("h").preferred_authentications.as_deref(),
            Some(&["password".to_string(), "publickey".to_string()][..])
        );
    }

    #[test]
    fn preferred_authentications_only_unimplementable_unsupported() {
        let err = SshClientConfig::parse("PreferredAuthentications gssapi-with-mic,hostbased\n")
            .unwrap_err();
        assert!(matches!(err, ConfigError::Unsupported { .. }));
    }

    #[test]
    fn preferred_authentications_unknown_method_rejected() {
        let err = SshClientConfig::parse("PreferredAuthentications quantum\n").unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }

    #[test]
    fn pubkey_authentication_parses() {
        let cfg = SshClientConfig::parse("PubkeyAuthentication no\n").unwrap();
        assert_eq!(cfg.lookup("h").pubkey_authentication, Some(false));
    }

    #[test]
    fn number_of_password_prompts_and_batchmode() {
        let cfg = SshClientConfig::parse("NumberOfPasswordPrompts 1\nBatchMode yes\n").unwrap();
        let eff = cfg.lookup("h");
        assert_eq!(eff.number_of_password_prompts, Some(1));
        assert_eq!(eff.batch_mode, Some(true));
    }

    #[test]
    fn exit_on_forward_failure_and_clear_all() {
        let cfg =
            SshClientConfig::parse("ExitOnForwardFailure yes\nClearAllForwardings yes\n").unwrap();
        let eff = cfg.lookup("h");
        assert_eq!(eff.exit_on_forward_failure, Some(true));
        assert_eq!(eff.clear_all_forwardings, Some(true));
    }

    #[test]
    fn dynamic_forward_parses() {
        let src = "Host gw\n  DynamicForward 1080\n  DynamicForward 127.0.0.1:1081\n";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(eff.dynamic_forwards.len(), 2);
        assert_eq!(eff.dynamic_forwards[0].bind_addr, None);
        assert_eq!(eff.dynamic_forwards[0].listen_port, 1080);
        assert_eq!(
            eff.dynamic_forwards[1].bind_addr.as_deref(),
            Some("127.0.0.1")
        );
        assert_eq!(eff.dynamic_forwards[1].listen_port, 1081);
    }

    #[test]
    fn gateway_ports_parses() {
        for (s, want) in [
            ("no", GatewayPorts::No),
            ("yes", GatewayPorts::Yes),
            ("clientspecified", GatewayPorts::ClientSpecified),
        ] {
            let cfg = SshClientConfig::parse(&format!("GatewayPorts {s}\n")).unwrap();
            assert_eq!(cfg.lookup("h").gateway_ports, Some(want));
        }
    }

    #[test]
    fn address_family_parses() {
        for (s, want) in [
            ("any", AddressFamily::Any),
            ("inet", AddressFamily::Inet),
            ("inet6", AddressFamily::Inet6),
        ] {
            let cfg = SshClientConfig::parse(&format!("AddressFamily {s}\n")).unwrap();
            assert_eq!(cfg.lookup("h").address_family, Some(want));
        }
        let err = SshClientConfig::parse("AddressFamily ipx\n").unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }

    #[test]
    fn bind_address_parses() {
        let cfg = SshClientConfig::parse("BindAddress 10.0.0.5\n").unwrap();
        assert_eq!(cfg.lookup("h").bind_address.as_deref(), Some("10.0.0.5"));
    }

    #[test]
    fn identity_agent_parses() {
        let cfg = SshClientConfig::parse("IdentityAgent none\n").unwrap();
        assert_eq!(cfg.lookup("h").identity_agent, Some(IdentityAgent::None));
        let cfg = SshClientConfig::parse("IdentityAgent /run/agent.sock\n").unwrap();
        assert_eq!(
            cfg.lookup("h").identity_agent,
            Some(IdentityAgent::Path("/run/agent.sock".to_string()))
        );
    }

    // ----- Match-block tests --------------------------------------------

    #[test]
    fn match_host_glob() {
        let src = "\
Match host *.example.com
  User alice
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("web.example.com").user.as_deref(), Some("alice"));
        assert_eq!(cfg.lookup("web.other.com").user, None);
    }

    #[test]
    fn control_master_values() {
        let cfg = SshClientConfig::parse("Host h\n  ControlMaster auto\n").unwrap();
        assert_eq!(cfg.lookup("h").control_master, Some(ControlMaster::Auto));
        let cfg = SshClientConfig::parse("Host h\n  ControlMaster yes\n").unwrap();
        assert_eq!(cfg.lookup("h").control_master, Some(ControlMaster::Yes));
        let cfg = SshClientConfig::parse("Host h\n  ControlMaster no\n").unwrap();
        assert_eq!(cfg.lookup("h").control_master, Some(ControlMaster::No));
    }

    #[test]
    fn control_master_ask_unsupported() {
        let err = SshClientConfig::parse("Host h\n  ControlMaster ask\n").unwrap_err();
        assert!(matches!(err, ConfigError::Unsupported { .. }));
        let err = SshClientConfig::parse("Host h\n  ControlMaster autoask\n").unwrap_err();
        assert!(matches!(err, ConfigError::Unsupported { .. }));
    }

    #[test]
    fn control_master_bad_value() {
        let err = SshClientConfig::parse("Host h\n  ControlMaster maybe\n").unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }

    #[test]
    fn control_path_none_disables() {
        let cfg = SshClientConfig::parse("Host h\n  ControlPath none\n").unwrap();
        assert_eq!(cfg.lookup("h").control_path, None);
        let cfg = SshClientConfig::parse("Host h\n  ControlPath ~/.ssh/cm-%r@%h:%p\n").unwrap();
        assert_eq!(
            cfg.lookup("h").control_path.as_deref(),
            Some("~/.ssh/cm-%r@%h:%p")
        );
    }

    #[test]
    fn control_persist_values() {
        let p = |s: &str| {
            SshClientConfig::parse(&format!("Host h\n  ControlPersist {s}\n"))
                .unwrap()
                .lookup("h")
                .control_persist
        };
        assert_eq!(p("no"), Some(ControlPersist::No));
        assert_eq!(p("yes"), Some(ControlPersist::Yes));
        assert_eq!(p("30"), Some(ControlPersist::Seconds(30)));
        assert_eq!(p("30s"), Some(ControlPersist::Seconds(30)));
        assert_eq!(p("5m"), Some(ControlPersist::Seconds(300)));
        assert_eq!(p("2h"), Some(ControlPersist::Seconds(7200)));
        // `0` collapses to No, matching OpenSSH.
        assert_eq!(p("0"), Some(ControlPersist::No));
    }

    #[test]
    fn control_persist_bad_value() {
        let err = SshClientConfig::parse("Host h\n  ControlPersist soon\n").unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
        let err = SshClientConfig::parse("Host h\n  ControlPersist 10x\n").unwrap_err();
        assert!(matches!(err, ConfigError::BadValue { .. }));
    }

    #[test]
    fn match_negated_host() {
        let src = "\
Match host *.example.com,!internal.example.com
  User alice
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("web.example.com").user.as_deref(), Some("alice"));
        assert_eq!(cfg.lookup("internal.example.com").user, None);
    }

    #[test]
    fn match_user_combined_with_host() {
        let src = "\
Match host *.example.com user alice
  Port 2222
";
        let cfg = SshClientConfig::parse(src).unwrap();
        // No user supplied → does not match.
        assert_eq!(cfg.lookup("web.example.com").port, None);
        // Wrong user → does not match.
        let ctx = MatchContext {
            host: "web.example.com",
            original_host: None,
            user: Some("bob"),
            local_user: None,
            ..MatchContext::default()
        };
        assert_eq!(cfg.lookup_with(ctx).port, None);
        // Right user → matches.
        let ctx = MatchContext {
            host: "web.example.com",
            original_host: None,
            user: Some("alice"),
            local_user: None,
            ..MatchContext::default()
        };
        assert_eq!(cfg.lookup_with(ctx).port, Some(2222));
    }

    #[test]
    fn match_all_matches_everything() {
        let src = "\
Match all
  Port 4242
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("anything").port, Some(4242));
        assert_eq!(cfg.lookup("other").port, Some(4242));
    }

    #[test]
    fn match_canonical_never_matches_in_first_pass() {
        let src = "\
Match canonical
  Port 4242
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("anything").port, None);
    }

    #[test]
    fn match_final_never_matches_in_first_pass() {
        let src = "\
Match final
  Port 4242
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert_eq!(cfg.lookup("anything").port, None);
    }

    #[test]
    fn match_exec_disabled_by_default() {
        // Even with a command that would succeed on every platform, the
        // block must be silently skipped while the default policy is in
        // effect.
        let src = "\
Match exec true
  Port 4242
";
        let cfg = SshClientConfig::parse(src).unwrap();
        assert!(!cfg.is_match_exec_enabled());
        assert_eq!(cfg.lookup("anything").port, None);
    }

    #[cfg(unix)]
    #[test]
    fn match_exec_enabled_runs_command() {
        // Use the shell builtins `true` / `false` (not the `/bin/true`
        // / `/bin/false` binaries) so the test is portable: macOS
        // runners ship coreutils-style helpers at `/usr/bin/true` and
        // recent macOS images don't carry `/bin/true` at all, so an
        // absolute path here breaks `macos-latest` in CI. The `sh -c`
        // wrapper this code routes through always resolves the
        // builtins.
        let src = "\
Match exec true
  Port 4242
";
        let cfg = SshClientConfig::parse(src).unwrap().enable_match_exec(true);
        assert!(cfg.is_match_exec_enabled());
        assert_eq!(cfg.lookup("anything").port, Some(4242));

        let src_false = "\
Match exec false
  Port 4242
";
        let cfg = SshClientConfig::parse(src_false)
            .unwrap()
            .enable_match_exec(true);
        assert_eq!(cfg.lookup("anything").port, None);
    }

    #[test]
    fn match_originalhost_uses_pre_substitution_name() {
        let src = "\
Match originalhost prod
  Port 2200
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let ctx = MatchContext {
            host: "10.0.0.1",
            original_host: Some("prod"),
            user: None,
            local_user: None,
            ..MatchContext::default()
        };
        assert_eq!(cfg.lookup_with(ctx).port, Some(2200));
    }

    #[test]
    fn match_localuser() {
        let src = "\
Match localuser alice
  Port 2200
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let ctx = MatchContext {
            host: "h",
            original_host: None,
            user: None,
            local_user: Some("alice"),
            ..MatchContext::default()
        };
        assert_eq!(cfg.lookup_with(ctx).port, Some(2200));
        let ctx = MatchContext {
            host: "h",
            original_host: None,
            user: None,
            local_user: Some("bob"),
            ..MatchContext::default()
        };
        assert_eq!(cfg.lookup_with(ctx).port, None);
    }

    #[test]
    fn match_block_with_settings_parses() {
        // Sanity: settings inside a Match block actually get applied when
        // the block matches.
        let src = "\
Match host gw
  HostName 10.0.0.1
  Port 2222
  User admin
";
        let cfg = SshClientConfig::parse(src).unwrap();
        let eff = cfg.lookup("gw");
        assert_eq!(eff.host_name.as_deref(), Some("10.0.0.1"));
        assert_eq!(eff.port, Some(2222));
        assert_eq!(eff.user.as_deref(), Some("admin"));
    }

    #[test]
    fn match_unknown_criterion_errors() {
        let src = "Match address 1.2.3.4\n  Port 22\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        match err {
            ConfigError::BadValue { line, .. } => assert_eq!(line, 1),
            _ => panic!("wrong err: {err:?}"),
        }
    }

    #[test]
    fn match_empty_args_errors() {
        let src = "Match\n  Port 22\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        match err {
            ConfigError::BadValue { line, .. } => assert_eq!(line, 1),
            _ => panic!("wrong err: {err:?}"),
        }
    }

    // ----- ObscureKeystrokeTiming tests --------------------------------

    #[test]
    fn obscure_keystroke_timing_yes_defaults_to_20ms() {
        let cfg = SshClientConfig::parse("ObscureKeystrokeTiming yes\n").unwrap();
        assert_eq!(
            cfg.lookup("h").obscure_keystroke_timing,
            Some(ObscureKeystrokeTiming::On { interval_ms: 20 })
        );
    }

    #[test]
    fn obscure_keystroke_timing_no_is_off() {
        let cfg = SshClientConfig::parse("ObscureKeystrokeTiming no\n").unwrap();
        assert_eq!(
            cfg.lookup("h").obscure_keystroke_timing,
            Some(ObscureKeystrokeTiming::Off)
        );
    }

    #[test]
    fn obscure_keystroke_timing_interval_ms_integer() {
        let cfg = SshClientConfig::parse("ObscureKeystrokeTiming interval:80\n").unwrap();
        assert_eq!(
            cfg.lookup("h").obscure_keystroke_timing,
            Some(ObscureKeystrokeTiming::On { interval_ms: 80 })
        );
    }

    #[test]
    fn obscure_keystroke_timing_interval_time_units() {
        let cases = [
            ("interval:1s", 1000),
            ("interval:500ms", 500),
            ("interval:2m", 120_000),
        ];
        for (spec, want) in cases {
            let cfg = SshClientConfig::parse(&format!("ObscureKeystrokeTiming {spec}\n")).unwrap();
            assert_eq!(
                cfg.lookup("h").obscure_keystroke_timing,
                Some(ObscureKeystrokeTiming::On { interval_ms: want }),
                "spec {spec}"
            );
        }
    }

    #[test]
    fn obscure_keystroke_timing_unset_is_none() {
        let cfg = SshClientConfig::parse("Host h\n  Port 22\n").unwrap();
        assert_eq!(cfg.lookup("h").obscure_keystroke_timing, None);
    }

    #[test]
    fn obscure_keystroke_timing_malformed_is_bad_value() {
        for bad in [
            "ObscureKeystrokeTiming maybe\n",
            "ObscureKeystrokeTiming interval:\n",
            "ObscureKeystrokeTiming interval:abc\n",
            "ObscureKeystrokeTiming interval:0\n",
            "ObscureKeystrokeTiming interval:-5\n",
            "ObscureKeystrokeTiming 80\n",
        ] {
            let err = SshClientConfig::parse(bad).unwrap_err();
            assert!(
                matches!(err, ConfigError::BadValue { .. }),
                "input {bad:?} gave {err:?}"
            );
        }
    }

    #[test]
    fn obscure_keystroke_timing_default_helpers() {
        assert!(ObscureKeystrokeTiming::default_on().is_on());
        assert_eq!(ObscureKeystrokeTiming::default_on().interval_ms(), Some(20));
        assert!(!ObscureKeystrokeTiming::Off.is_on());
        assert_eq!(ObscureKeystrokeTiming::Off.interval_ms(), None);
    }

    #[test]
    fn append_layers_user_over_system() {
        // Mimics the CLI's default search path: the user file is loaded
        // first (higher precedence) and the system file appended below it.
        let mut user = SshClientConfig::parse("Host gw\n  Port 2200\n  IdentityFile /u/key\n")
            .expect("user parses");
        let system = SshClientConfig::parse("Host gw\n  Port 22\n  IdentityFile /etc/key\n")
            .expect("system parses");
        user.append(system);
        let eff = user.lookup("gw");
        // First-match-wins scalar: the user file's Port survives.
        assert_eq!(eff.port, Some(2200));
        // Cumulative list: user entry first, then system.
        assert_eq!(eff.identity_files, vec!["/u/key", "/etc/key"]);
    }

    // ----- Include-directive tests -------------------------------------

    #[cfg(feature = "std")]
    #[test]
    fn include_unsupported_in_string_parse() {
        // parse(&str) cannot resolve Include — it should surface a friendly
        // diagnostic rather than UnknownKeyword.
        let src = "Include /etc/ssh/somefile\n";
        let err = SshClientConfig::parse(src).unwrap_err();
        match err {
            ConfigError::Unsupported { line, msg } => {
                assert_eq!(line, 1);
                assert!(msg.contains("Include"), "msg = {msg}");
            }
            _ => panic!("wrong err: {err:?}"),
        }
    }

    #[cfg(feature = "std")]
    mod include_io {
        use super::*;
        use std::io::Write;
        use std::path::PathBuf;

        struct TempDir {
            path: PathBuf,
        }
        impl TempDir {
            fn new(prefix: &str) -> Self {
                use std::time::{SystemTime, UNIX_EPOCH};
                let nanos = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_nanos())
                    .unwrap_or(0);
                let pid = std::process::id();
                let path =
                    std::env::temp_dir().join(format!("puressh-cfg-client-{prefix}-{pid}-{nanos}"));
                std::fs::create_dir_all(&path).expect("create tempdir");
                Self { path }
            }
            fn write(&self, name: &str, body: &str) -> PathBuf {
                let p = self.path.join(name);
                if let Some(parent) = p.parent() {
                    std::fs::create_dir_all(parent).expect("mkdir");
                }
                let mut f = std::fs::File::create(&p).expect("create file");
                f.write_all(body.as_bytes()).expect("write file");
                p
            }
        }
        impl Drop for TempDir {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.path);
            }
        }

        #[test]
        fn include_pulls_in_settings() {
            let dir = TempDir::new("pull");
            let leaf = dir.write("leaf.cfg", "Port 4242\n");
            let root = dir.write(
                "root.cfg",
                &format!("Host gw\n  HostName 10.0.0.1\nInclude {}\n", leaf.display()),
            );
            let cfg = SshClientConfig::load(&root).unwrap();
            // Include is inside the `Host gw` block — its Port applies to gw.
            assert_eq!(cfg.lookup("gw").port, Some(4242));
            assert_eq!(cfg.lookup("gw").host_name.as_deref(), Some("10.0.0.1"));
        }

        #[test]
        fn include_glob_pulls_all_matches() {
            let dir = TempDir::new("glob");
            dir.write("conf.d/01.cfg", "Host gw\n  Port 2001\n");
            dir.write("conf.d/02.cfg", "Host gw\n  User u2\n");
            dir.write("conf.d/03.cfg", "Host gw\n  IdentityFile /tmp/k3\n");
            dir.write("conf.d/skip.txt", "Host gw\n  Port 9999\n");
            let root = dir.write(
                "root.cfg",
                &format!("Include {}/conf.d/*.cfg\n", dir.path.display()),
            );
            let cfg = SshClientConfig::load(&root).unwrap();
            let eff = cfg.lookup("gw");
            // First-match-wins on Port → 2001 (alphabetical 01.cfg sorts
            // first under our deterministic sort).
            assert_eq!(eff.port, Some(2001));
            assert_eq!(eff.user.as_deref(), Some("u2"));
            assert_eq!(eff.identity_files, vec!["/tmp/k3"]);
        }

        #[test]
        fn include_relative_to_containing_file() {
            // root.cfg lives in dir/; Include uses a bare filename, which
            // must be resolved against dir/ (not the CWD).
            let dir = TempDir::new("relative");
            dir.write("sibling.cfg", "Host gw\n  Port 7777\n");
            let root = dir.write("root.cfg", "Include sibling.cfg\n");
            let cfg = SshClientConfig::load(&root).unwrap();
            assert_eq!(cfg.lookup("gw").port, Some(7777));
        }

        #[test]
        fn include_missing_file_warned_not_fatal() {
            let dir = TempDir::new("missing");
            let root = dir.write(
                "root.cfg",
                &format!(
                    "Host gw\n  Port 22\nInclude {}/nope.cfg\n",
                    dir.path.display()
                ),
            );
            let cfg = SshClientConfig::load(&root).expect("missing include is non-fatal");
            assert_eq!(cfg.lookup("gw").port, Some(22));
        }

        #[test]
        fn include_circular_capped_at_16_depth() {
            // file A includes file A → infinite loop guarded by depth cap.
            let dir = TempDir::new("circ");
            // Path-stable file under the temp dir.
            let p = dir.path.join("loop.cfg");
            let body = format!("Include {}\n", p.display());
            std::fs::write(&p, body).expect("write loop.cfg");
            let err = SshClientConfig::load(&p).unwrap_err();
            match err {
                ConfigError::Syntax { msg, .. } => {
                    assert!(msg.contains("max depth"), "msg = {msg}");
                }
                _ => panic!("wrong err: {err:?}"),
            }
        }

        #[test]
        fn include_load_with_base_resolves_relative() {
            let dir = TempDir::new("loadbase");
            dir.write("inner.cfg", "Host gw\n  Port 9999\n");
            let src = "Include inner.cfg\n";
            let cfg = SshClientConfig::load_with_base(src, &dir.path).unwrap();
            assert_eq!(cfg.lookup("gw").port, Some(9999));
        }

        #[test]
        fn include_inside_match_block_only_applies_there() {
            // The Include sits inside a Host block — its settings should be
            // tagged onto that block, not bleed into a sibling block.
            let dir = TempDir::new("inblock");
            dir.write("only_gw.cfg", "Port 3300\n");
            let root = dir.write(
                "root.cfg",
                "Host gw\n  Include only_gw.cfg\nHost other\n  Port 22\n",
            );
            let cfg = SshClientConfig::load(&root).unwrap();
            assert_eq!(cfg.lookup("gw").port, Some(3300));
            assert_eq!(cfg.lookup("other").port, Some(22));
        }
    }
}