puressh 0.2.2

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
//! Shared helpers for the puressh client-side binaries (`ssh`, `sftp`,
//! `scp`). Each binary pulls this module in via
//! `#[path = "common.rs"] mod common;` so Cargo doesn't need a separate
//! `[[bin]]` entry for the helpers.
//!
//! Every helper is `#[allow(dead_code)]` at the function level, because no
//! single binary uses all of them — pulling the module in via `#[path]`
//! produces an independent copy per binary, and Rust's dead-code lint
//! complains otherwise.
//!
//! Helpers cluster around four concerns:
//!
//! - **User resolution** (`resolve_user`, `parse_userhost`,
//!   `parse_userhost_path`): turning command-line targets into
//!   `(user, host[, path])` triples consistently.
//! - **Credentials** (`load_identity`, `connect_agent_credentials`,
//!   `read_password_from_stdin`): collecting whatever the user gave us into
//!   the lib's [`ClientCredential`] vector.
//! - **Host-key policy** (`build_host_key_policy`, `default_known_hosts_path`,
//!   host-key prompts, `fingerprint_b64_sha256`, `base64_no_pad`): mapping
//!   OpenSSH-style `StrictHostKeyChecking` semantics into a
//!   [`HostKeyPolicy`].
//! - **`StrictMode`**: the four-valued enum that drives the policy choice.

#![allow(dead_code)]

use core::sync::atomic::{AtomicU8, Ordering};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use purecrypto::zeroize::Zeroizing;
use puressh::Error;
#[cfg(unix)]
use puressh::agent::{Agent, AgentHostKey};
use puressh::auth::ClientCredential;
use puressh::client::{HostKeyPolicy, KnownHostsPolicy, TofuAction};
use puressh::key::PrivateKey;
use puressh::known_hosts::KnownHosts;

#[cfg(unix)]
#[path = "unix_sys.rs"]
pub mod unix_sys;

// `StrictMode` lives in the lib so the config parser and the binaries share
// one definition. Re-exported here so existing `use common::StrictMode;`
// sites keep compiling unchanged.
pub use puressh::config::StrictMode;

/// Scrub bytes that are unsafe to emit to an interactive terminal, returning
/// a display-safe `String`.
///
/// Keyboard-interactive (RFC 4256) `name`, `instruction`, and `prompt`
/// strings arrive from the server DURING authentication — before any trust
/// decision — and are written verbatim to the operator's TTY. A malicious or
/// MITM server can embed ANSI/OSC control sequences (e.g. `ESC[...m`,
/// `ESC]0;...BEL`) to clear the screen, retitle the window, or spoof a prompt
/// to phish a password. Mirroring `sftp`'s `sanitize_terminal_bytes`, every
/// control byte — anything below `0x20` (including ESC `0x1b`, TAB `0x09`,
/// CR/LF) and DEL `0x7f` — is replaced with a `?` placeholder. Printable
/// non-ASCII characters (e.g. UTF-8 multibyte) pass through unchanged; only
/// the C0 control range and DEL are scrubbed.
pub fn sanitize_terminal_str(src: &str) -> String {
    src.chars()
        .map(|c| {
            if (c as u32) < 0x20 || c == '\u{7f}' {
                '?'
            } else {
                c
            }
        })
        .collect()
}

/// Pick the effective username for an SSH session, in OpenSSH's order of
/// precedence: explicit `-l user` wins; otherwise `user@host` syntax;
/// otherwise the calling user's `$USER`.
pub fn resolve_user(cli_user: Option<&str>, user_in_host: Option<&str>) -> Result<String, String> {
    if let Some(u) = cli_user {
        return Ok(u.to_string());
    }
    if let Some(u) = user_in_host {
        return Ok(u.to_string());
    }
    local_user_name().ok_or_else(|| "no user specified and the local user name is unknown".into())
}

/// The local user's name, as OpenSSH finds it: the password database entry
/// for our uid ($USER is not set in many containers and services), else
/// `$USER` / `$LOGNAME` (`%USERNAME%` on Windows).
pub fn local_user_name() -> Option<String> {
    #[cfg(unix)]
    if let Some((name, _)) = unix_sys::passwd_entry(unix_sys::getuid()) {
        return Some(name);
    }
    std::env::var("USER")
        .or_else(|_| std::env::var("LOGNAME"))
        .or_else(|_| std::env::var("USERNAME"))
        .ok()
        .filter(|u| !u.is_empty())
}

/// Split a `[user@]host` token. The host portion is whatever follows the
/// first `@` — for an unadorned `host`, the user half is `None`.
pub fn parse_userhost(target: &str) -> (Option<String>, String) {
    match target.split_once('@') {
        Some((u, h)) => (Some(u.to_string()), h.to_string()),
        None => (None, target.to_string()),
    }
}

/// Split a `[user@]host[:port]` CLI target. The host half goes through
/// [`puressh::config::parse_host_port`] so bracketed IPv6 literals
/// (`[2001:db8::1]:22`) and bare IPv6 literals (`2001:db8::1`, no
/// port) work. The returned port is `Some(p)` when the target carried
/// an explicit port (either `host:port` or `[v6]:port`), and `None`
/// when it didn't — callers decide whether `-p`/config/22 wins.
///
/// Returns `(user, host, port)`. `user` is `None` when the target had no
/// `@`. Errors are stringified for the bin's existing error-reporting
/// flow.
pub fn parse_target(target: &str) -> Result<(Option<String>, String, Option<u16>), String> {
    // `ssh://[user[;params]@]host[:port][/]` (OpenSSH 7.7+): no path, the
    // user percent-decoded.
    if let Some(rest) = target.strip_prefix("ssh://") {
        let rest = rest.strip_suffix('/').unwrap_or(rest);
        if rest.contains('/') {
            return Err(format!("{target}: a path is not allowed in an ssh:// URI"));
        }
        let (user, hostport) = match rest.rfind('@') {
            Some(i) => {
                let userinfo = rest[..i].split(';').next().unwrap_or("");
                (Some(uri_decode(userinfo)), &rest[i + 1..])
            }
            None => (None, rest),
        };
        let (_, host, port) = parse_target(hostport)?;
        return Ok((user.filter(|u| !u.is_empty()), host, port));
    }
    let (user, host_with_port) = parse_userhost(target);
    if host_with_port.is_empty() {
        return Err("empty host".into());
    }
    // We pass a sentinel default of 0 to parse_host_port and reconstruct
    // the "was a port given?" bit afterwards. Port 0 is reserved for
    // OS-assigned binds; it's never a meaningful connect target, so
    // using it as the "no port given" marker is unambiguous.
    // OpenSSH's cleanhostname(): brackets may surround any host, not only an
    // IPv6 literal (Ansible's sftp/scp pass `[192.0.2.1]`).
    if let Some((inner, after)) = host_with_port
        .strip_prefix('[')
        .and_then(|r| r.split_once(']'))
        && !inner.is_empty()
        && inner.parse::<std::net::Ipv6Addr>().is_err()
    {
        let port = match after {
            "" => None,
            a => Some(
                a.strip_prefix(':')
                    .and_then(|p| p.parse::<u16>().ok())
                    .ok_or_else(|| format!("bad port in {host_with_port:?}"))?,
            ),
        };
        return Ok((user, inner.to_string(), port));
    }
    let (host, port) =
        puressh::config::parse_host_port(&host_with_port, 0).map_err(|e| format!("{e}"))?;
    let port_opt = if port == 0 { None } else { Some(port) };
    Ok((user, host, port_opt))
}

