puressh 0.2.4

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
//! C ABI for the `KnownHosts` store: build, persist, lookup, mutate,
//! plus a `pcssh_client_connect_known_hosts` policy variant that
//! verifies the server host key against the store on connect.
//!
//! The Rust-side handle [`PcSshKnownHosts`] wraps the store in
//! `Arc<Mutex<KnownHosts>>` so a single FFI handle can both be operated
//! on through `pcssh_known_hosts_*` and be plugged into a connect-time
//! [`HostKeyPolicy::KnownHosts`] policy simultaneously (the lib's
//! [`KnownHostsPolicy::store`] field is also `Arc<Mutex<KnownHosts>>`).
//!
//! Every entry point grabs the mutex for the duration of one Rust call.
//! Concurrent use from multiple OS threads is safe; they serialise.

use core::ffi::{c_char, c_int};
use core::ptr;
use std::ffi::c_void;
use std::path::PathBuf;
use std::slice;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use super::client::{PcSshClient, connect_bounded, timeout_from_ms};
use super::common::{
    PCSSH_ERR_BUFFER_TOO_SMALL, PCSSH_ERR_GENERIC, PCSSH_ERR_INVALID_ARGUMENT, PCSSH_ERR_IO,
    PCSSH_OK, catch, slice_len_ok, with_cstr, with_two_cstr,
};
use crate::client::{Config, HostKeyPolicy, KnownHostsPolicy, TofuAction, TofuPromptFn};
use crate::known_hosts::{KnownHosts, LookupResult};
use crate::shared::SharedClient;

/// Lookup-result variant returned by [`pcssh_known_hosts_lookup`]: an
/// exact host+key match was found.
pub const PCSSH_KH_MATCH: c_int = 0;
/// Lookup-result variant: at least one entry matched the host, but no
/// entry's key matched. This is the security-relevant case — refuse the
/// connection.
pub const PCSSH_KH_MISMATCH: c_int = 1;
/// Lookup-result variant: no entry matched the host. The caller decides
/// whether to TOFU-add.
pub const PCSSH_KH_UNKNOWN: c_int = 2;

/// TOFU action: refuse the connection (equivalent to OpenSSH's
/// `StrictHostKeyChecking=yes`).
pub const PCSSH_TOFU_REJECT: c_int = 0;
/// TOFU action: accept silently and (optionally) save back.
pub const PCSSH_TOFU_ACCEPT: c_int = 1;
/// TOFU action: invoke the C callback to decide.
pub const PCSSH_TOFU_PROMPT: c_int = 2;

/// Opaque handle to an in-memory `known_hosts` store.
///
/// Internally backed by `Arc<Mutex<KnownHosts>>` so the same handle can
/// be plugged into [`pcssh_client_connect_known_hosts`] and continue to
/// receive `pcssh_known_hosts_*` mutations afterwards.
pub struct PcSshKnownHosts {
    pub(crate) inner: Arc<Mutex<KnownHosts>>,
}

/// TOFU prompt callback signature for
/// [`pcssh_client_connect_known_hosts`].
///
/// Invoked when the connecting host is unknown to the store and
/// `on_unknown == PCSSH_TOFU_PROMPT`. Return `1` to accept (and the
/// callback is expected to have shown the user the fingerprint), `0` to
/// reject.
///
/// Arguments mirror the underlying [`crate::client::TofuPromptFn`]:
/// host, port, algorithm name, key blob.
///
/// Contract:
///
/// - Runs synchronously on the thread that called
///   `pcssh_client_connect_known_hosts`, in the middle of the handshake
///   (the connect blocks until the callback returns).
/// - `host`, `algorithm` and `key_blob` point into library-owned
///   storage that is valid **only for the duration of the callback**;
///   copy anything that must outlive it.
/// - The store handle passed to the connect is *not* locked while the
///   callback runs, so calling `pcssh_known_hosts_*` on that same
///   handle from inside the callback (e.g. to inspect or pre-add the
///   entry) is allowed.
/// - `ctx` is the caller's `prompt_ctx`, passed through untouched.
pub type PcSshTofuPromptCb = Option<
    unsafe extern "C" fn(
        ctx: *mut c_void,
        host: *const c_char,
        port: u16,
        algorithm: *const c_char,
        key_blob: *const u8,
        key_blob_len: usize,
    ) -> c_int,
