bssh 2.4.1

Parallel SSH command execution tool for cluster management
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
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SSH connection management and establishment.
//!
//! This module handles the low-level SSH connection establishment,
//! including address resolution, connection attempts, and initial handshake.

use russh::client::{Config, Handle, Handler};
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use std::{fmt::Debug, io};

use super::address_family::AddressFamily;
use super::authentication::{AuthMethod, ServerCheckMethod};
use crate::ssh::SshConfig;

/// Default keepalive interval in seconds.
///
/// This is intentionally below common 60-second idle reapers so the client
/// sends traffic before the remote side or an intermediate gateway decides the
/// session is idle.
pub const DEFAULT_KEEPALIVE_INTERVAL: u64 = 30;

/// Default maximum keepalive attempts before considering connection dead.
/// With the default interval and max, connection failure is detected within
/// about 120s: three unanswered probes plus the next timer tick that observes
/// they were missed.
pub const DEFAULT_KEEPALIVE_MAX: usize = 3;

/// SSH connection configuration for keepalive and timeout settings.
///
/// This struct provides a centralized way to configure SSH connection
/// parameters, particularly for keepalive functionality which prevents
/// idle connections from being terminated by firewalls or NAT devices.
///
/// # Example
///
/// ```no_run
/// use bssh::ssh::tokio_client::SshConnectionConfig;
///
/// // Use defaults (30s interval, 3 max attempts)
/// let config = SshConnectionConfig::default();
///
/// // Custom configuration
/// let config = SshConnectionConfig::new()
///     .with_keepalive_interval(Some(15))
///     .with_keepalive_max(5);
///
/// // Disable keepalive
/// let config = SshConnectionConfig::new()
///     .with_keepalive_interval(None);
/// ```
#[derive(Debug, Clone)]
pub struct SshConnectionConfig {
    /// Interval in seconds between keepalive packets.
    /// None disables keepalive.
    /// Default: 30 seconds
    pub keepalive_interval: Option<u64>,

    /// Maximum number of keepalive packets to send without response
    /// before considering the connection dead.
    /// Default: 3
    pub keepalive_max: usize,

    /// Whether the ssh_config `Compression` directive resolved to `yes`.
    ///
    /// `false` (the default) matches `Compression no`/unset and advertises
    /// only `none` compression to the server. `true` matches `Compression
    /// yes` and advertises eager `zlib` ahead of `none`. See
    /// [`to_russh_config`](Self::to_russh_config) for why `zlib@openssh.com`
    /// is never advertised regardless of this flag.
    pub compression: bool,

    /// Which IP address family the connection may use.
    ///
    /// [`AddressFamily::Any`] (the default) tries every resolved address in
    /// resolver order, which is the historical behavior. The forced variants
    /// come from `-4`/`-6` or the ssh_config `AddressFamily` keyword and are
    /// applied in [`Client::connect_with_ssh_config`]; see `ARCHITECTURE.md`
    /// ("Address Family Preference") for the scope of that constraint.
    pub address_family: AddressFamily,
}

impl Default for SshConnectionConfig {
    fn default() -> Self {
        Self {
            keepalive_interval: Some(DEFAULT_KEEPALIVE_INTERVAL),
            keepalive_max: DEFAULT_KEEPALIVE_MAX,
            compression: false,
            address_family: AddressFamily::Any,
        }
    }
}

/// Resolves SSH connection settings for a concrete target host.
///
/// The dispatcher builds this once from the CLI flags, YAML defaults, and the
/// parsed ssh_config. Per-node execution then calls
/// [`resolve_for_host`](Self::resolve_for_host) at the last responsible moment
/// so `Host <name>` blocks apply to the actual destination or jump hop instead
/// of a once-per-dispatch fallback.
#[derive(Debug, Clone, Default)]
pub struct SshConnectionConfigResolver {
    fixed_config: Option<SshConnectionConfig>,
    ssh_config: Option<SshConfig>,
    cli_keepalive_interval: Option<u64>,
    cli_keepalive_max: Option<usize>,
    yaml_keepalive_interval: Option<u64>,
    yaml_keepalive_max: Option<usize>,
    cli_address_family: Option<AddressFamily>,
}