/// `%XX`-decode a URI component.
fn uri_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%'
            && let Some(v) = b
                .get(i + 1..i + 3)
                .and_then(|h| std::str::from_utf8(h).ok())
                .and_then(|h| u8::from_str_radix(h, 16).ok())
        {
            out.push(v);
            i += 3;
            continue;
        }
        out.push(b[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Split a `[user@]host:path` token used by `scp(1)` / `sftp(1)` local-or-
/// remote arguments. Returns `None` when there's no `:` — that signals a
/// plain local path. The user prefix is optional (as in `host:path`).
///
/// We deliberately accept colons in the path portion (after the first one)
/// to match OpenSSH's behaviour; the caller decides whether to refuse them.
///
/// IPv6 literals must be bracketed in this position so the `:` separator
/// is unambiguous: `[user@][2001:db8::1]:/etc/motd`. A bare v6 host
/// (`2001:db8::1:/path`) is not accepted because there is no way to
/// distinguish the address from the path. This matches OpenSSH `scp(1)`
/// behaviour.
pub fn parse_userhost_path(target: &str) -> Option<(Option<String>, String, String)> {
    // Refuse a bare absolute path (`/foo/bar:baz` is local, not remote).
    if target.starts_with('/') {
        return None;
    }

    // Pull the optional `user@` prefix off the front first. We split on
    // the FIRST `@` because that matches the existing parse_userhost
    // semantics; v6 in brackets does not contain `@`.
    let (user, after_user) = parse_userhost(target);

    // Now look for the host/path separator. With a bracketed v6, the `]`
    // ends the host and the next char must be `:` then the path.
    let (host, path) = if let Some(rest) = after_user.strip_prefix('[') {
        // [host]:path — find the closing `]`. Everything in between is
        // the host (taken verbatim, no v6 validation here because scp is
        // happy to forward any string to its peer's resolver).
        let close = rest.find(']')?;
        let host = rest[..close].to_string();
        let after_bracket = &rest[close + 1..];
        let path = after_bracket.strip_prefix(':')?;
        (host, path.to_string())
    } else {
        // Plain `host:path` — split on the first `:`.
        let (h, p) = after_user.split_once(':')?;
        (h.to_string(), p.to_string())
    };

    if host.is_empty() {
        return None;
    }
    Some((user, host, path))
}

/// A handle on the controlling terminal for interactive prompts (host-key
/// confirmation, passwords, keyboard-interactive answers).
///
/// On Unix this is `/dev/tty` opened read+write — **not** stdin/stderr — so a
/// redirected stdin (`ssh host < data`, `yes | ssh …`, a CI job) can never
/// answer a prompt by accident, and a hostile server offering `password`
/// auth cannot harvest whatever the first lines of the user's stdin data
/// happen to be. This mirrors OpenSSH's `readpass.c`, which opens `/dev/tty`
/// and fails closed when it cannot.
///
/// On non-Unix platforms there is no `/dev/tty`; we fall back to stdin +
/// stderr, but only when stdin is actually a terminal.
struct PromptTty {
    input: Box<dyn Read>,
    output: Box<dyn Write>,
    /// Raw descriptor of the terminal, for `termios` echo control.
    #[cfg(unix)]
    fd: libc::c_int,
}

/// Open the controlling terminal for prompting. Returns `None` when there is
/// none (daemonised, stdin redirected on non-Unix, `setsid` without a tty…);
/// callers must treat that as "cannot ask" and fail closed.
fn open_prompt_tty() -> Option<PromptTty> {
    #[cfg(unix)]
    {
        use std::os::unix::io::AsRawFd;
        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open("/dev/tty")
            .ok()?;
        let output = file.try_clone().ok()?;
        let fd = file.as_raw_fd();
        Some(PromptTty {
            input: Box::new(file),
            output: Box::new(output),
            fd,
        })
    }
    #[cfg(not(unix))]
    {
        use std::io::IsTerminal;
        if !std::io::stdin().is_terminal() {
            return None;
        }
        Some(PromptTty {
            input: Box::new(std::io::stdin()),
            output: Box::new(std::io::stderr()),
        })
    }
}

/// Whether `$SSH_ASKPASS` names a helper we are allowed to run
/// (`SSH_ASKPASS_REQUIRE=never` vetoes it).
fn askpass_configured() -> bool {
    let set = matches!(std::env::var_os("SSH_ASKPASS"), Some(v) if !v.is_empty());
    let vetoed = matches!(std::env::var_os("SSH_ASKPASS_REQUIRE"), Some(req) if req == "never");
    set && !vetoed
}

/// Whether an interactive secret (password / keyboard-interactive answer)
/// can be obtained at all: either an askpass helper is configured or a
/// controlling terminal can be opened. When this is `false` the binaries
/// must not offer `password` / `keyboard-interactive` auth — exactly like
/// OpenSSH under `BatchMode yes` — instead of reading answers from a
/// non-terminal stdin.
pub fn secret_prompt_available() -> bool {
    askpass_configured() || open_prompt_tty().is_some()
}

/// Read a password (for `password` userauth) without echoing it. Returns a
/// [`Zeroizing<String>`] so the buffer is wiped on drop — callers should not
/// clone the inner `String` and should drop the wrapper as soon as auth
/// completes.
///
/// Lookup order:
/// 1. `$SSH_ASKPASS` is set (and `SSH_ASKPASS_REQUIRE` is not `never`): run
///    the named helper, take its first stdout line.
/// 2. The controlling terminal (`/dev/tty` on Unix; stdin-if-a-terminal
///    elsewhere): print the prompt there, disable echo via
///    `tcsetattr(ECHO off)` where supported, read one line, restore the old
///    settings via a `Drop` guard.
/// 3. Neither available: return an error. The password is **never** read
///    from a redirected stdin — see [`PromptTty`] for why.
///
/// The historical name is kept so the three client binaries keep compiling;
/// the source is no longer stdin.
pub fn read_password_from_stdin() -> std::io::Result<Zeroizing<String>> {
    const PROMPT: &str = "password: ";
    if let Some(out) = try_ssh_askpass(PROMPT)? {
        return Ok(out);
    }
    let mut tty = open_prompt_tty().ok_or_else(no_tty_error)?;
    tty.output.write_all(PROMPT.as_bytes())?;
    tty.output.flush()?;
    read_secret_line(&mut tty)
}

/// Read one keyboard-interactive (RFC 4256) answer for `prompt`. When `echo`
/// is `true` the input is shown (e.g. an OTP token, a username); when `false`
/// the terminal echo bit is suppressed exactly like the password reader. Used
/// by the `ssh` binary's keyboard-interactive responder.
///
/// Like [`read_password_from_stdin`], the answer comes from `$SSH_ASKPASS`
/// or the controlling terminal — never from a redirected stdin — and an
/// error is returned when neither is available.
///
/// The returned buffer is [`Zeroizing`] so even echo-on answers (which may
/// still be secret-adjacent) are wiped on drop.
pub fn read_kbdint_response(prompt: &str, echo: bool) -> std::io::Result<Zeroizing<String>> {
    // The prompt is server-supplied and arrives pre-trust; scrub control
    // bytes so it cannot rewrite the terminal or spoof another prompt.
    let prompt = sanitize_terminal_str(prompt);
    let Some(mut tty) = open_prompt_tty() else {
        // No terminal: an askpass helper is the only acceptable source
        // (OpenSSH routes keyboard-interactive prompts through it too).
        return try_ssh_askpass(&prompt)?.ok_or_else(no_tty_error);
    };
    tty.output.write_all(prompt.as_bytes())?;
    tty.output.flush()?;
    if echo {
        let mut buf = String::new();
        read_one_line(&mut tty.input, &mut buf, 4096)?;
        Ok(Zeroizing::new(buf))
    } else {
        read_secret_line(&mut tty)
    }
}

/// Ask for a secret (a key passphrase, an agent lock password) with
/// `prompt`: on the controlling terminal with echo off, else through
/// `$SSH_ASKPASS`; never from a redirected stdin.
#[allow(dead_code)] // not every binary prompts for secrets
pub fn read_secret(prompt: &str) -> std::io::Result<Zeroizing<String>> {
    if let Some(mut tty) = open_prompt_tty() {
        tty.output.write_all(prompt.as_bytes())?;
        tty.output.flush()?;
        return read_secret_line(&mut tty);
    }
    try_ssh_askpass(prompt)?.ok_or_else(no_tty_error)
}

/// The error returned when a secret is requested but there is no terminal
/// to ask on and no askpass helper.
fn no_tty_error() -> std::io::Error {
    std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "no controlling terminal to prompt on and $SSH_ASKPASS is not set \
         (refusing to read a secret from a redirected stdin)",
    )
}

/// Pull one line off `r` into `buf`, stopping at `\n` (which is
/// consumed but not appended). `\r` is dropped. Capped at `max_len`
/// bytes to bound memory if the source is unbounded.
fn read_one_line(r: &mut dyn Read, buf: &mut String, max_len: usize) -> std::io::Result<()> {
    let mut byte = [0u8; 1];
    loop {
        let n = r.read(&mut byte)?;
        if n == 0 || byte[0] == b'\n' {
            break;
        }
        if byte[0] == b'\r' {
            continue;
        }
        buf.push(byte[0] as char);
        if buf.len() > max_len {
            break;
        }
    }
    Ok(())
}

/// Unix no-echo secret read from the prompt terminal. The terminal's echo
/// bit is cleared for the duration of the read and restored via a `Drop`
/// guard, even if the read fails or panics. Should `tcgetattr`/`tcsetattr`
/// fail (it should not on `/dev/tty`), the read proceeds with echo after a
/// one-line warning rather than silently exposing the secret.
#[cfg(unix)]
fn read_secret_line(tty: &mut PromptTty) -> std::io::Result<Zeroizing<String>> {
    let fd = tty.fd;
    // SAFETY: zero-init is the documented way to allocate a termios
    // struct before tcgetattr fills it in.
    let mut term: libc::termios = unsafe { core::mem::zeroed() };
    // SAFETY: `fd` is the open `/dev/tty` descriptor owned by `tty`;
    // `term` is a writable termios.
    let got = unsafe { libc::tcgetattr(fd, &mut term as *mut _) } == 0;
    let original = term;

    // Drop guard restores echo even on panic/early-return.
    struct EchoGuard {
        fd: libc::c_int,
        original: libc::termios,
    }
    impl Drop for EchoGuard {
        fn drop(&mut self) {
            // SAFETY: we captured the original termios just above; the fd
            // outlives this guard (it belongs to the enclosing `PromptTty`).
            unsafe { libc::tcsetattr(self.fd, libc::TCSANOW, &self.original) };
        }
    }

    term.c_lflag &= !libc::ECHO;
    // SAFETY: `term` is a valid termios value derived from `tcgetattr`,
    // with only ECHO cleared.
    let no_echo = got && unsafe { libc::tcsetattr(fd, libc::TCSANOW, &term) } == 0;
    let _guard = no_echo.then_some(EchoGuard { fd, original });
    if !no_echo {
        let _ = writeln!(
            tty.output,
            "\n(warning: terminal echo could not be disabled; input will be visible)"
        );
    }

    let mut buf = String::new();
    let res = read_one_line(&mut tty.input, &mut buf, 4096);
    // Print the missing newline so subsequent output doesn't run into
    // the prompt line.
    let _ = tty.output.write_all(b"\n");
    res?;
    Ok(Zeroizing::new(buf))
}

/// Non-Unix secret read: we have no portable way to clear the console echo
/// bit without extra dependencies, so warn once and read with echo.
#[cfg(not(unix))]
fn read_secret_line(tty: &mut PromptTty) -> std::io::Result<Zeroizing<String>> {
    let _ = writeln!(
        tty.output,
        "\n(warning: terminal echo could not be disabled; input will be visible)"
    );
    let mut buf = String::new();
    read_one_line(&mut tty.input, &mut buf, 4096)?;
    Ok(Zeroizing::new(buf))
}

/// Drop-guard wrapper around a saved `termios` snapshot that switches
/// stdin into raw mode on construction and restores it on drop. Used
/// by the interactive-shell path in `ssh.rs` so a panic, signal, or
/// early-return through any of the I/O threads still leaves the
/// user's terminal usable.
///
/// "Raw" here mirrors the bit-clear set OpenSSH applies for
/// `ssh -tt`: clear `ICANON | ECHO | ECHOE | ECHOK | ECHONL | ISIG |
/// IEXTEN` on `c_lflag`, `IXON | ICRNL | BRKINT | INPCK | ISTRIP` on
/// `c_iflag`, `OPOST` on `c_oflag`, plus `VMIN=1 / VTIME=0` so reads
/// return as soon as a single byte arrives.
///
/// In addition to the `Drop` restore (which covers normal exit + panic
/// unwind), `install` arms an async-signal-safe handler for
/// SIGINT/SIGTERM/SIGHUP/SIGQUIT that runs `tcsetattr` back to the
/// saved settings *before* the process dies — otherwise Ctrl-C from
/// the local tty would leave the user's shell in raw mode, no echo,
/// no line discipline, and they'd have to type `reset` blind. The
/// handler is installed with `SA_RESETHAND` so the second occurrence
/// of the same signal kills the process with the default disposition
/// (and the correct WIFSIGNALED exit code); the first occurrence both
/// restores termios and re-raises the signal after re-installing the
/// previous disposition.
///
/// Nested guards on the same fd are NOT supported: `install` will
/// fall back to a Drop-only guard (no signal handler) when one is
/// already armed, so the outer guard's handler stays in place and
/// the inner guard is a no-op for signal purposes. The current call
/// site in `ssh.rs` never nests, so this is a defensive contract,
/// not a hot path.
#[cfg(unix)]
pub struct TermiosRawGuard {
    fd: libc::c_int,
    original: libc::termios,
    /// `true` when *this* guard owns the installed signal handlers
    /// and must tear them down on drop; `false` for a nested
    /// guard (which restores termios on drop but leaves the
    /// outer guard's handler in place).
    owns_handler: bool,
}

#[cfg(unix)]
mod termios_signal {
    //! Signal-handler state for [`super::TermiosRawGuard`].
    //!
    //! Everything here is laid out so the handler can run from
    //! inside `sigaction(2)` without touching anything that isn't
    //! on POSIX's async-signal-safe list (`tcsetattr`, `sigaction`,
    //! `raise`, atomic loads/stores). No `Mutex`, no allocation,
    //! no `eprintln!`, no `Drop`.
    use core::cell::UnsafeCell;
    use core::mem::MaybeUninit;
    use core::sync::atomic::{AtomicBool, AtomicI32, Ordering};

    /// `true` while a [`super::TermiosRawGuard`] holds the
    /// install slot. Set by `try_install` (compare-exchange) and
    /// cleared by `uninstall`. Read by both the install path and,
    /// indirectly (via the saved state), the handler.
    pub(super) static INSTALLED: AtomicBool = AtomicBool::new(false);

    /// fd to call `tcsetattr` on from inside the handler. `-1`
    /// means "no install active" — the handler must check this
    /// to avoid acting on stale state if it ever races with
    /// `uninstall` (which it shouldn't, since we `SA_RESETHAND`
    /// and tear down the disposition before clearing `INSTALLED`,
    /// but the read is free).
    pub(super) static SAVED_FD: AtomicI32 = AtomicI32::new(-1);

    /// Saved termios bytes. Written by `try_install` *before*
    /// `sigaction` arms the handler, read by the handler. The
    /// store/arm ordering is the only thing that makes this
    /// safe to read from the handler.
    ///
    /// Not behind a `Mutex` on purpose: the handler may not
    /// lock. Outside the handler, accesses are gated by
    /// `INSTALLED` (a single guard owns the slot at a time).
    pub(super) struct TermiosCell(pub UnsafeCell<MaybeUninit<libc::termios>>);
    // SAFETY: writes are gated by `INSTALLED` (only one guard at
    // a time); the handler reads via a raw pointer and `tcsetattr`
    // treats the buffer as read-only.
    unsafe impl Sync for TermiosCell {}
    pub(super) static SAVED_TERMIOS: TermiosCell =
        TermiosCell(UnsafeCell::new(MaybeUninit::uninit()));

    /// Previous `sigaction` for SIGINT/SIGTERM/SIGHUP/SIGQUIT,
    /// captured at install time and restored on uninstall. Indexed
    /// in the same order as [`SIGNALS`].
    pub(super) struct SigactionCell(pub UnsafeCell<MaybeUninit<libc::sigaction>>);
    // SAFETY: same `INSTALLED`-gated access pattern as `TermiosCell`.
    unsafe impl Sync for SigactionCell {}
    pub(super) static PREV_SIGACTIONS: [SigactionCell; 4] = [
        SigactionCell(UnsafeCell::new(MaybeUninit::uninit())),
        SigactionCell(UnsafeCell::new(MaybeUninit::uninit())),
        SigactionCell(UnsafeCell::new(MaybeUninit::uninit())),
        SigactionCell(UnsafeCell::new(MaybeUninit::uninit())),
    ];

    /// Signals we intercept. Order matches `PREV_SIGACTIONS`.
    pub(super) const SIGNALS: [libc::c_int; 4] =
        [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];

    /// Async-signal-safe handler. Restores the saved termios,
    /// then re-raises `sig` so the process dies with the proper
    /// WIFSIGNALED exit code. We armed via `SA_RESETHAND`, so
    /// the disposition has already reverted to the default by the
    /// time we re-enter (no `sigaction` call needed from inside
    /// the handler).
    ///
    /// Only async-signal-safe libc calls are used:
    ///   - `tcsetattr` (POSIX-listed)
    ///   - `raise` (POSIX-listed)
    ///
    /// Atomic loads/stores are lock-free on every Unix tier-1
    /// target and are safe from a signal handler.
    pub(super) extern "C" fn handler(sig: libc::c_int) {
        let fd = SAVED_FD.load(Ordering::Relaxed);
        if fd >= 0 {
            // SAFETY: `SAVED_TERMIOS` was initialised before
            // `sigaction` armed this handler, by the install
            // path which set `SAVED_FD` last. So whenever
            // `fd >= 0` the cell holds a valid `libc::termios`
            // that the handler may read. `tcsetattr` only reads
            // the buffer. Failure (-1) is intentionally ignored
            // — we cannot `eprintln!` from here.
            unsafe {
                let ptr = SAVED_TERMIOS.0.get();
                libc::tcsetattr(fd, libc::TCSANOW, (*ptr).as_ptr());
            }
        }
        // SA_RESETHAND already restored the default disposition;
        // re-raise so the process dies with the correct status.
        // Ignore the return — there's nothing useful to do on
        // failure, and `raise` is async-signal-safe.
        unsafe {
            libc::raise(sig);
        }
    }
}

#[cfg(unix)]
impl TermiosRawGuard {
    /// Switch fd 0 into raw mode and return a guard that restores the
    /// passed-in `original` termios on drop. Best-effort: if the
    /// `tcsetattr` call fails (e.g. stdin isn't a tty after all), the
    /// returned guard still restores on drop — no observable effect
    /// in that case.
    ///
    /// Also arms a signal-safe handler for SIGINT/SIGTERM/SIGHUP/
    /// SIGQUIT that runs `tcsetattr` back to `original` before the
    /// process dies — see the type-level docs for the rationale.
    /// Failure to arm a handler is non-fatal: the guard still works
    /// for the panic / clean-exit case.
    pub fn install(original: &libc::termios) -> Self {
        let fd: libc::c_int = 0;
        let mut raw = *original;
        raw.c_lflag &= !(libc::ICANON
            | libc::ECHO
            | libc::ECHOE
            | libc::ECHOK
            | libc::ECHONL
            | libc::ISIG
            | libc::IEXTEN);
        raw.c_iflag &= !(libc::IXON | libc::ICRNL | libc::BRKINT | libc::INPCK | libc::ISTRIP);
        raw.c_oflag &= !libc::OPOST;
        raw.c_cc[libc::VMIN] = 1;
        raw.c_cc[libc::VTIME] = 0;
        // SAFETY: `raw` is derived from `original` (which the caller
        // got from a successful tcgetattr); the fd is stdin and valid
        // for the process lifetime.
        unsafe {
            libc::tcsetattr(fd, libc::TCSANOW, &raw);
        }
        // Arm the signal handler. Returns false if one is already
        // installed (nested guard) — in that case we leave the outer
        // guard's handler in charge and the inner guard becomes
        // Drop-only.
        let owns_handler = install_signal_handler(fd, original);
        TermiosRawGuard {
            fd,
            original: *original,
            owns_handler,
        }
    }
}

#[cfg(unix)]
impl Drop for TermiosRawGuard {
    fn drop(&mut self) {
        if self.owns_handler {
            // Tear down the signal handler *before* the termios
            // restore: the handler is now a no-op-ish path
            // (SAVED_FD will be set to -1), and if a signal lands
            // between the two operations the default disposition
            // (or whatever was there before us) is exactly what we
            // want — the user's shell will already be in cooked
            // mode by then because we're about to do the
            // tcsetattr below.
            uninstall_signal_handler();
        }
        // SAFETY: same justification as `install` — we captured a
        // valid termios; the fd is stdin.
        unsafe {
            libc::tcsetattr(self.fd, libc::TCSANOW, &self.original);
        }
    }
}

/// Arm the signal-safe restore handler. Returns `true` if this call
/// installed the handlers (and the caller must call
/// [`uninstall_signal_handler`] later), `false` if a handler was
/// already installed (nested guard — leave the outer handler alone).
///
/// On `sigaction` failure for any of the four signals, the slot is
/// left in its prior state and we keep going: any signal we did
/// manage to install on still restores the tty; a SIGTERM we
/// couldn't install on still kills the process, but the Drop guard
/// handles the clean-exit path too.
#[cfg(unix)]
fn install_signal_handler(fd: libc::c_int, original: &libc::termios) -> bool {
    use core::sync::atomic::Ordering;
    // CAS: refuse to install when another guard already owns the slot.
    if termios_signal::INSTALLED
        .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
        .is_err()
    {
        return false;
    }
    // SAFETY: we hold the install slot (the CAS above), so we're the
    // only writer to these statics. The termios store *must* happen
    // before SAVED_FD is set (the handler keys off SAVED_FD >= 0).
    unsafe {
        (*termios_signal::SAVED_TERMIOS.0.get()).write(*original);
    }
    // Publish `fd` last; this is the "data ready" signal for the
    // handler. Release ordering pairs with the Relaxed load in the
    // handler — relaxed is fine on the handler side because signal
    // delivery already establishes a synchronizes-with relation with
    // the kernel's sigaction install.
    termios_signal::SAVED_FD.store(fd, Ordering::Release);

    let mut all_ok = true;
    // SAFETY: caller-owned `sigaction` structs, well-formed. The
    // handler we point at uses only async-signal-safe calls.
    unsafe {
        for (idx, &sig) in termios_signal::SIGNALS.iter().enumerate() {
            let mut sa: libc::sigaction = core::mem::zeroed();
            sa.sa_sigaction = termios_signal::handler as *const () as usize;
            // SA_RESETHAND: a second signal of the same type after
            // the first one's been handled gets the default
            // disposition — which is what we want, since we'll have
            // re-raised the signal at the end of the handler and the
            // default is "die with WIFSIGNALED set". Also avoids any
            // re-entrancy worry on the rare path where the handler
            // is interrupted by a second SIGINT.
            sa.sa_flags = libc::SA_RESETHAND;
            libc::sigemptyset(&mut sa.sa_mask);
            let prev_ptr = termios_signal::PREV_SIGACTIONS[idx].0.get();
            if libc::sigaction(sig, &sa, (*prev_ptr).as_mut_ptr()) != 0 {
                // Mark the slot as uninitialised so uninstall
                // doesn't try to restore garbage. We do this by
                // zero-initialising the prev — `sigaction(sig, prev, NULL)`
                // with a zeroed sigaction installs SIG_DFL, which is
                // the safest fallback for a signal we couldn't manage.
                (*prev_ptr).write(core::mem::zeroed());
                all_ok = false;
            }
        }
    }
    let _ = all_ok;
    true
}

/// Tear down the signal-safe restore handler installed by
/// [`install_signal_handler`]. Restores the previous `sigaction` for
/// each of SIGINT/SIGTERM/SIGHUP/SIGQUIT (which is `SIG_DFL` in the
/// common case where the process never installed its own), clears
/// the install slot, and zeros `SAVED_FD` so any stray late delivery
/// is a no-op.
#[cfg(unix)]
fn uninstall_signal_handler() {
    use core::sync::atomic::Ordering;
    // Reset SAVED_FD first: a signal racing with uninstall will see
    // -1 and skip the tcsetattr (the Drop guard runs the restore
    // synchronously right after this anyway). Release pairs with the
    // handler's Relaxed load.
    termios_signal::SAVED_FD.store(-1, Ordering::Release);
    // SAFETY: we own the install slot; only writer to these statics.
    unsafe {
        for (idx, &sig) in termios_signal::SIGNALS.iter().enumerate() {
            let prev_ptr = termios_signal::PREV_SIGACTIONS[idx].0.get();
            // The prev sigaction was either populated by a successful
            // sigaction() in install (real previous disposition) or
            // zeroed by install on failure (which restores SIG_DFL,
            // the safe fallback). Either way the buffer is valid to
            // hand back to sigaction().
            libc::sigaction(sig, (*prev_ptr).as_ptr(), core::ptr::null_mut());
        }
    }
    // Release the install slot last so any future install can
    // observe the cleared SAVED_FD via the Acquire CAS.
    termios_signal::INSTALLED.store(false, Ordering::Release);
}

/// Honour `$SSH_ASKPASS` when set: invoke the named helper with `prompt` as
/// its sole argument and take its first stdout line as the answer. Returns
/// `Ok(None)` if no helper is configured (or `SSH_ASKPASS_REQUIRE=never`), or
/// if the helper could not be run / exited non-zero.
fn try_ssh_askpass(prompt: &str) -> std::io::Result<Option<Zeroizing<String>>> {
    if !askpass_configured() {
        return Ok(None);
    }
    let askpass = match std::env::var_os("SSH_ASKPASS") {
        Some(v) => v,
        None => return Ok(None),
    };
    let mut cmd = std::process::Command::new(askpass);
    cmd.arg(prompt);
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::inherit());
    let out = match cmd.output() {
        Ok(o) => o,
        Err(_) => return Ok(None),
    };
    if !out.status.success() {
        return Ok(None);
    }
    // Take the first line, drop the trailing newline if present.
    let mut s = String::from_utf8_lossy(&out.stdout).into_owned();
    if let Some(idx) = s.find('\n') {
        s.truncate(idx);
    }
    if s.ends_with('\r') {
        s.pop();
    }
    Ok(Some(Zeroizing::new(s)))
}