>;

/// Allocate an empty `known_hosts` store.
///
/// # Safety
///
/// `out` must be non-NULL and point to writable storage for one
/// `*mut PcSshKnownHosts`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_new(out: *mut *mut PcSshKnownHosts) -> c_int {
    catch(|| {
        if out.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: `out` non-NULL per caller contract. Zero up-front so
        // the post-condition "on error, `*out` is NULL" holds for any
        // future error path added between here and the success write.
        unsafe { *out = ptr::null_mut() };
        let kh = PcSshKnownHosts {
            inner: Arc::new(Mutex::new(KnownHosts::new())),
        };
        // SAFETY: `out` non-NULL per caller contract.
        unsafe { *out = Box::into_raw(Box::new(kh)) };
        PCSSH_OK
    })
}

/// Load an OpenSSH-format `known_hosts` file. A missing file yields an
/// empty store (matches OpenSSH client behaviour).
///
/// # Safety
///
/// - `path` must be NUL-terminated, valid UTF-8.
/// - `out` must be non-NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_load(
    path: *const c_char,
    out: *mut *mut PcSshKnownHosts,
) -> c_int {
    catch(|| {
        if out.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: caller contract.
        unsafe { *out = ptr::null_mut() };
        // SAFETY: caller contract.
        with_cstr(path, |path_s| {
            let kh = match KnownHosts::load(path_s) {
                Ok(k) => k,
                Err(_) => return PCSSH_ERR_IO,
            };
            let boxed = PcSshKnownHosts {
                inner: Arc::new(Mutex::new(kh)),
            };
            // SAFETY: out non-NULL.
            unsafe { *out = Box::into_raw(Box::new(boxed)) };
            PCSSH_OK
        })
        .unwrap_or(PCSSH_ERR_INVALID_ARGUMENT)
    })
}

/// Atomically save the store to `path` (writes `path.tmp` then
/// renames).
///
/// # Safety
///
/// - `kh` must be a valid handle returned by `pcssh_known_hosts_*`.
/// - `path` must be NUL-terminated, valid UTF-8.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_save(
    kh: *const PcSshKnownHosts,
    path: *const c_char,
) -> c_int {
    catch(|| {
        if kh.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: caller contract.
        with_cstr(path, |path_s| {
            // SAFETY: kh non-NULL per check.
            let h = unsafe { &*kh };
            let g = match h.inner.lock() {
                Ok(g) => g,
                Err(_) => return PCSSH_ERR_GENERIC,
            };
            match g.save(path_s) {
                Ok(()) => PCSSH_OK,
                Err(_) => PCSSH_ERR_IO,
            }
        })
        .unwrap_or(PCSSH_ERR_INVALID_ARGUMENT)
    })
}