impl SshConnectionConfigResolver {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn fixed(config: SshConnectionConfig) -> Self {
        Self {
            fixed_config: Some(config),
            ..Self::default()
        }
    }

    #[must_use]
    pub fn with_ssh_config(mut self, ssh_config: Option<SshConfig>) -> Self {
        self.ssh_config = ssh_config;
        self
    }

    #[must_use]
    pub fn with_cli_keepalive_interval(mut self, interval: Option<u64>) -> Self {
        self.cli_keepalive_interval = interval;
        self
    }

    #[must_use]
    pub fn with_cli_keepalive_max(mut self, max: Option<usize>) -> Self {
        self.cli_keepalive_max = max;
        self
    }

    #[must_use]
    pub fn with_yaml_keepalive_interval(mut self, interval: Option<u64>) -> Self {
        self.yaml_keepalive_interval = interval;
        self
    }

    #[must_use]
    pub fn with_yaml_keepalive_max(mut self, max: Option<usize>) -> Self {
        self.yaml_keepalive_max = max;
        self
    }

    #[must_use]
    pub fn with_cli_address_family(mut self, family: Option<AddressFamily>) -> Self {
        if let (Some(config), Some(family)) = (self.fixed_config.as_mut(), family) {
            config.address_family = family;
            return self;
        }
        self.cli_address_family = family;
        self
    }

    pub fn resolve_for_host(&self, hostname: &str) -> SshConnectionConfig {
        if let Some(config) = &self.fixed_config {
            return config.clone();
        }

        let keepalive_interval = self
            .cli_keepalive_interval
            .or_else(|| {
                self.ssh_config
                    .as_ref()
                    .and_then(|config| config.get_int_option(Some(hostname), "serveraliveinterval"))
                    .map(|v| v as u64)
            })
            .or(self.yaml_keepalive_interval)
            .unwrap_or(DEFAULT_KEEPALIVE_INTERVAL);

        let keepalive_max = self
            .cli_keepalive_max
            .or_else(|| {
                self.ssh_config
                    .as_ref()
                    .and_then(|config| config.get_int_option(Some(hostname), "serveralivecountmax"))
                    .map(|v| v as usize)
            })
            .or(self.yaml_keepalive_max)
            .unwrap_or(DEFAULT_KEEPALIVE_MAX);

        let compression = self
            .ssh_config
            .as_ref()
            .and_then(|config| config.get_compression(hostname))
            .unwrap_or(false);

        let config_address_family = self
            .ssh_config
            .as_ref()
            .and_then(|config| config.get_address_family(hostname));
        let address_family = self.cli_address_family.unwrap_or_else(|| {
            AddressFamily::resolve(false, false, config_address_family.as_deref())
        });

        SshConnectionConfig::new()
            .with_keepalive_interval(if keepalive_interval == 0 {
                None
            } else {
                Some(keepalive_interval)
            })
            .with_keepalive_max(keepalive_max)
            .with_compression(compression)
            .with_address_family(address_family)
    }
}

/// Compression preference advertised when ssh_config resolves `Compression
/// no` (or the directive is unset). This matches the current effective
/// behavior and the server-side fix in #215.
const NONE_ONLY_COMPRESSION: &[russh::compression::Name] = &[russh::compression::NONE];

/// Compression preference advertised when ssh_config resolves `Compression
/// yes`.
///
/// This deliberately omits `russh::compression::ZLIB_LEGACY`
/// (`zlib@openssh.com`). #215 found that russh's delayed-zlib transport
/// desyncs the flate2 stream a few packets after compression activates
/// post-auth, corrupting the next packet's length prefix (reproducible on
/// russh 0.61.1 and 0.62.1). That bug lives in russh's compression codec, not
/// the server role, so a bssh client that advertised `zlib@openssh.com` would
/// be just as exposed when talking to a server that selects it. Eager `zlib`
/// (activated immediately after key exchange, not delayed) does not exhibit
/// the same desync and is offered ahead of `none`.
const COMPRESSED_ORDER: &[russh::compression::Name] =
    &[russh::compression::ZLIB, russh::compression::NONE];