/// OpenSSH's `sshkey_perm_ok` check: a private key file owned by the
/// calling user must not be group- or world-accessible (`mode & 0o077`).
/// Returns `Err` with OpenSSH's exact banner when the file is too open;
/// `Ok(())` otherwise (including for files owned by another user, which
/// OpenSSH also leaves to that user's discretion, and on non-Unix
/// platforms where the mode bits carry no meaning).
///
/// The check is a metadata lookup on `path` *before* it is read, so a
/// too-open key never even enters memory.
pub fn check_identity_perms(path: &Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let md = std::fs::metadata(path).map_err(|e| format!("read {}: {e}", path.display()))?;
        let euid = unix_sys::geteuid();
        let mode = md.mode() & 0o777;
        if md.uid() == euid && (mode & 0o077) != 0 {
            return Err(format!(
                "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\
                 @         WARNING: UNPROTECTED PRIVATE KEY FILE!          @\n\
                 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\
                 Permissions {mode:04o} for '{}' are too open.\n\
                 It is required that your private key files are NOT accessible by others.\n\
                 This private key will be ignored.",
                path.display()
            ));
        }
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}

/// Read an OpenSSH PEM identity file off disk and parse it. We refuse
/// passphrase-protected keys here (the bins don't have the prompting
/// infrastructure); users can pre-decrypt with `ssh-keygen -p`.
///
/// A key file that is group/world-accessible is refused outright with
/// OpenSSH's `UNPROTECTED PRIVATE KEY FILE!` banner
/// (see [`check_identity_perms`]).
pub fn load_identity(path: &str) -> Result<PrivateKey, String> {
    check_identity_perms(Path::new(path))?;
    let pem = std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))?;
    PrivateKey::parse_pem(&pem, None)
        .map_err(|e| format!("parse {path}: {e} (passphrase-protected keys not supported here)"))
}