/// Parse a `known_hosts` file from a byte buffer.
///
/// # Safety
///
/// - `buf` must point to at least `len` readable bytes.
/// - `out` must be non-NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_from_bytes(
    buf: *const u8,
    len: usize,
    out: *mut *mut PcSshKnownHosts,
) -> c_int {
    catch(|| {
        if out.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: out non-NULL per check. Zero up-front so the
        // post-condition "on error, `*out` is NULL" stays correct for
        // every error path below (including the argument checks) —
        // matches the convention used by other constructors
        // (`pcssh_known_hosts_load`, `pcssh_agent_connect`, …).
        unsafe { *out = ptr::null_mut() };
        if (buf.is_null() && len != 0) || !slice_len_ok(len) {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: caller contract; len=0 is empty slice; len bounded above.
        let bytes = if len == 0 {
            &[][..]
        } else {
            unsafe { slice::from_raw_parts(buf, len) }
        };
        let kh = KnownHosts::from_bytes(bytes);
        let boxed = PcSshKnownHosts {
            inner: Arc::new(Mutex::new(kh)),
        };
        // SAFETY: out non-NULL.
        unsafe { *out = Box::into_raw(Box::new(boxed)) };
        PCSSH_OK
    })
}

/// Serialise the store to a caller-supplied buffer. Writes the required
/// length to `*out_len`; if `cap < required`, returns
/// [`PCSSH_ERR_BUFFER_TOO_SMALL`] (the length still being written so the
/// caller can resize).
///
/// # Safety
///
/// - `kh` must be a valid handle.
/// - `buf` may be NULL only if `cap == 0`.
/// - `out_len` must be non-NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_to_bytes(
    kh: *const PcSshKnownHosts,
    buf: *mut u8,
    cap: usize,
    out_len: *mut usize,
) -> c_int {
    catch(|| {
        if kh.is_null() || out_len.is_null() || (buf.is_null() && cap != 0) {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: kh non-NULL.
        let h = unsafe { &*kh };
        let g = match h.inner.lock() {
            Ok(g) => g,
            Err(_) => return PCSSH_ERR_GENERIC,
        };
        let data = g.to_bytes();
        let need = data.len();
        // SAFETY: out_len non-NULL.
        unsafe { *out_len = need };
        if need > cap {
            return PCSSH_ERR_BUFFER_TOO_SMALL;
        }
        if need > 0 {
            // SAFETY: cap >= need bytes writable at buf.
            unsafe { ptr::copy_nonoverlapping(data.as_ptr(), buf, need) };
        }
        PCSSH_OK
    })
}

/// Look up `(host, port, algorithm, key_blob)` in the store. The result
/// variant is written to `*out_result` (one of `PCSSH_KH_MATCH`,
/// `PCSSH_KH_MISMATCH`, `PCSSH_KH_UNKNOWN`).
///
/// `Mismatch` does not surface the list of expected keys through this
/// API; an enriched `pcssh_known_hosts_find` returning the expected
/// keys is deferred to a future revision.
///
/// # Safety
///
/// - `kh` must be a valid handle.
/// - `host`, `algorithm` must be NUL-terminated valid UTF-8.
/// - `key_blob` must point to at least `key_blob_len` readable bytes.
/// - `out_result` must be non-NULL.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_lookup(
    kh: *const PcSshKnownHosts,
    host: *const c_char,
    port: u16,
    algorithm: *const c_char,
    key_blob: *const u8,
    key_blob_len: usize,
    out_result: *mut c_int,
) -> c_int {
    catch(|| {
        if kh.is_null() || out_result.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        if (key_blob.is_null() && key_blob_len != 0) || !slice_len_ok(key_blob_len) {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: caller contract for both strings.
        with_two_cstr(host, algorithm, |host_s, alg_s| {
            // SAFETY: caller contract; len=0 yields empty slice; len bounded above.
            let blob = if key_blob_len == 0 {
                &[][..]
            } else {
                unsafe { slice::from_raw_parts(key_blob, key_blob_len) }
            };
            // SAFETY: kh non-NULL.
            let h = unsafe { &*kh };
            let g = match h.inner.lock() {
                Ok(g) => g,
                Err(_) => return PCSSH_ERR_GENERIC,
            };
            let r = match g.lookup(host_s, port, alg_s, blob) {
                LookupResult::Match => PCSSH_KH_MATCH,
                LookupResult::Mismatch { .. } => PCSSH_KH_MISMATCH,
                LookupResult::Unknown => PCSSH_KH_UNKNOWN,
                // A revoked key is reported as a mismatch at the C ABI (the
                // fail-closed answer); the Rust `LookupResult::Revoked`
                // variant is what the in-crate client refuses on
                // unconditionally.
                LookupResult::Revoked => PCSSH_KH_MISMATCH,
            };
            // SAFETY: out_result non-NULL.
            unsafe { *out_result = r };
            PCSSH_OK
        })
        .unwrap_or(PCSSH_ERR_INVALID_ARGUMENT)
    })
}

/// Append a new entry. If `hash_host != 0`, the host pattern is stored
/// as an HMAC-SHA1 hash (OpenSSH's `HashKnownHosts yes`).
///
/// A `host` or `algorithm` that cannot be written as one well-formed line
/// (whitespace / control characters, `,`, or a leading `@`, `|` or `#`) is
/// refused with `PCSSH_ERR_INVALID_ARGUMENT`; nothing is added.
///
/// # Safety
///
/// - `kh` must be a valid handle.
/// - `host`, `algorithm` must be NUL-terminated valid UTF-8.
/// - `key_blob` must point to at least `key_blob_len` readable bytes.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_add(
    kh: *mut PcSshKnownHosts,
    host: *const c_char,
    port: u16,
    algorithm: *const c_char,
    key_blob: *const u8,
    key_blob_len: usize,
    hash_host: c_int,
) -> c_int {
    catch(|| {
        if kh.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        if (key_blob.is_null() && key_blob_len != 0) || !slice_len_ok(key_blob_len) {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: caller contract for both strings.
        with_two_cstr(host, algorithm, |host_s, alg_s| {
            // SAFETY: caller contract; len=0 → empty; len bounded above.
            let blob = if key_blob_len == 0 {
                &[][..]
            } else {
                unsafe { slice::from_raw_parts(key_blob, key_blob_len) }
            };
            // SAFETY: kh non-NULL.
            let h = unsafe { &*kh };
            let mut g = match h.inner.lock() {
                Ok(g) => g,
                Err(_) => return PCSSH_ERR_GENERIC,
            };
            match g.try_add(host_s, port, alg_s, blob, hash_host != 0) {
                Ok(()) => PCSSH_OK,
                Err(_) => PCSSH_ERR_INVALID_ARGUMENT,
            }
        })
        .unwrap_or(PCSSH_ERR_INVALID_ARGUMENT)
    })
}

/// Remove every entry matching `host[:port]`. Writes the count to
/// `*out_removed` if non-NULL.
///
/// # Safety
///
/// - `kh` must be a valid handle.
/// - `host` must be NUL-terminated valid UTF-8.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_remove(
    kh: *mut PcSshKnownHosts,
    host: *const c_char,
    port: u16,
    out_removed: *mut usize,
) -> c_int {
    catch(|| {
        if kh.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: caller contract.
        with_cstr(host, |host_s| {
            // SAFETY: kh non-NULL.
            let h = unsafe { &*kh };
            let mut g = match h.inner.lock() {
                Ok(g) => g,
                Err(_) => return PCSSH_ERR_GENERIC,
            };
            let n = g.remove(host_s, port);
            if !out_removed.is_null() {
                // SAFETY: caller contract.
                unsafe { *out_removed = n };
            }
            PCSSH_OK
        })
        .unwrap_or(PCSSH_ERR_INVALID_ARGUMENT)
    })
}