impl SshConnectionConfig {
    /// Create a new configuration with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the keepalive interval in seconds.
    /// Pass None, or Some(0), to disable keepalive.
    #[must_use]
    pub fn with_keepalive_interval(mut self, interval: Option<u64>) -> Self {
        self.keepalive_interval = interval.filter(|seconds| *seconds > 0);
        self
    }

    /// Set the maximum number of keepalive attempts.
    #[must_use]
    pub fn with_keepalive_max(mut self, max: usize) -> Self {
        self.keepalive_max = max;
        self
    }

    /// Set whether SSH transport compression should be advertised, mirroring
    /// the ssh_config `Compression` directive (`yes` -> `true`, `no`/unset ->
    /// `false`).
    #[must_use]
    pub fn with_compression(mut self, enabled: bool) -> Self {
        self.compression = enabled;
        self
    }

    /// Constrain the connection to a single IP address family, mirroring
    /// OpenSSH's `-4` / `-6` flags and the ssh_config `AddressFamily` keyword.
    #[must_use]
    pub fn with_address_family(mut self, family: AddressFamily) -> Self {
        self.address_family = family;
        self
    }

    /// Convert this configuration to a russh client Config.
    ///
    /// `inactivity_timeout` stays disabled for client sessions. A healthy
    /// interactive SSH session can legitimately produce no inbound data for a
    /// long time, so inactivity must not be treated as a local reason to close
    /// it. When keepalive is enabled, russh's keepalive counter is the liveness
    /// detector; when it is disabled, the client leaves idle sessions alone.
    ///
    /// `preferred.compression` is derived from `self.compression`: `false`
    /// advertises only `none`; `true` advertises `zlib` ahead of `none`.
    /// `zlib@openssh.com` is never advertised; see [`COMPRESSED_ORDER`] for
    /// why.
    pub fn to_russh_config(&self) -> Config {
        let compression_order = if self.compression {
            COMPRESSED_ORDER
        } else {
            NONE_ONLY_COMPRESSION
        };
        let preferred = russh::Preferred {
            compression: std::borrow::Cow::Borrowed(compression_order),
            ..russh::Preferred::DEFAULT
        };

        Config {
            keepalive_interval: self.keepalive_interval.map(Duration::from_secs),
            keepalive_max: self.keepalive_max,
            inactivity_timeout: None,
            preferred,
            ..Default::default()
        }
    }

    /// Derive a TCP-level keepalive configuration from this SSH keepalive
    /// configuration. Returns `None` if SSH keepalive is disabled.
    ///
    /// TCP keepalive is a belt-and-suspenders mechanism: it lets the kernel
    /// detect a broken TCP path even when no application data is flowing and
    /// even if SSH-level keepalive replies are dropped by a middlebox.
    pub fn to_tcp_keepalive(&self) -> Option<socket2::TcpKeepalive> {
        let interval = self.keepalive_interval.filter(|seconds| *seconds > 0)?;
        // Start probing after `interval` seconds of idleness, probe every
        // half-interval, up to keepalive_max retries.
        let probe_interval = (interval / 2).max(1);
        let ka = socket2::TcpKeepalive::new()
            .with_time(Duration::from_secs(interval))
            .with_interval(Duration::from_secs(probe_interval));
        #[cfg(any(
            target_os = "linux",
            target_os = "macos",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "tvos",
            target_os = "watchos",
            target_os = "ios",
        ))]
        let ka = ka.with_retries(self.keepalive_max.max(1) as u32);
        Some(ka)
    }
}
use super::ToSocketAddrsWithHostname;

/// A ssh connection to a remote server.
///
/// After creating a `Client` by [`connect`]ing to a remote host,
/// use [`execute`] to send commands and receive results through the connections.
///
/// [`connect`]: Client::connect
/// [`execute`]: Client::execute
///
/// # Examples
///
/// ```no_run
/// use bssh::ssh::tokio_client::{Client, AuthMethod, ServerCheckMethod};
/// #[tokio::main]
/// async fn main() -> Result<(), bssh::ssh::tokio_client::Error> {
///     let mut client = Client::connect(
///         ("10.10.10.2", 22),
///         "root",
///         AuthMethod::with_password("root"),
///         ServerCheckMethod::NoCheck,
///     ).await?;
///
///     let result = client.execute("echo Hello SSH").await?;
///     assert_eq!(result.stdout, "Hello SSH\n");
///     assert_eq!(result.exit_status, 0);
///
///     Ok(())
/// }
#[derive(Clone)]
pub struct Client {
    pub(super) connection_handle: Arc<Handle<ClientHandler>>,
    pub(super) username: String,
    pub(super) address: SocketAddr,
    /// Public access to the SSH session for jump host operations
    #[allow(private_interfaces)]
    pub session: Arc<Handle<ClientHandler>>,
}