/// A passphrase-protected identity file. Like OpenSSH, it is offered by its
/// public key, and the passphrase is asked for (up to three times) only
/// when the server would accept the key, at signing time.
pub struct LazyIdentity {
    path: String,
    pem: Zeroizing<String>,
    algorithm: &'static str,
    public_blob: Vec<u8>,
    loaded: Mutex<Option<Box<dyn puressh::hostkey::HostKey + Send + Sync>>>,
}

impl puressh::hostkey::HostKey for LazyIdentity {
    fn algorithm(&self) -> &'static str {
        self.algorithm
    }

    fn public_blob(&self) -> Vec<u8> {
        self.public_blob.clone()
    }

    fn sign(&self, msg: &[u8]) -> puressh::Result<Vec<u8>> {
        let mut loaded = self
            .loaded
            .lock()
            .map_err(|_| Error::Config("identity lock poisoned"))?;
        if loaded.is_none() {
            for _ in 0..3 {
                let pass = read_secret(&format!("Enter passphrase for key '{}': ", self.path))
                    .map_err(Error::Io)?;
                if pass.is_empty() {
                    break;
                }
                match PrivateKey::parse_pem(&self.pem, Some(pass.as_bytes())) {
                    Ok(k) => {
                        *loaded = Some(k.into_host_key_sync()?);
                        break;
                    }
                    Err(Error::Crypto(_)) => {}
                    Err(e) => return Err(e),
                }
            }
        }
        match loaded.as_ref() {
            Some(k) => k.sign(msg),
            None => Err(Error::Crypto("no passphrase for the identity")),
        }
    }
}

/// An identity file as a publickey credential: loaded now when it is not
/// encrypted, else a [`LazyIdentity`] (when a passphrase can be asked for).
/// `Ok(None)` for a default identity that does not exist or is unusable,
/// and for an encrypted key under BatchMode / without a terminal (OpenSSH
/// skips those too).
pub fn identity_credential(
    path: &str,
    is_default: bool,
    batch: bool,
) -> Result<Option<ClientCredential>, String> {
    Ok(identity_signer(path, is_default, batch)?.map(|s| ClientCredential::PublicKey(s)))
}

/// The signer behind [`identity_credential`] (also wrapped by certificates).
pub fn identity_signer(
    path: &str,
    is_default: bool,
    batch: bool,
) -> Result<Option<Box<dyn puressh::hostkey::HostKey + Send + Sync>>, String> {
    let pem = match std::fs::read_to_string(path) {
        Ok(s) => Zeroizing::new(s),
        Err(e) if is_default && e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("read {path}: {e}")),
    };
    if let Err(banner) = check_identity_perms(Path::new(path)) {
        if is_default {
            eprintln!("{banner}");
            return Ok(None);
        }
        return Err(banner);
    }
    match PrivateKey::parse_pem(&pem, None) {
        Ok(k) => Ok(Some(
            k.into_host_key_sync().map_err(|e| format!("{path}: {e}"))?,
        )),
        Err(Error::Crypto(_)) => {
            if batch || !secret_prompt_available() {
                vlog(
                    1,
                    &format!("{path}: encrypted, and no way to ask for its passphrase"),
                );
                return Ok(None);
            }
            let public = PrivateKey::public_key_from_pem(&pem)
                .ok()
                .or_else(|| {
                    let line = std::fs::read_to_string(format!("{path}.pub")).ok()?;
                    puressh::key::PublicKey::parse_authorized_keys_line(line.trim()).ok()
                })
                .ok_or_else(|| format!("{path}: encrypted key without a readable {path}.pub"))?;
            let algorithm = match public.algorithm() {
                "ssh-rsa" => "rsa-sha2-512",
                other => other,
            };
            Ok(Some(Box::new(LazyIdentity {
                path: path.to_string(),
                pem,
                algorithm,
                public_blob: public.wire_blob(),
                loaded: Mutex::new(None),
            })))
        }
        Err(e) => Err(format!("parse {path}: {e}")),
    }
}

/// The agent connections authentication signs through, bound to the session
/// once it is up (`session-bind@openssh.com`, see [`bind_auth_agents`]).
#[cfg(unix)]
static AUTH_AGENTS: Mutex<Vec<Arc<Mutex<Agent>>>> = Mutex::new(Vec::new());

/// Bind every agent connection authentication uses to the session, as
/// OpenSSH does before it signs with an agent key: an agent that holds keys
/// with destination constraints only lets them sign for the hosts named.
#[cfg(unix)]
#[allow(dead_code)] // ssh only
pub fn bind_auth_agents(binding: &puressh::client::SessionBinding) {
    let agents = AUTH_AGENTS.lock().map(|g| g.clone()).unwrap_or_default();
    for agent in agents {
        if let Ok(mut a) = agent.lock() {
            match a.bind_session(
                &binding.host_key,
                &binding.session_id,
                &binding.signature,
                false,
            ) {
                Ok(true) => vlog(1, "bound agent to hostkey"),
                Ok(false) => vlog(1, "agent does not support session binding"),
                Err(e) => vlog(1, &format!("agent session binding: {e}")),
            }
        }
    }
}

/// The agent's signer for the public key `blob`, if the agent holds it
/// (to pair a `CertificateFile` with an agent key, as OpenSSH does).
#[cfg(unix)]
#[allow(dead_code)] // ssh only
pub fn agent_signer_for(blob: &[u8]) -> Option<AgentHostKey> {
    let agent = Agent::connect_env().ok()??;
    let agent = Arc::new(Mutex::new(agent));
    if let Ok(mut g) = AUTH_AGENTS.lock() {
        g.push(agent.clone());
    }
    let held = agent
        .lock()
        .ok()?
        .identities()
        .ok()?
        .into_iter()
        .any(|i| i.key_blob == blob);
    if !held {
        return None;
    }
    AgentHostKey::from_identity(agent, blob.to_vec()).ok()
}

/// Connect to `$SSH_AUTH_SOCK` (if set), list identities, and wrap each as a
/// publickey credential backed by [`AgentHostKey`]. Returns `Ok(empty)` when
/// no agent is reachable — that's an expected "no agent" state, not an
/// error.
///
/// On non-Unix platforms there is no `ssh-agent` to talk to (the
/// `puressh::agent` module is `cfg(unix)`); the function returns
/// `Ok(empty)` so callers can keep the "agent first, identity files
/// second" credential layering without platform checks.
#[cfg(unix)]
pub fn connect_agent_credentials() -> Result<Vec<ClientCredential>, String> {
    // No agent, or a stale $SSH_AUTH_SOCK: carry on without (OpenSSH only
    // says so at debug level).
    let agent = match Agent::connect_env() {
        Ok(Some(a)) => a,
        Ok(None) => return Ok(Vec::new()),
        Err(e) => {
            vlog(1, &format!("agent: {e}"));
            return Ok(Vec::new());
        }
    };
    let agent = Arc::new(Mutex::new(agent));
    if let Ok(mut g) = AUTH_AGENTS.lock() {
        g.push(agent.clone());
    }
    let identities = {
        let mut a = agent
            .lock()
            .map_err(|_| "agent mutex poisoned".to_string())?;
        a.identities().map_err(|e| format!("identities: {e}"))?
    };
    let mut creds: Vec<ClientCredential> = Vec::with_capacity(identities.len());
    for ident in identities {
        match AgentHostKey::from_identity(Arc::clone(&agent), ident.key_blob.clone()) {
            Ok(hk) => creds.push(ClientCredential::PublicKey(Box::new(hk))),
            Err(e) => eprintln!(
                "warning: agent identity {:?}: skipping: {e}",
                ident.comment()
            ),
        }
    }
    Ok(creds)
}

/// Non-Unix stub: no `ssh-agent` to consult, so return an empty list.
#[cfg(not(unix))]
pub fn connect_agent_credentials() -> Result<Vec<ClientCredential>, String> {
    Ok(Vec::new())
}

/// Compute the user's default known_hosts path: `$HOME/.ssh/known_hosts`.
/// Returns `None` if `$HOME` is unset.
pub fn default_known_hosts_path() -> Option<PathBuf> {
    let home = std::env::var_os("HOME")?;
    Some(PathBuf::from(home).join(".ssh").join("known_hosts"))
}

/// SHA-256 fingerprint, base64-encoded (no padding), formatted as
/// `SHA256:<base64>` — matches `ssh-keygen -lf`.
pub fn fingerprint_b64_sha256(blob: &[u8]) -> String {
    use purecrypto::hash::{Digest, Sha256};
    let digest = Sha256::digest(blob);
    let s = base64_no_pad(digest.as_ref());
    format!("SHA256:{s}")
}