/// Hash every plain entry in the store using a fresh salt — the
/// equivalent of `ssh-keygen -H`.
///
/// # Safety
///
/// `kh` must be a valid handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_hash_in_place(kh: *mut PcSshKnownHosts) -> c_int {
    catch(|| {
        if kh.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: kh non-NULL.
        let h = unsafe { &*kh };
        let mut g = match h.inner.lock() {
            Ok(g) => g,
            Err(_) => return PCSSH_ERR_GENERIC,
        };
        g.hash_in_place();
        PCSSH_OK
    })
}

/// Free a `known_hosts` handle. Safe to call with NULL.
///
/// # Safety
///
/// `kh` must either be NULL, or a pointer previously returned by a
/// `pcssh_known_hosts_*` constructor that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_known_hosts_free(kh: *mut PcSshKnownHosts) {
    if kh.is_null() {
        return;
    }
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        // SAFETY: pointer originally from Box::into_raw, caller no double-free.
        let _ = unsafe { Box::from_raw(kh) };
    }));
}

/// Connect to `host:port`, run version-exchange + KEX with a
/// [`HostKeyPolicy::KnownHosts`] policy backed by `kh`.
///
/// `on_unknown` is one of `PCSSH_TOFU_REJECT`, `PCSSH_TOFU_ACCEPT`, or
/// `PCSSH_TOFU_PROMPT`. With `PROMPT`, `prompt_cb` is invoked; with
/// `ACCEPT` and a non-NULL `save_path`, the new entry is also persisted
/// back. `hash_new != 0` requests that newly added entries be hashed.
///
/// Mismatch is always a hard reject (host known, wrong key).
///
/// `timeout_ms`, address iteration and IPv6-literal handling follow
/// [`pcssh_client_connect_ex`](super::client::pcssh_client_connect_ex)
/// exactly — both go through the same private `connect_bounded` helper.
///
/// # Safety
///
/// - `host` (and `save_path` if non-NULL) must be NUL-terminated valid
///   UTF-8.
/// - `kh` must be a valid handle.
/// - `out_client` must be non-NULL.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn pcssh_client_connect_known_hosts(
    host: *const c_char,
    port: u16,
    timeout_ms: i32,
    kh: *mut PcSshKnownHosts,
    on_unknown: c_int,
    prompt_cb: PcSshTofuPromptCb,
    prompt_ctx: *mut c_void,
    save_path: *const c_char,
    hash_new: c_int,
    out_client: *mut *mut PcSshClient,
) -> c_int {
    catch(|| {
        if out_client.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // SAFETY: caller contract.
        unsafe { *out_client = ptr::null_mut() };
        if kh.is_null() {
            return PCSSH_ERR_INVALID_ARGUMENT;
        }
        // Optional save_path: NULL keeps None; non-NULL must be valid UTF-8
        // (the previous code returned PCSSH_ERR_INVALID_ARGUMENT on
        // non-UTF-8, matching what `with_cstr` reports via `None`).
        let save_path_opt: Option<PathBuf> = if save_path.is_null() {
            None
        } else {
            // SAFETY: caller contract.
            match with_cstr(save_path, |s| PathBuf::from(s)) {
                Some(p) => Some(p),
                None => return PCSSH_ERR_INVALID_ARGUMENT,
            }
        };

        // SAFETY: caller contract on `host`.
        with_cstr(host, |host_s| {
            let timeout = timeout_from_ms(timeout_ms);

            // The header promises `prompt_cb` / `prompt_ctx` are only used
            // during this call. The closure lives on in the client (a
            // re-key could reach it), so it is armed only until the connect
            // returns; disarmed, it refuses without calling into C.
            let armed = Arc::new(AtomicBool::new(true));
            let armed_cb = Arc::clone(&armed);

            // Build the TOFU prompt (if any) from the C side. Kept as a
            // bare `Arc` so the per-address `make_cfg` below can rebuild
            // a fresh `TofuAction` each time (`Config` is not `Clone`).
            let prompt: Option<Arc<TofuPromptFn>> = match on_unknown {
                PCSSH_TOFU_REJECT | PCSSH_TOFU_ACCEPT => None,
                PCSSH_TOFU_PROMPT => match prompt_cb {
                    Some(cb) => {
                        // Capture the raw pointer as an integer so the closure
                        // is Send + Sync. The caller promises the context is
                        // live for the duration of the connect.
                        let ctx_addr = prompt_ctx as usize;
                        Some(Arc::new(
                            move |host: &str, port: u16, alg: &str, blob: &[u8]| -> bool {
                                if !armed_cb.load(Ordering::SeqCst) {
                                    return false;
                                }
                                let h_cs = match std::ffi::CString::new(host) {
                                    Ok(c) => c,
                                    Err(_) => return false,
                                };
                                let a_cs = match std::ffi::CString::new(alg) {
                                    Ok(c) => c,
                                    Err(_) => return false,
                                };
                                // SAFETY: function pointer validity + lifetime
                                // upheld by the C caller per docs.
                                let rc = unsafe {
                                    cb(
                                        ctx_addr as *mut c_void,
                                        h_cs.as_ptr(),
                                        port,
                                        a_cs.as_ptr(),
                                        blob.as_ptr(),
                                        blob.len(),
                                    )
                                };
                                rc != 0
                            },
                        ))
                    }
                    None => return PCSSH_ERR_INVALID_ARGUMENT,
                },
                _ => return PCSSH_ERR_INVALID_ARGUMENT,
            };

            // SAFETY: kh non-NULL.
            let kh_handle = unsafe { &*kh };
            let store = Arc::clone(&kh_handle.inner);

            let make_cfg = || {
                let on_unknown = match &prompt {
                    Some(p) => TofuAction::Prompt(Arc::clone(p)),
                    None if on_unknown == PCSSH_TOFU_ACCEPT => TofuAction::Accept,
                    None => TofuAction::Reject,
                };
                let policy = KnownHostsPolicy {
                    store: Arc::clone(&store),
                    save_path: save_path_opt.clone(),
                    hash_new: hash_new != 0,
                    on_unknown,
                    // FFI callers that want loud-but-permissive mismatch can
                    // upgrade to a future pcssh_client_connect_known_hosts_ex
                    // taking an on_mismatch action; the default here matches
                    // OpenSSH's `StrictHostKeyChecking=yes` for mismatches.
                    on_mismatch: TofuAction::Reject,
                    global: Vec::new(),
                    host_key_alias: None,
                    revoked: None,
                    command: None,
                };
                Config {
                    host_key_policy: HostKeyPolicy::KnownHosts(policy),
                    timeout,
                    algorithms: Default::default(),
                    pinned_host_key: None,
                }
            };

            let res = connect_bounded(host_s, port, timeout, make_cfg);
            armed.store(false, Ordering::SeqCst);
            match res {
                Ok(c) => {
                    let boxed = Box::new(PcSshClient {
                        inner: SharedClient::from(c),
                    });
                    // SAFETY: out_client non-NULL.
                    unsafe { *out_client = Box::into_raw(boxed) };
                    PCSSH_OK
                }
                Err(code) => code,
            }
        })
        .unwrap_or(PCSSH_ERR_INVALID_ARGUMENT)
    })
}

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

    #[test]
    fn free_null_is_safe() {
        // SAFETY: NULL is the documented safe input.
        unsafe { pcssh_known_hosts_free(ptr::null_mut()) };
    }

    #[test]
    fn new_then_free() {
        let mut h: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: well-formed inputs.
        let rc = unsafe { pcssh_known_hosts_new(&mut h) };
        assert_eq!(rc, PCSSH_OK);
        assert!(!h.is_null());
        // SAFETY: handle returned from pcssh_known_hosts_new.
        unsafe { pcssh_known_hosts_free(h) };
    }

    #[test]
    fn lookup_empty_is_unknown() {
        let mut h: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: well-formed inputs.
        unsafe { pcssh_known_hosts_new(&mut h) };
        let host = CString::new("example.com").unwrap();
        let alg = CString::new("ssh-ed25519").unwrap();
        let blob = [1u8, 2, 3];
        let mut r: c_int = -1;
        // SAFETY: well-formed inputs.
        let rc = unsafe {
            pcssh_known_hosts_lookup(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                &mut r,
            )
        };
        assert_eq!(rc, PCSSH_OK);
        assert_eq!(r, PCSSH_KH_UNKNOWN);
        // SAFETY: handle from new.
        unsafe { pcssh_known_hosts_free(h) };
    }

    #[test]
    fn add_then_lookup_matches() {
        let mut h: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: well-formed inputs.
        unsafe { pcssh_known_hosts_new(&mut h) };
        let host = CString::new("example.com").unwrap();
        let alg = CString::new("ssh-ed25519").unwrap();
        let blob = [9u8, 8, 7, 6];
        // SAFETY: handle valid, strings NUL-terminated.
        let rc = unsafe {
            pcssh_known_hosts_add(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                0,
            )
        };
        assert_eq!(rc, PCSSH_OK);
        let mut r: c_int = -1;
        // SAFETY: handle valid.
        let rc = unsafe {
            pcssh_known_hosts_lookup(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                &mut r,
            )
        };
        assert_eq!(rc, PCSSH_OK);
        assert_eq!(r, PCSSH_KH_MATCH);
        // SAFETY: handle valid.
        unsafe { pcssh_known_hosts_free(h) };
    }

    #[test]
    fn add_refuses_line_injection() {
        let mut h: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: well-formed inputs.
        unsafe { pcssh_known_hosts_new(&mut h) };
        let host = CString::new("example.com").unwrap();
        let alg = CString::new("ssh-ed25519\n* ssh-ed25519 AAAA").unwrap();
        let blob = [9u8, 8, 7, 6];
        // SAFETY: handle valid, strings NUL-terminated.
        let rc = unsafe {
            pcssh_known_hosts_add(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                0,
            )
        };
        assert_eq!(rc, PCSSH_ERR_INVALID_ARGUMENT);
        // SAFETY: handle valid.
        assert!(unsafe { &*h }.inner.lock().unwrap().to_bytes().is_empty());
        // SAFETY: handle valid.
        unsafe { pcssh_known_hosts_free(h) };
    }

    #[test]
    fn add_wrong_key_is_mismatch() {
        let mut h: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: well-formed inputs.
        unsafe { pcssh_known_hosts_new(&mut h) };
        let host = CString::new("example.com").unwrap();
        let alg = CString::new("ssh-ed25519").unwrap();
        let blob_good = [1u8, 2, 3];
        let blob_bad = [4u8, 5, 6];
        // SAFETY: handle valid.
        unsafe {
            pcssh_known_hosts_add(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob_good.as_ptr(),
                blob_good.len(),
                0,
            )
        };
        let mut r: c_int = -1;
        // SAFETY: handle valid.
        unsafe {
            pcssh_known_hosts_lookup(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob_bad.as_ptr(),
                blob_bad.len(),
                &mut r,
            )
        };
        assert_eq!(r, PCSSH_KH_MISMATCH);
        // SAFETY: handle valid.
        unsafe { pcssh_known_hosts_free(h) };
    }

    #[test]
    fn to_bytes_then_from_bytes_roundtrip() {
        let mut h: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: well-formed.
        unsafe { pcssh_known_hosts_new(&mut h) };
        let host = CString::new("a.example").unwrap();
        let alg = CString::new("ssh-ed25519").unwrap();
        let blob = [1u8, 2, 3, 4];
        // SAFETY: handle valid.
        unsafe {
            pcssh_known_hosts_add(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                0,
            )
        };
        // Two-pass: query size, then write.
        let mut need: usize = 0;
        // SAFETY: handle valid, cap=0 + buf=null is documented.
        let rc = unsafe { pcssh_known_hosts_to_bytes(h, ptr::null_mut(), 0, &mut need) };
        assert_eq!(rc, PCSSH_ERR_BUFFER_TOO_SMALL);
        assert!(need > 0);
        let mut buf = vec![0u8; need];
        let mut got: usize = 0;
        // SAFETY: handle valid, buf has need bytes.
        let rc = unsafe { pcssh_known_hosts_to_bytes(h, buf.as_mut_ptr(), buf.len(), &mut got) };
        assert_eq!(rc, PCSSH_OK);
        assert_eq!(got, need);

        // Parse back.
        let mut h2: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: buf has `got` readable bytes.
        let rc = unsafe { pcssh_known_hosts_from_bytes(buf.as_ptr(), got, &mut h2) };
        assert_eq!(rc, PCSSH_OK);
        let mut r: c_int = -1;
        // SAFETY: h2 valid.
        unsafe {
            pcssh_known_hosts_lookup(
                h2,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                &mut r,
            )
        };
        assert_eq!(r, PCSSH_KH_MATCH);
        // SAFETY: handles valid.
        unsafe {
            pcssh_known_hosts_free(h);
            pcssh_known_hosts_free(h2);
        };
    }

    #[test]
    fn remove_then_lookup_unknown() {
        let mut h: *mut PcSshKnownHosts = ptr::null_mut();
        // SAFETY: well-formed.
        unsafe { pcssh_known_hosts_new(&mut h) };
        let host = CString::new("rm.example").unwrap();
        let alg = CString::new("ssh-ed25519").unwrap();
        let blob = [7u8; 8];
        // SAFETY: handle valid.
        unsafe {
            pcssh_known_hosts_add(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                0,
            )
        };
        let mut n: usize = 0;
        // SAFETY: handle valid.
        let rc = unsafe { pcssh_known_hosts_remove(h, host.as_ptr(), 22, &mut n) };
        assert_eq!(rc, PCSSH_OK);
        assert_eq!(n, 1);
        let mut r: c_int = -1;
        // SAFETY: handle valid.
        unsafe {
            pcssh_known_hosts_lookup(
                h,
                host.as_ptr(),
                22,
                alg.as_ptr(),
                blob.as_ptr(),
                blob.len(),
                &mut r,
            )
        };
        assert_eq!(r, PCSSH_KH_UNKNOWN);
        // SAFETY: handle valid.
        unsafe { pcssh_known_hosts_free(h) };
    }
}