impl Client {
    /// Open a ssh connection to a remote host with default keepalive settings.
    ///
    /// `addr` is an address of the remote host. Anything which implements
    /// [`ToSocketAddrsWithHostname`] trait can be supplied for the address;
    /// ToSocketAddrsWithHostname reimplements all of [`ToSocketAddrs`];
    /// see this trait's documentation for concrete examples.
    ///
    /// If `addr` yields multiple addresses, `connect` will be attempted with
    /// each of the addresses until a connection is successful.
    /// Authentification is tried on the first successful connection and the whole
    /// process aborted if this fails.
    ///
    /// This method uses default keepalive settings (30s interval, 3 max attempts)
    /// to prevent idle connection timeouts.
    pub async fn connect(
        addr: impl ToSocketAddrsWithHostname,
        username: &str,
        auth: AuthMethod,
        server_check: ServerCheckMethod,
    ) -> Result<Self, super::Error> {
        Self::connect_with_ssh_config(
            addr,
            username,
            auth,
            server_check,
            &SshConnectionConfig::default(),
        )
        .await
    }

    /// Connect with custom SSH connection configuration.
    ///
    /// This method allows specifying keepalive settings and other connection
    /// parameters through [`SshConnectionConfig`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bssh::ssh::tokio_client::{Client, AuthMethod, ServerCheckMethod, SshConnectionConfig};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), bssh::ssh::tokio_client::Error> {
    ///     let ssh_config = SshConnectionConfig::new()
    ///         .with_keepalive_interval(Some(15))
    ///         .with_keepalive_max(5);
    ///
    ///     let client = Client::connect_with_ssh_config(
    ///         ("example.com", 22),
    ///         "user",
    ///         AuthMethod::with_key_file("~/.ssh/id_rsa", None),
    ///         ServerCheckMethod::DefaultKnownHostsFile,
    ///         &ssh_config,
    ///     ).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn connect_with_ssh_config(
        addr: impl ToSocketAddrsWithHostname,
        username: &str,
        auth: AuthMethod,
        server_check: ServerCheckMethod,
        ssh_config: &SshConnectionConfig,
    ) -> Result<Self, super::Error> {
        let config = ssh_config.to_russh_config();
        let tcp_keepalive = ssh_config.to_tcp_keepalive();
        Self::connect_with_config_inner(
            addr,
            username,
            auth,
            server_check,
            config,
            tcp_keepalive.as_ref(),
            ssh_config.address_family,
        )
        .await
    }

    /// Same as `connect`, but with the option to specify a non default
    /// [`russh::client::Config`].
    ///
    /// For most use cases, prefer [`connect_with_ssh_config`] which provides
    /// a higher-level API with sensible defaults.
    pub async fn connect_with_config(
        addr: impl ToSocketAddrsWithHostname,
        username: &str,
        auth: AuthMethod,
        server_check: ServerCheckMethod,
        config: Config,
    ) -> Result<Self, super::Error> {
        Self::connect_with_config_inner(
            addr,
            username,
            auth,
            server_check,
            config,
            None,
            AddressFamily::Any,
        )
        .await
    }

    /// Resolve `addr`, apply the address family constraint, and connect to the
    /// first candidate that answers.
    ///
    /// With [`AddressFamily::Any`] the candidate list is the resolver's output
    /// untouched, in resolver order. A forced family filters that list and, if
    /// nothing survives, fails with [`Error::NoAddressForFamily`] instead of
    /// falling back to the other family.
    ///
    /// [`Error::NoAddressForFamily`]: super::Error::NoAddressForFamily
    async fn connect_with_config_inner(
        addr: impl ToSocketAddrsWithHostname,
        username: &str,
        auth: AuthMethod,
        server_check: ServerCheckMethod,
        config: Config,
        tcp_keepalive: Option<&socket2::TcpKeepalive>,
        address_family: AddressFamily,
    ) -> Result<Self, super::Error> {
        let config = Arc::new(config);

        // Connection code inspired from std::net::TcpStream::connect and std::net::each_addr
        let resolved = addr
            .to_socket_addrs()
            .map_err(super::Error::AddressInvalid)?;
        let resolved_count = resolved.len();
        let socket_addrs = address_family.filter(resolved);

        if address_family.is_forced() {
            tracing::debug!(
                "Address family {} forced for '{}': {} of {} resolved address(es) usable",
                address_family,
                addr.hostname(),
                socket_addrs.len(),
                resolved_count
            );
            if socket_addrs.is_empty() {
                return Err(super::Error::NoAddressForFamily {
                    host: addr.hostname(),
                    family: address_family,
                });
            }
        }

        let mut connect_res: Result<
            (SocketAddr, russh::client::Handle<ClientHandler>),
            super::Error,
        > = Err(super::Error::AddressInvalid(io::Error::new(
            io::ErrorKind::InvalidInput,
            "could not resolve to any addresses",
        )));
        for socket_addr in socket_addrs {
            let handler = ClientHandler {
                hostname: addr.hostname(),
                host: socket_addr,
                server_check: server_check.clone(),
            };

            let stream = match tokio::net::TcpStream::connect(socket_addr).await {
                Ok(s) => s,
                Err(e) => {
                    connect_res = Err(super::Error::IoError(e));
                    continue;
                }
            };

            if let Some(ka) = tcp_keepalive {
                let sock_ref = socket2::SockRef::from(&stream);
                if let Err(e) = sock_ref.set_tcp_keepalive(ka) {
                    tracing::debug!(
                        "Failed to set TCP keepalive on socket to {}: {}",
                        socket_addr,
                        e
                    );
                }
            }

            match russh::client::connect_stream(config.clone(), stream, handler).await {
                Ok(h) => {
                    connect_res = Ok((socket_addr, h));
                    break;
                }
                Err(e) => connect_res = Err(e),
            }
        }
        let (address, mut handle) = connect_res?;
        let username = username.to_string();

        super::authentication::authenticate(&mut handle, &username, auth).await?;

        let connection_handle = Arc::new(handle);
        Ok(Self {
            connection_handle: connection_handle.clone(),
            username,
            address,
            session: connection_handle,
        })
    }

    /// Create a Client from an existing russh handle and address.
    ///
    /// This is used internally for jump host connections where we already have
    /// an authenticated russh handle from connect_stream.
    pub fn from_handle_and_address(
        handle: Arc<Handle<ClientHandler>>,
        username: String,
        address: SocketAddr,
    ) -> Self {
        Self {
            connection_handle: handle.clone(),
            username,
            address,
            session: handle,
        }
    }

    /// A debugging function to get the username this client is connected as.
    pub fn get_connection_username(&self) -> &String {
        &self.username
    }

    /// A debugging function to get the address this client is connected to.
    pub fn get_connection_address(&self) -> &SocketAddr {
        &self.address
    }

    /// Disconnect from the remote host.
    pub async fn disconnect(&self) -> Result<(), super::Error> {
        self.connection_handle
            .disconnect(russh::Disconnect::ByApplication, "", "")
            .await
            .map_err(super::Error::SshError)
    }

    /// Check if the connection is closed.
    pub fn is_closed(&self) -> bool {
        self.connection_handle.is_closed()
    }

    /// Request remote port forwarding (tcpip-forward) - Future Implementation Placeholder
    ///
    /// **TODO**: This method needs to be implemented once russh provides
    /// global request functionality or we find the appropriate API.
    ///
    /// This sends a global request to the SSH server to bind a port on the remote end
    /// and forward connections back to the client. This is used for remote port forwarding (-R).
    ///
    /// # Arguments
    /// * `bind_address` - Address to bind on the remote server (e.g., "localhost", "0.0.0.0")
    /// * `bind_port` - Port to bind on the remote server (0 to let server choose)
    ///
    /// # Returns
    /// The actual port number that was bound by the server (useful when bind_port is 0)
    pub async fn request_port_forward(
        &self,
        _bind_address: String,
        _bind_port: u32,
    ) -> Result<u32, super::Error> {
        // **TODO**: Implement actual tcpip-forward global request
        // For now, return an error indicating this is not yet implemented
        tracing::warn!("Remote port forwarding request not yet implemented - TODO");
        Err(super::Error::PortForwardingNotSupported)
    }

    /// Cancel remote port forwarding (cancel-tcpip-forward) - Future Implementation Placeholder
    ///
    /// **TODO**: This method needs to be implemented once russh provides
    /// global request functionality or we find the appropriate API.
    ///
    /// This sends a global request to cancel a previously established remote port forward.
    ///
    /// # Arguments
    /// * `bind_address` - Address that was bound on the remote server
    /// * `bind_port` - Port that was bound on the remote server
    pub async fn cancel_port_forward(
        &self,
        _bind_address: String,
        _bind_port: u32,
    ) -> Result<(), super::Error> {
        // **TODO**: Implement actual cancel-tcpip-forward global request
        // For now, return an error indicating this is not yet implemented
        tracing::warn!("Cancel remote port forwarding not yet implemented - TODO");
        Err(super::Error::PortForwardingNotSupported)
    }
}