/// Standard base64 (RFC 4648 alphabet), no padding. Matches OpenSSH's
/// fingerprint encoding.
pub fn base64_no_pad(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    let mut i = 0;
    while i + 3 <= bytes.len() {
        let b = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
        out.push(ALPHABET[((b >> 18) & 0x3F) as usize] as char);
        out.push(ALPHABET[((b >> 12) & 0x3F) as usize] as char);
        out.push(ALPHABET[((b >> 6) & 0x3F) as usize] as char);
        out.push(ALPHABET[(b & 0x3F) as usize] as char);
        i += 3;
    }
    let rem = bytes.len() - i;
    if rem == 1 {
        let b = (bytes[i] as u32) << 16;
        out.push(ALPHABET[((b >> 18) & 0x3F) as usize] as char);
        out.push(ALPHABET[((b >> 12) & 0x3F) as usize] as char);
    } else if rem == 2 {
        let b = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
        out.push(ALPHABET[((b >> 18) & 0x3F) as usize] as char);
        out.push(ALPHABET[((b >> 12) & 0x3F) as usize] as char);
        out.push(ALPHABET[((b >> 6) & 0x3F) as usize] as char);
    }
    out
}

/// The connection's peer address, for the host-key prompt's `'host
/// (address)'`: set once the TCP connection is up.
static PEER_ADDR: Mutex<Option<std::net::SocketAddr>> = Mutex::new(None);

/// Record the peer of the connection being set up (see [`PEER_ADDR`]).
#[allow(dead_code)] // ssh only
pub fn set_peer_addr(addr: Option<std::net::SocketAddr>) {
    if let Ok(mut g) = PEER_ADDR.lock() {
        *g = addr;
    }
}

/// `host`, or `[host]:port` off port 22, as OpenSSH names hosts.
fn host_target(host: &str, port: u16) -> String {
    if port == 22 {
        host.to_string()
    } else {
        format!("[{host}]:{port}")
    }
}

/// Every known_hosts line (`file`, 1-based line, entry) in `files`.
fn known_hosts_lines(files: &[PathBuf]) -> Vec<(PathBuf, usize, KnownHosts)> {
    let mut out = Vec::new();
    for f in files {
        let Ok(text) = std::fs::read_to_string(f) else {
            continue;
        };
        for (i, line) in text.lines().enumerate() {
            let t = line.trim_start();
            if t.is_empty() || t.starts_with('#') {
                continue;
            }
            out.push((f.clone(), i + 1, KnownHosts::from_bytes(line.as_bytes())));
        }
    }
    out
}

/// Host-key decisions worded as OpenSSH words them (`StrictHostKeyChecking`
/// `strict`; `files`: the user known_hosts files, new keys going to the
/// first): an unknown key is refused (`yes`), asked about (`ask`: `yes`,
/// `no` or the fingerprint), or added with `Warning: Permanently added`;
/// a changed key is refused with the file and line of the stale entry
/// (`no` connects anyway; that is [`TofuAction::AcceptWithWarning`]).
fn openssh_host_key_actions(strict: StrictMode, files: Vec<PathBuf>) -> (TofuAction, TofuAction) {
    let files = Arc::new(files);
    let unknown_files = Arc::clone(&files);
    let unknown =
        TofuAction::PromptDetailed(Arc::new(move |p: &puressh::client::HostKeyPrompt| {
            let label = puressh::client::host_key_type_label(p.key_blob);
            let target = host_target(p.host, p.port);
            let accepted = match strict {
                StrictMode::Yes => {
                    eprintln!(
                        "No {label} host key is known for {target} and you have requested strict \
                     checking."
                    );
                    false
                }
                StrictMode::Ask => ask_unknown_host(p, &label, &target, &unknown_files),
                StrictMode::AcceptNew | StrictMode::No => true,
                // A keyword value this binary predates: fail closed.
                _ => false,
            };
            if accepted && !is_quiet() {
                eprintln!(
                    "Warning: Permanently added '{target}' ({label}) to the list of known hosts."
                );
            }
            accepted
        }));
    let changed =
        TofuAction::PromptDetailed(Arc::new(move |p: &puressh::client::HostKeyPrompt| {
            let label = puressh::client::host_key_type_label(p.key_blob);
            let target = host_target(p.host, p.port);
            eprintln!("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            eprintln!("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
            eprintln!("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            eprintln!("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
            eprintln!(
                "Someone could be eavesdropping on you right now (man-in-the-middle attack)!"
            );
            eprintln!("It is also possible that a host key has just been changed.");
            eprintln!(
                "The fingerprint for the {label} key sent by the remote host is\n{}.",
                p.fingerprint
            );
            eprintln!("Please contact your system administrator.");
            if let Some(first) = files.first() {
                eprintln!(
                    "Add correct host key in {} to get rid of this message.",
                    first.display()
                );
            }
            for (file, line, store) in known_hosts_lines(&files) {
                for e in store.find(p.host, p.port) {
                    if e.marker.is_none() {
                        eprintln!(
                            "Offending {} key in {}:{line}",
                            puressh::client::host_key_type_label(&e.key_blob),
                            file.display()
                        );
                    }
                }
            }
            eprintln!("Host key for {target} has changed and you have requested strict checking.");
            false
        }));
    let changed = if strict == StrictMode::No {
        TofuAction::AcceptWithWarning
    } else {
        changed
    };
    (unknown, changed)
}

/// OpenSSH's first-contact question; `yes` or the key's fingerprint
/// accepts, `no` refuses, anything else asks again. No terminal: refused.
fn ask_unknown_host(
    p: &puressh::client::HostKeyPrompt,
    label: &str,
    target: &str,
    files: &[PathBuf],
) -> bool {
    let addr = PEER_ADDR
        .lock()
        .ok()
        .and_then(|g| *g)
        .map(|a| host_target(&a.ip().to_canonical().to_string(), a.port()))
        .unwrap_or_else(|| target.to_string());
    let mut banner = format!(
        "The authenticity of host '{target} ({addr})' can't be established.\n\
         {label} key fingerprint is {}.\n",
        p.fingerprint
    );
    let others: Vec<String> = known_hosts_lines(files)
        .into_iter()
        .flat_map(|(file, line, store)| {
            store
                .find_key(p.key_blob)
                .into_iter()
                .map(move |name| format!("    {}:{line}: {name}", file.display()))
                .collect::<Vec<_>>()
        })
        .collect();
    if others.is_empty() {
        banner.push_str("This key is not known by any other names.\n");
    } else {
        banner.push_str("This host key is known by the following other names/addresses:\n");
        for o in others.iter().take(8) {
            banner.push_str(o);
            banner.push('\n');
        }
    }
    let Some(mut tty) = open_prompt_tty() else {
        eprint!("{banner}");
        return false;
    };
    let mut question = "Are you sure you want to continue connecting (yes/no/[fingerprint])? ";
    if tty.output.write_all(banner.as_bytes()).is_err() {
        return false;
    }
    loop {
        if tty
            .output
            .write_all(question.as_bytes())
            .and_then(|()| tty.output.flush())
            .is_err()
        {
            return false;
        }
        let mut line = String::new();
        if read_one_line(&mut tty.input, &mut line, 256).is_err() || line.is_empty() {
            return false;
        }
        let answer = line.trim();
        if answer.eq_ignore_ascii_case("yes") || answer == p.fingerprint {
            return true;
        }
        if answer.eq_ignore_ascii_case("no") {
            return false;
        }
        question = "Please type 'yes', 'no' or the fingerprint: ";
    }
}

/// Build the [`HostKeyPolicy`] for a given strict mode + optional override
/// path + hash-on-write flag. Every variant loads the known_hosts store —
/// even `StrictMode::No`, which mirrors OpenSSH's loud-but-tolerant
/// `StrictHostKeyChecking=no`: unknown hosts are accepted silently
/// (matching `accept-new`), but a *changed* key still triggers the
/// `WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!` banner before the
/// connection proceeds. Pre-2026 puressh degraded `No` to
/// `HostKeyPolicy::AcceptAny`, which dropped the mismatch warning on
/// the floor; that gap is the reason this helper now never returns
/// `AcceptAny`.
pub fn build_host_key_policy(
    strict: StrictMode,
    explicit_path: Option<PathBuf>,
    hash_known_hosts: bool,
    user_files: Vec<PathBuf>,
) -> Result<HostKeyPolicy, String> {
    let path = match explicit_path {
        Some(p) => p,
        None => default_known_hosts_path()
            .ok_or_else(|| "no $HOME, cannot locate default known_hosts".to_string())?,
    };
    let store = KnownHosts::load(&path).map_err(|e| format!("load {}: {e}", path.display()))?;

    // OpenSSH's decisions and wording: refuse / ask / add an unknown key;
    // refuse a changed one (`no`: connect anyway, loudly, without
    // updating the file). The answer is read from the terminal only.
    let (on_unknown, on_mismatch) = openssh_host_key_actions(strict, user_files);

    let mut policy = KnownHostsPolicy::strict(Arc::new(Mutex::new(store)));
    policy.save_path = Some(path);
    policy.hash_new = hash_known_hosts;
    policy.on_unknown = on_unknown;
    policy.on_mismatch = on_mismatch;
    Ok(HostKeyPolicy::KnownHosts(policy))
}

/// Apply the known_hosts-related ssh_config options to a host-key policy:
/// `GlobalKnownHostsFile` (default `/etc/ssh/ssh_known_hosts{,2}`; missing
/// files are skipped), `HostKeyAlias`, and `RevokedHostKeys`, whose file
/// must be readable, as with OpenSSH: checking against a list that cannot
/// be read would silently accept a revoked key.
pub fn apply_known_hosts_options(
    policy: &mut HostKeyPolicy,
    cfg: &puressh::config::ClientOptions,
) -> Result<(), String> {
    let HostKeyPolicy::KnownHosts(kh) = policy else {
        return Ok(());
    };
    let globals: Vec<String> = match &cfg.global_known_hosts_files {
        Some(files) if files.iter().any(|f| f.eq_ignore_ascii_case("none")) => Vec::new(),
        Some(files) => files.iter().map(|f| expand_tilde(f)).collect(),
        None => vec![
            "/etc/ssh/ssh_known_hosts".into(),
            "/etc/ssh/ssh_known_hosts2".into(),
        ],
    };
    for path in globals {
        match KnownHosts::load(&path) {
            Ok(store) => kh.global.push(Arc::new(store)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => vlog(1, &format!("global known_hosts {path}: {e}")),
        }
    }
    kh.host_key_alias = cfg.host_key_alias.clone();
    if let Some(path) = cfg
        .revoked_host_keys
        .as_deref()
        .filter(|p| !p.eq_ignore_ascii_case("none"))
    {
        let path = expand_tilde(path);
        let revoked = puressh::known_hosts::RevokedHostKeys::load(&path)
            .map_err(|e| format!("RevokedHostKeys {path}: {e}"))?;
        kh.revoked = Some(Arc::new(revoked));
    }
    Ok(())
}

/// Binary-local verbosity level (`-v` / `-vv` / `-vvv`). One copy per
/// binary because `common.rs` is `#[path]`-included rather than shared
/// as a crate — that's fine, since each binary's process only ever sees
/// its own.
///
/// Levels: 0 = silent (default), 1..=3 = OpenSSH-style debug1/2/3. Held
/// in an atomic so [`vlog`] callers don't need to thread a handle
/// through every helper (which would noisify every signature for a
/// debug aid).
static VERBOSE: AtomicU8 = AtomicU8::new(0);

/// `-q`: suppress warnings and diagnostics (not errors, not security
/// banners such as a changed host key).
static QUIET: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Turn quiet mode on (`-q`).
#[allow(dead_code)] // not every binary has `-q`
pub fn set_quiet(on: bool) {
    QUIET.store(on, Ordering::Relaxed);
}

/// An I/O error as OpenSSH words it (`strerror`): without Rust's
/// ` (os error N)` suffix.
#[allow(dead_code)] // not every binary dials out
pub fn io_reason(e: &std::io::Error) -> String {
    if e.kind() == std::io::ErrorKind::TimedOut && e.raw_os_error().is_none() {
        return "Connection timed out".to_string();
    }
    let s = e.to_string();
    match s.find(" (os error ") {
        Some(i) => s[..i].to_string(),
        None => s,
    }
}

/// Whether `-q` is in force.
#[allow(dead_code)]
pub fn is_quiet() -> bool {
    QUIET.load(Ordering::Relaxed)
}

/// Bump the binary-local verbosity to `level`, clamped to `0..=3`.
/// Idempotent; call once after `parse_args` returns.
pub fn set_verbose(level: u8) {
    VERBOSE.store(level.min(3), Ordering::Relaxed);
}

/// Current verbose level (0..=3). Cheap; safe to call on the hot path.
pub fn verbose_level() -> u8 {
    VERBOSE.load(Ordering::Relaxed)
}

/// Emit `"debug{level}: {msg}"` to stderr iff the current verbose
/// level is at least `level`. Mirrors OpenSSH's `debug1:` /
/// `debug2:` / `debug3:` prefix convention so users porting muscle
/// memory get the same shape of output.
///
/// `level` is clamped to `1..=3`; passing 0 means "always print" but
/// callers should just `eprintln!` directly in that case.
/// The stderr ssh started with, while `-E` sends its own messages (fd 2)
/// to a log file: the remote command's stderr still goes here, as with
/// OpenSSH.
#[cfg(unix)]
static ORIGINAL_STDERR: std::sync::OnceLock<std::fs::File> = std::sync::OnceLock::new();

/// `-E file`: ssh's own messages go to `file` from now on.
#[cfg(unix)]
#[allow(dead_code)] // ssh only
pub fn log_to_file(path: &str) -> Result<(), String> {
    let f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .map_err(|e| format!("-E {path}: {e}"))?;
    use std::os::fd::AsFd;
    let saved = std::io::stderr()
        .as_fd()
        .try_clone_to_owned()
        .map_err(|e| format!("-E {path}: {e}"))?;
    let _ = ORIGINAL_STDERR.set(std::fs::File::from(saved));
    unix_sys::dup2(&f, 2).map_err(|e| format!("-E {path}: {e}"))?;
    Ok(())
}

/// Where the remote command's stderr goes: the terminal's stderr, even
/// under `-E`.
#[allow(dead_code)] // ssh only
pub fn remote_stderr() -> Box<dyn std::io::Write + Send> {
    #[cfg(unix)]
    if let Some(f) = ORIGINAL_STDERR.get().and_then(|f| f.try_clone().ok()) {
        return Box::new(f);
    }
    Box::new(std::io::stderr())
}

/// Give fd 2 back to the original stderr (for code that writes the remote
/// stderr there itself).
#[allow(dead_code)] // ssh only
pub fn restore_stderr() {
    #[cfg(unix)]
    if let Some(f) = ORIGINAL_STDERR.get() {
        let _ = unix_sys::dup2(f, 2);
    }
}

pub fn vlog(level: u8, msg: &str) {
    let level = level.clamp(1, 3);
    if VERBOSE.load(Ordering::Relaxed) >= level {
        eprintln!("debug{level}: {msg}");
    }
}

/// OpenSSH-style default identity paths under `$HOME/.ssh/`, in
/// preference order. Returns an empty vector when `$HOME` is unset
/// (no defaults to try, no error — callers fall back to the password
/// flow).
///
/// We deliberately omit:
///   - `id_dsa` — DSA is removed from modern OpenSSH defaults; our
///     key parser doesn't accept it.
///   - `id_ecdsa_sk`, `id_ed25519_sk` — FIDO/U2F security-key keys
///     need a hardware-token handshake (`sk-*` algorithms) that
///     puressh doesn't implement yet.
///
/// The returned paths are absolute and may not exist on disk; pair
/// each with [`try_load_default_identity`] which silently treats a
/// missing file as "skip".
pub fn default_identity_paths() -> Vec<PathBuf> {
    let Some(home) = std::env::var_os("HOME") else {
        return Vec::new();
    };
    let dot_ssh = PathBuf::from(home).join(".ssh");
    // OpenSSH's order (it also lists the FIDO `_sk` keys, which we lack).
    ["id_rsa", "id_ecdsa", "id_ed25519"]
        .iter()
        .map(|name| dot_ssh.join(name))
        .collect()
}

/// Load a default-discovery identity *silently*.
///
/// Returns:
///   - `Ok(None)` when the file is missing — that's the common case
///     for any default path the user doesn't actually have.
///   - `Ok(None)` when the file exists but is passphrase-protected
///     and we have no passphrase. OpenSSH prompts; for now we skip,
///     matching the explicit-`-i` policy in [`load_identity`] which
///     also refuses passphrase-protected keys. Distinguishes
///     "encrypted, no key material" from "broken file" via the
///     `Error::Crypto("passphrase required")` sentinel produced by
///     `PrivateKey::parse_openssh_pem`.
///   - `Ok(None)` (after printing OpenSSH's `UNPROTECTED PRIVATE KEY
///     FILE!` banner) when the file is group/world-accessible.
///   - `Ok(Some(_))` when the key parsed.
///   - `Err(_)` when the file exists but is malformed — surfaced
///     so the caller can warn once, since a broken default identity
///     is almost certainly a real misconfiguration the user wants
///     to know about.
pub fn try_load_default_identity(path: &Path) -> Result<Option<PrivateKey>, String> {
    let pem = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(format!("read {}: {e}", path.display())),
    };
    // Too-open default identities are skipped with OpenSSH's loud warning
    // rather than treated as a hard error: the user didn't name this key,
    // discovery did, and OpenSSH behaves the same way.
    if let Err(banner) = check_identity_perms(path) {
        eprintln!("{banner}");
        return Ok(None);
    }
    match PrivateKey::parse_pem(&pem, None) {
        Ok(pk) => Ok(Some(pk)),
        Err(Error::Crypto("passphrase required")) => Ok(None),
        Err(e) => Err(format!("parse {}: {e}", path.display())),
    }
}

// ---------------------------------------------------------------------------
// SSH config file discovery + loading
// ---------------------------------------------------------------------------

/// Load an `ssh_config(5)` for client binaries.
///
/// When `explicit` is `Some`, ONLY that file is parsed (matching OpenSSH's
/// `-F` behaviour). When `None`, both `~/.ssh/config` and
/// `/etc/ssh/ssh_config` are read in that order — the user file wins for
/// scalar options and both contribute to cumulative lists.
///
/// A missing file is silently skipped. Errors: a file that exists but won't
/// parse, or a `~/.ssh/config` with bad ownership / permissions (see
/// [`check_user_config_perms`]). `Include` paths get their `%` tokens from
/// `expand`.
pub fn load_client_config(
    explicit: Option<&Path>,
    expand: &dyn Fn(&str) -> String,
) -> Result<puressh::config::SshClientConfig, String> {
    use puressh::config::SshClientConfig;
    if let Some(path) = explicit {
        // `-F none`: no configuration file at all.
        if path == Path::new("none") {
            return Ok(SshClientConfig::default());
        }
        // File-based load so `Include` directives resolve (each anchored to
        // the including file's own directory). `-F` means this file only.
        return SshClientConfig::load_expanding(path, expand)
            .map_err(|e| format!("{}: {e}", path.display()));
    }
    // Default search path: user file first (wins), then system file. Each is
    // loaded independently so its `Include`s anchor to that file's directory;
    // the two block lists are then layered with the user file on top.
    let mut cfg: Option<SshClientConfig> = None;
    if let Some(home) = std::env::var_os("HOME") {
        let user = PathBuf::from(home).join(".ssh").join("config");
        if user.exists() {
            check_user_config_perms(&user)?;
            cfg = Some(
                SshClientConfig::load_expanding(&user, expand)
                    .map_err(|e| format!("{}: {e}", user.display()))?,
            );
        }
    }
    let system = Path::new("/etc/ssh/ssh_config");
    if system.exists() {
        let sys = SshClientConfig::load_expanding(system, expand)
            .map_err(|e| format!("{}: {e}", system.display()))?;
        match cfg.as_mut() {
            Some(existing) => existing.append(sys),
            None => cfg = Some(sys),
        }
    }
    Ok(cfg.unwrap_or_default())
}

/// OpenSSH's `SSHCONF_CHECKPERM` rule for the per-user client config: the
/// file must be owned by the calling user or root and must not be group- or
/// world-writable, otherwise it is refused with `Bad owner or permissions on
/// <path>`. A writable config lets another local user inject `ProxyCommand`
/// (arbitrary command execution), `IdentityFile`, `StrictHostKeyChecking no`,
/// and friends into every session the victim starts.
///
/// Only `~/.ssh/config` is checked, exactly like OpenSSH: `-F file` is an
/// explicit user choice and `/etc/ssh/ssh_config` is root-managed. Files
/// pulled in via `Include` are *not* checked because the config loader does
/// not expose the list of files it read. No-op on non-Unix.
fn check_user_config_perms(path: &Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let md = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
        let euid = unix_sys::geteuid();
        if (md.uid() != 0 && md.uid() != euid) || (md.mode() & 0o022) != 0 {
            return Err(format!("Bad owner or permissions on {}", path.display()));
        }
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}

/// Load an `sshd_config(5)` for the `sshd` binary. Returns an error if the
/// file is missing — server-side config is opt-in (`-f path`), so the caller
/// asked for this exact file.
pub fn load_server_config(path: &Path) -> Result<puressh::config::SshServerConfig, String> {
    // File-based load so `Include` directives resolve, anchored to the
    // including file's own directory.
    puressh::config::SshServerConfig::load(path).map_err(|e| format!("{}: {e}", path.display()))
}

/// OpenSSH precedence helper: returns the first `Some` of `cli`, `cfg`,
/// otherwise `default`. The standard scalar-option resolution pattern is
/// `pick(cli_flag, cfg_value, builtin_default)`.
pub fn pick<T>(cli: Option<T>, cfg: Option<T>, default: T) -> T {
    cli.or(cfg).unwrap_or(default)
}

/// Expand a leading `~/` or `~` in a config-supplied path to `$HOME`. Other
/// strings pass through verbatim. We deliberately do NOT expand `~user/` —
/// OpenSSH does, but our binaries don't currently consume cross-user paths.
pub fn expand_tilde(path: &str) -> String {
    if path == "~" {
        return std::env::var("HOME").unwrap_or_else(|_| "~".into());
    }
    if let Some(rest) = path.strip_prefix("~/")
        && let Ok(home) = std::env::var("HOME")
    {
        return format!("{home}/{rest}");
    }
    path.to_string()
}

/// What a [`KeystrokeObfuscator`] tick decided to do this cadence slot.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TickAction {
    /// Ship this chunk of real keystroke data over the channel.
    SendData(Vec<u8>),
    /// No real data was queued but the chaff window is open — emit a
    /// `ping@openssh.com` chaff packet to keep the cadence constant.
    SendChaff,
    /// The chaff window just expired on this tick (no data was queued and
    /// the tail elapsed). The caller should stop the cadence and emit the
    /// "stopping: chaff time expired" debug line. Carries the number of
    /// chaff packets sent during the window that just closed.
    WindowExpired { chaff_sent: u64 },
    /// Cadence is idle (window closed, nothing queued); do nothing.
    Idle,
}

/// Pure, timer-independent state machine implementing OpenSSH's
/// `ObscureKeystrokeTiming` cadence + chaff model for an interactive pty
/// session.
///
/// The caller drives it with a monotonic millisecond clock so the logic is
/// fully testable without real threads or timers:
///
/// - [`enqueue`](Self::enqueue) appends real keystroke bytes and (re)opens a
///   chaff window that stays open for `tail_ms` after the most recent
///   keystroke.
/// - [`tick`](Self::tick) is called on the cadence (every `interval_ms`). If
///   data is queued it returns a bounded [`TickAction::SendData`] chunk; if
///   the window is open but nothing is queued it returns
///   [`TickAction::SendChaff`]; when the window's tail elapses with nothing
///   queued it returns [`TickAction::WindowExpired`] once, then
///   [`TickAction::Idle`] until the next keystroke.
///
/// Releasing data on the fixed cadence (rather than immediately) and padding
/// idle gaps with chaff makes the on-wire packet rate constant while typing,
/// masking both inter-keystroke timing and when typing starts/stops.
pub struct KeystrokeObfuscator {
    interval_ms: u32,
    tail_ms: u32,
    max_chunk: usize,
    queue: Vec<u8>,
    /// Clock value at/after which the chaff window closes, when open.
    window_until: Option<u64>,
    /// `true` once a window has opened and not yet been reported as expired.
    window_active: bool,
    /// Chaff packets emitted during the currently-open window.
    chaff_sent: u64,
    /// `true` once we have logged the "starting" line for the open window.
    started_logged: bool,
}

impl KeystrokeObfuscator {
    /// Default per-keystroke chunk cap. OpenSSH ships keystrokes one cadence
    /// slot at a time; a small cap keeps a paste from collapsing the timing
    /// cover, while still draining a burst over a few ticks.
    pub const DEFAULT_MAX_CHUNK: usize = 256;

    /// Create a new obfuscator with the given cadence `interval_ms` and chaff
    /// `tail_ms` (how long the window stays open after the last keystroke).
    pub fn new(interval_ms: u32, tail_ms: u32) -> Self {
        Self {
            interval_ms: interval_ms.max(1),
            tail_ms,
            max_chunk: Self::DEFAULT_MAX_CHUNK,
            queue: Vec::new(),
            window_until: None,
            window_active: false,
            chaff_sent: 0,
            started_logged: false,
        }
    }

    /// The configured cadence interval in milliseconds (≥ 1).
    pub fn interval_ms(&self) -> u32 {
        self.interval_ms
    }

    /// `true` when the chaff window is currently open (cadence running).
    pub fn window_open(&self) -> bool {
        self.window_active
    }

    /// `true` if the caller still needs to emit the "starting" debug line for
    /// the current window. Returns `true` exactly once per window open; calling
    /// it flips the flag so the line is logged a single time.
    pub fn take_started_log(&mut self) -> bool {
        if self.window_active && !self.started_logged {
            self.started_logged = true;
            true
        } else {
            false
        }
    }

    /// Append real keystroke bytes and (re)open the chaff window: the window
    /// will stay open until `now_ms + tail_ms`.
    pub fn enqueue(&mut self, data: &[u8], now_ms: u64) {
        if data.is_empty() {
            return;
        }
        self.queue.extend_from_slice(data);
        self.open_or_extend_window(now_ms);
    }

    fn open_or_extend_window(&mut self, now_ms: u64) {
        let deadline = now_ms.saturating_add(self.tail_ms as u64);
        self.window_until = Some(deadline);
        if !self.window_active {
            self.window_active = true;
            self.chaff_sent = 0;
            self.started_logged = false;
        }
    }

    /// Advance the cadence by one slot at `now_ms`. See [`TickAction`].
    pub fn tick(&mut self, now_ms: u64) -> TickAction {
        // Data always takes priority: drain a bounded chunk and keep the
        // window open (so a long burst doesn't let the cover lapse mid-type).
        if !self.queue.is_empty() {
            let take = self.queue.len().min(self.max_chunk);
            let chunk: Vec<u8> = self.queue.drain(..take).collect();
            // Sending real data refreshes the tail, exactly like a keystroke.
            self.open_or_extend_window(now_ms);
            return TickAction::SendData(chunk);
        }

        if !self.window_active {
            return TickAction::Idle;
        }

        // Window open, nothing queued: chaff until the tail elapses.
        match self.window_until {
            Some(until) if now_ms < until => {
                self.chaff_sent = self.chaff_sent.saturating_add(1);
                TickAction::SendChaff
            }
            _ => {
                let chaff_sent = self.chaff_sent;
                self.window_active = false;
                self.window_until = None;
                self.started_logged = false;
                self.chaff_sent = 0;
                TickAction::WindowExpired { chaff_sent }
            }
        }
    }
}

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

    #[test]
    fn idle_when_no_activity() {
        let mut o = KeystrokeObfuscator::new(20, 1000);
        assert_eq!(o.tick(0), TickAction::Idle);
        assert_eq!(o.tick(20), TickAction::Idle);
        assert!(!o.window_open());
    }

    #[test]
    fn enqueue_opens_window_and_data_drains_on_ticks() {
        let mut o = KeystrokeObfuscator::new(20, 1000);
        o.enqueue(b"abc", 0);
        assert!(o.window_open());
        // First tick after the keystroke ships the data.
        assert_eq!(o.tick(20), TickAction::SendData(b"abc".to_vec()));
        // No more data, but the window stayed open → chaff.
        assert_eq!(o.tick(40), TickAction::SendChaff);
    }

    #[test]
    fn large_burst_is_chunked_across_ticks() {
        let mut o = KeystrokeObfuscator::new(20, 1000);
        let big = vec![b'x'; KeystrokeObfuscator::DEFAULT_MAX_CHUNK * 2 + 5];
        o.enqueue(&big, 0);
        let a = o.tick(20);
        let b = o.tick(40);
        let c = o.tick(60);
        match (&a, &b, &c) {
            (TickAction::SendData(x), TickAction::SendData(y), TickAction::SendData(z)) => {
                assert_eq!(x.len(), KeystrokeObfuscator::DEFAULT_MAX_CHUNK);
                assert_eq!(y.len(), KeystrokeObfuscator::DEFAULT_MAX_CHUNK);
                assert_eq!(z.len(), 5);
            }
            other => panic!("expected three SendData chunks, got {other:?}"),
        }
    }

    #[test]
    fn window_expires_after_tail_with_chaff_count() {
        let mut o = KeystrokeObfuscator::new(20, 50);
        o.enqueue(b"k", 0);
        // Ship the data at t=20 (refreshes tail to 70).
        assert_eq!(o.tick(20), TickAction::SendData(b"k".to_vec()));
        // Chaff while within the window.
        assert_eq!(o.tick(40), TickAction::SendChaff);
        assert_eq!(o.tick(60), TickAction::SendChaff);
        // At t=70 the tail (last refresh 20 + 50) has elapsed → expired,
        // reporting the two chaff packets sent.
        assert_eq!(o.tick(70), TickAction::WindowExpired { chaff_sent: 2 });
        // After expiry the cadence is idle until the next keystroke.
        assert_eq!(o.tick(90), TickAction::Idle);
        assert!(!o.window_open());
    }

    #[test]
    fn new_keystroke_reopens_window_after_expiry() {
        let mut o = KeystrokeObfuscator::new(20, 30);
        o.enqueue(b"a", 0);
        assert_eq!(o.tick(20), TickAction::SendData(b"a".to_vec()));
        // Let it expire (last refresh 20 + 30 = 50).
        assert!(matches!(o.tick(50), TickAction::WindowExpired { .. }));
        assert_eq!(o.tick(70), TickAction::Idle);
        // Typing again reopens a fresh window.
        o.enqueue(b"b", 100);
        assert!(o.window_open());
        assert!(o.take_started_log(), "starting line logged once per window");
        assert!(!o.take_started_log(), "starting line not logged twice");
        assert_eq!(o.tick(120), TickAction::SendData(b"b".to_vec()));
    }

    #[test]
    fn started_log_fires_once_per_window() {
        let mut o = KeystrokeObfuscator::new(20, 30);
        o.enqueue(b"a", 0);
        assert!(o.take_started_log());
        assert!(!o.take_started_log());
    }
}