impl Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("username", &self.username)
            .field("address", &self.address)
            .field("connection_handle", &"Handle<ClientHandler>")
            .finish()
    }
}

/// SSH client handler for managing server key verification.
#[derive(Debug, Clone)]
pub struct ClientHandler {
    hostname: String,
    host: SocketAddr,
    server_check: ServerCheckMethod,
}

impl ClientHandler {
    /// Create a new client handler.
    pub fn new(hostname: String, host: SocketAddr, server_check: ServerCheckMethod) -> Self {
        Self {
            hostname,
            host,
            server_check,
        }
    }
}

impl Handler for ClientHandler {
    type Error = super::Error;

    async fn check_server_key(
        &mut self,
        server_public_key: &russh::keys::PublicKey,
    ) -> Result<bool, Self::Error> {
        match &self.server_check {
            ServerCheckMethod::NoCheck => Ok(true),
            ServerCheckMethod::PublicKey(key) => {
                let pk = russh::keys::parse_public_key_base64(key)
                    .map_err(|_| super::Error::ServerCheckFailed)?;

                Ok(pk == *server_public_key)
            }
            ServerCheckMethod::PublicKeyFile(key_file_name) => {
                let pk = russh::keys::load_public_key(key_file_name)
                    .map_err(|_| super::Error::ServerCheckFailed)?;

                Ok(pk == *server_public_key)
            }
            ServerCheckMethod::KnownHostsFile(known_hosts_path) => {
                super::host_verification::verify_known_hosts_file(
                    &self.hostname,
                    self.host.port(),
                    server_public_key,
                    known_hosts_path,
                )
            }
            ServerCheckMethod::DefaultKnownHostsFile => {
                // Resolve the default path here rather than letting russh
                // resolve it internally, so the check and the changed-key
                // banner's `ssh-keygen -f "<file>"` hint agree on one path and
                // both modes share `verify_known_hosts_file`. No home
                // directory means no trust state at all, so fail closed.
                let Some(known_hosts_path) =
                    crate::ssh::known_hosts::get_default_known_hosts_path()
                else {
                    tracing::error!(
                        "Cannot determine the known_hosts path; rejecting host key for '{}'",
                        self.hostname
                    );
                    return Err(super::Error::ServerCheckFailed);
                };
                super::host_verification::verify_known_hosts_file(
                    &self.hostname,
                    self.host.port(),
                    server_public_key,
                    &known_hosts_path.to_string_lossy(),
                )
            }
            ServerCheckMethod::AcceptNewKnownHostsFile(known_hosts_path) => {
                super::host_verification::verify_accept_new(
                    &self.hostname,
                    self.host.port(),
                    server_public_key,
                    known_hosts_path,
                )
                .await
            }
            ServerCheckMethod::AcceptNewInMemory => {
                super::host_verification::verify_accept_new_in_memory(
                    &self.hostname,
                    self.host.port(),
                    server_public_key,
                )
                .await
            }
        }
    }
}