#[cfg(all(test, unix))]
mod perm_tests {
    //! Owner / mode checks for `~/.ssh/config` and private identity files.
    use super::*;
    use std::os::unix::fs::PermissionsExt;

    struct Scratch(PathBuf);
    impl Scratch {
        fn new(tag: &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 dir = std::env::temp_dir()
                .join(format!("puressh-perm-{tag}-{}-{nanos}", std::process::id()));
            std::fs::create_dir_all(&dir).unwrap();
            Self(dir)
        }
        fn file(&self, name: &str, mode: u32) -> PathBuf {
            let p = self.0.join(name);
            std::fs::write(&p, b"x").unwrap();
            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode)).unwrap();
            p
        }
    }
    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn identity_too_open_is_refused_with_openssh_banner() {
        let s = Scratch::new("id");
        for mode in [0o644, 0o640, 0o604, 0o660, 0o777] {
            let p = s.file(&format!("key-{mode:o}"), mode);
            let err = check_identity_perms(&p).unwrap_err();
            assert!(
                err.contains("UNPROTECTED PRIVATE KEY FILE"),
                "{mode:o}: {err}"
            );
            assert!(err.contains(&format!("Permissions {mode:04o}")), "{err}");
            assert!(err.contains("will be ignored"), "{err}");
        }
        for mode in [0o600, 0o400, 0o700] {
            let p = s.file(&format!("key-{mode:o}"), mode);
            assert!(check_identity_perms(&p).is_ok(), "{mode:o}");
        }
    }

    #[test]
    fn identity_too_open_is_rejected_by_both_loaders() {
        let s = Scratch::new("load");
        let p = s.file("id_ed25519", 0o644);
        let err = load_identity(p.to_str().unwrap()).unwrap_err();
        assert!(err.contains("UNPROTECTED"), "{err}");
        // Default-discovery path: skipped (warning printed), not an error.
        assert!(matches!(try_load_default_identity(&p), Ok(None)));
    }

    #[test]
    fn identity_missing_is_a_read_error_not_a_perm_error() {
        let s = Scratch::new("missing");
        let err = check_identity_perms(&s.0.join("nope")).unwrap_err();
        assert!(err.starts_with("read "), "{err}");
    }

    #[test]
    fn user_config_group_or_world_writable_is_refused() {
        let s = Scratch::new("cfg");
        for mode in [0o664, 0o646, 0o666, 0o622] {
            let p = s.file(&format!("config-{mode:o}"), mode);
            let err = check_user_config_perms(&p).unwrap_err();
            assert!(
                err.starts_with("Bad owner or permissions on "),
                "{mode:o}: {err}"
            );
        }
        for mode in [0o644, 0o600, 0o444, 0o755] {
            let p = s.file(&format!("config-{mode:o}"), mode);
            assert!(check_user_config_perms(&p).is_ok(), "{mode:o}");
        }
    }

    #[test]
    fn user_config_missing_is_an_error() {
        let s = Scratch::new("cfgmissing");
        assert!(check_user_config_perms(&s.0.join("config")).is_err());
    }
}

#[cfg(test)]
mod target_tests {
    //! Cross-platform tests for the `[user@]host[:port]` and
    //! `[user@]host:path` CLI parsers. These don't need a tty so they're
    //! not gated to `cfg(unix)` (unlike the signal-handler tests below,
    //! which do).
    use super::*;

    #[test]
    fn sanitize_strips_control_and_del() {
        // ESC, OSC-style title set, BEL, CR/LF, TAB, and DEL all become '?'.
        let evil = "ok\x1b]0;pwned\x07\x1b[2Jline2\r\n\ttab\x7fend";
        let out = sanitize_terminal_str(evil);
        assert!(!out.contains('\x1b'), "ESC survived: {out:?}");
        assert!(!out.contains('\x07'), "BEL survived: {out:?}");
        assert!(!out.contains('\r') && !out.contains('\n'), "CR/LF survived");
        assert!(!out.contains('\t'), "TAB survived");
        assert!(!out.contains('\x7f'), "DEL survived");
        // Printable text is preserved; each scrubbed byte maps to one '?'.
        assert!(out.starts_with("ok?]0;pwned?"));
        assert!(out.ends_with("end"));
    }

    #[test]
    fn sanitize_preserves_printable_and_unicode() {
        let s = "Password for café (日本語): ";
        assert_eq!(sanitize_terminal_str(s), s);
    }

    #[test]
    fn parse_target_plain_host_no_port() {
        let (u, h, p) = parse_target("example.com").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "example.com");
        assert_eq!(p, None);
    }

    #[test]
    fn parse_target_user_at_host() {
        let (u, h, p) = parse_target("alice@example.com").unwrap();
        assert_eq!(u.as_deref(), Some("alice"));
        assert_eq!(h, "example.com");
        assert_eq!(p, None);
    }

    #[test]
    fn parse_target_host_with_port() {
        let (u, h, p) = parse_target("example.com:2222").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "example.com");
        assert_eq!(p, Some(2222));
    }

    #[test]
    fn parse_target_user_host_port() {
        let (u, h, p) = parse_target("alice@example.com:2222").unwrap();
        assert_eq!(u.as_deref(), Some("alice"));
        assert_eq!(h, "example.com");
        assert_eq!(p, Some(2222));
    }

    #[test]
    fn parse_target_bare_v6() {
        let (u, h, p) = parse_target("2001:db8::1").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "2001:db8::1");
        assert_eq!(p, None);
    }

    #[test]
    fn parse_target_bracketed_v6_with_port() {
        let (u, h, p) = parse_target("[2001:db8::1]:2222").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "2001:db8::1");
        assert_eq!(p, Some(2222));
    }

    #[test]
    fn parse_target_user_at_bracketed_v6() {
        let (u, h, p) = parse_target("alice@[2001:db8::1]:2222").unwrap();
        assert_eq!(u.as_deref(), Some("alice"));
        assert_eq!(h, "2001:db8::1");
        assert_eq!(p, Some(2222));
    }

    #[test]
    fn parse_target_user_at_bare_v6() {
        // Bare v6 after `user@` — the `@` split removes the user, then
        // parse_host_port sees the bare v6 and accepts it.
        let (u, h, p) = parse_target("alice@2001:db8::1").unwrap();
        assert_eq!(u.as_deref(), Some("alice"));
        assert_eq!(h, "2001:db8::1");
        assert_eq!(p, None);
    }

    #[test]
    fn parse_target_rejects_empty_host() {
        assert!(parse_target("alice@").is_err());
        assert!(parse_target("").is_err());
    }

    #[test]
    fn parse_target_rejects_unmatched_bracket() {
        assert!(parse_target("[2001:db8::1").is_err());
    }

    #[test]
    fn parse_target_brackets_around_any_host() {
        assert_eq!(
            parse_target("deploy@[192.0.2.1]").unwrap(),
            (Some("deploy".into()), "192.0.2.1".into(), None)
        );
        assert_eq!(
            parse_target("[web.example]:2222").unwrap(),
            (None, "web.example".into(), Some(2222))
        );
        assert!(parse_target("[web.example]:x").is_err());
    }

    #[test]
    fn parse_userhost_path_plain() {
        let (u, h, p) = parse_userhost_path("alice@example.com:/etc/motd").unwrap();
        assert_eq!(u.as_deref(), Some("alice"));
        assert_eq!(h, "example.com");
        assert_eq!(p, "/etc/motd");
    }

    #[test]
    fn parse_userhost_path_no_user() {
        let (u, h, p) = parse_userhost_path("example.com:/etc/motd").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "example.com");
        assert_eq!(p, "/etc/motd");
    }

    #[test]
    fn parse_userhost_path_local_rejects_absolute() {
        // A bare absolute path is local, not remote.
        assert!(parse_userhost_path("/etc/motd").is_none());
    }

    #[test]
    fn parse_userhost_path_local_rejects_no_colon() {
        // No `:` -> local path.
        assert!(parse_userhost_path("relative/path").is_none());
    }

    #[test]
    fn parse_userhost_path_bracketed_v6() {
        let (u, h, p) = parse_userhost_path("[2001:db8::1]:/etc/motd").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "2001:db8::1");
        assert_eq!(p, "/etc/motd");
    }

    #[test]
    fn parse_userhost_path_user_at_bracketed_v6() {
        let (u, h, p) = parse_userhost_path("alice@[2001:db8::1]:/etc/motd").unwrap();
        assert_eq!(u.as_deref(), Some("alice"));
        assert_eq!(h, "2001:db8::1");
        assert_eq!(p, "/etc/motd");
    }

    #[test]
    fn parse_userhost_path_preserves_colons_in_path() {
        // Path may contain extra colons (Windows-style drive letters or
        // SCP-of-SCP-style nested targets); only the first separator is
        // used as the host/path boundary.
        let (u, h, p) = parse_userhost_path("host:/a:b:c").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "host");
        assert_eq!(p, "/a:b:c");
    }

    #[test]
    fn parse_userhost_path_bracketed_v6_path_with_colons() {
        let (u, h, p) = parse_userhost_path("[2001:db8::1]:/a:b").unwrap();
        assert_eq!(u, None);
        assert_eq!(h, "2001:db8::1");
        assert_eq!(p, "/a:b");
    }

    #[test]
    fn parse_userhost_path_bracketed_v6_unmatched_bracket() {
        assert!(parse_userhost_path("[2001:db8::1/path").is_none());
    }
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use core::sync::atomic::Ordering;

    /// Read back the current `sigaction` for `sig` via `sigaction(NULL, prev)`.
    /// Returns the handler pointer value (`sa_sigaction`) — `0` is SIG_DFL,
    /// `1` is SIG_IGN, anything else is a function pointer.
    fn current_handler_ptr(sig: libc::c_int) -> usize {
        // SAFETY: passing NULL for the new disposition leaves the signal
        // alone; we only read the previous via the out param.
        unsafe {
            let mut prev: libc::sigaction = core::mem::zeroed();
            let rc = libc::sigaction(sig, core::ptr::null(), &mut prev);
            assert_eq!(rc, 0, "sigaction(read) failed");
            prev.sa_sigaction
        }
    }

    /// Install/uninstall the signal handler on its own (without going
    /// through `TermiosRawGuard::install`, which would also try to
    /// `tcsetattr` stdin — fine in cargo test where stdin is not a tty
    /// and the call is a silent no-op, but the bookkeeping is what we
    /// care about here).
    ///
    /// Asserts that:
    ///   1. After `install_signal_handler` returns true, the four signal
    ///      handlers point at our `termios_signal::handler`.
    ///   2. A second `install_signal_handler` call returns false (the
    ///      slot is already owned).
    ///   3. After `uninstall_signal_handler`, none of the four signals
    ///      still has *our* handler installed — they've reverted to
    ///      whatever was there before (typically SIG_DFL in the test
    ///      runner, though the test does not assert that exact value
    ///      because libtest is free to install its own dispositions).
    ///   4. A fresh `install_signal_handler` after the clean uninstall
    ///      succeeds.
    #[test]
    fn signal_handler_install_cycle_is_clean() {
        // Capture pre-install dispositions so we can assert the
        // uninstall path restored *something other than* our handler.
        let pre = [
            current_handler_ptr(libc::SIGINT),
            current_handler_ptr(libc::SIGTERM),
            current_handler_ptr(libc::SIGHUP),
            current_handler_ptr(libc::SIGQUIT),
        ];

        // SAFETY: zero-init is the documented way to allocate a termios
        // struct; we never call `tcsetattr` with it in this test, we
        // only stash a copy in the static.
        let original: libc::termios = unsafe { core::mem::zeroed() };

        // First install.
        let installed = install_signal_handler(0, &original);
        assert!(installed, "first install should succeed");
        assert!(
            termios_signal::INSTALLED.load(Ordering::Acquire),
            "INSTALLED must be true after first install"
        );
        let our_handler = termios_signal::handler as *const () as usize;
        for &sig in &termios_signal::SIGNALS {
            assert_eq!(
                current_handler_ptr(sig),
                our_handler,
                "signal {sig} should now point at our handler"
            );
        }

        // Second install must refuse (nested guard contract).
        let second = install_signal_handler(0, &original);
        assert!(!second, "second install while one is active must fail");

        // Uninstall.
        uninstall_signal_handler();
        assert!(
            !termios_signal::INSTALLED.load(Ordering::Acquire),
            "INSTALLED must be false after uninstall"
        );
        assert_eq!(
            termios_signal::SAVED_FD.load(Ordering::Acquire),
            -1,
            "SAVED_FD must be cleared after uninstall"
        );
        for (sig, &prev_ptr) in termios_signal::SIGNALS.iter().zip(pre.iter()) {
            let now = current_handler_ptr(*sig);
            assert_ne!(
                now, our_handler,
                "signal {sig} still points at our handler after uninstall"
            );
            assert_eq!(
                now, prev_ptr,
                "signal {sig} disposition was not restored to its pre-install value"
            );
        }

        // Fresh install after a clean uninstall must succeed.
        let reinstall = install_signal_handler(0, &original);
        assert!(reinstall, "fresh install after uninstall must succeed");
        uninstall_signal_handler();
    }
}