aria2-protocol 0.3.10

Multi-protocol networking stack for aria2-rust: HTTP/HTTPS client, FTP/SFTP, full BitTorrent (DHT/PEX/MSE), and Metalink V3/V4 parser
Documentation
//! SSH connection options and host-key policy.

use std::path::PathBuf;
use std::time::Duration;
use tracing::debug;
/// Host key verification modes for SSH connections
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum HostKeyCheckingMode {
    /// Strict host key checking - reject unknown/changed host keys
    #[default]
    Strict,
    /// Accept new host keys automatically but detect changes
    AcceptNew,
    /// Disable all host key verification (insecure, use only for testing)
    Disable,
}

impl std::fmt::Display for HostKeyCheckingMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Strict => write!(f, "strict"),
            Self::AcceptNew => write!(f, "accept-new"),
            Self::Disable => write!(f, "disable"),
        }
    }
}

/// Configuration options for establishing an SSH connection
#[derive(Clone)]
pub struct SshOptions {
    /// Remote hostname or IP address
    pub host: String,
    /// TCP port number (default: 22)
    pub port: u16,
    /// Username for authentication
    pub username: String,
    /// Password for password-based authentication (optional if using key auth)
    pub password: Option<String>,
    /// Path to private key file (optional if using password auth)
    pub private_key_path: Option<String>,
    /// Passphrase for encrypted private keys
    pub private_key_passphrase: Option<String>,
    /// Timeout for connection establishment, SSH negotiation, authentication, and SFTP channel opening.
    pub connect_timeout: Duration,
    /// Timeout for read operations on the SSH channel
    pub read_timeout: Duration,
    /// Host key verification mode
    pub host_key_mode: HostKeyCheckingMode,
    /// Expected fingerprint in `hashType=digest` form.
    pub host_key_fingerprint: Option<String>,
    /// OpenSSH-format known-hosts file. Defaults to `~/.ssh/known_hosts`.
    pub known_hosts_path: Option<PathBuf>,
    /// Compression setting (not all servers support this)
    pub compression: bool,
    /// Keep-alive interval (None to disable)
    pub keepalive_interval: Option<Duration>,
    /// Preferred ciphers (empty = server default)
    pub preferred_ciphers: Vec<String>,
}

impl std::fmt::Debug for SshOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let password = self.password.as_ref().map(|_| "[REDACTED]");
        let username = (!self.username.is_empty()).then_some("[REDACTED]");
        let private_key_passphrase = self.private_key_passphrase.as_ref().map(|_| "[REDACTED]");
        f.debug_struct("SshOptions")
            .field("host", &self.host)
            .field("port", &self.port)
            .field("username", &username)
            .field("password", &password)
            .field("private_key_path", &self.private_key_path)
            .field("private_key_passphrase", &private_key_passphrase)
            .field("connect_timeout", &self.connect_timeout)
            .field("read_timeout", &self.read_timeout)
            .field("host_key_mode", &self.host_key_mode)
            .field("host_key_fingerprint", &self.host_key_fingerprint)
            .field("known_hosts_path", &self.known_hosts_path)
            .field("compression", &self.compression)
            .field("keepalive_interval", &self.keepalive_interval)
            .field("preferred_ciphers", &self.preferred_ciphers)
            .finish()
    }
}

impl Default for SshOptions {
    fn default() -> Self {
        Self {
            host: "localhost".to_string(),
            port: crate::sftp::DEFAULT_PORT,
            username: String::new(),
            password: None,
            private_key_path: None,
            private_key_passphrase: None,
            connect_timeout: Duration::from_secs(crate::DEFAULT_SFTP_CONNECT_TIMEOUT_SECS),
            read_timeout: Duration::from_secs(crate::DEFAULT_SFTP_READ_TIMEOUT_SECS),
            host_key_mode: HostKeyCheckingMode::default(),
            host_key_fingerprint: None,
            known_hosts_path: None,
            compression: false,
            keepalive_interval: Some(Duration::from_secs(
                crate::DEFAULT_SFTP_KEEPALIVE_INTERVAL_SECS,
            )),
            preferred_ciphers: Vec::new(),
        }
    }
}

impl SshOptions {
    /// Create new SSH options with required fields
    pub fn new(host: &str, username: &str) -> Self {
        Self {
            host: host.to_string(),
            port: crate::sftp::DEFAULT_PORT,
            username: username.to_string(),
            ..Default::default()
        }
    }

    /// Set the port number
    pub fn with_port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Set the password for authentication
    pub fn with_password(mut self, password: &str) -> Self {
        self.password = Some(password.to_string());
        self
    }

    /// Set the path to a private key file for authentication
    pub fn with_private_key(mut self, path: &str) -> Self {
        self.private_key_path = Some(path.to_string());
        self
    }

    /// Set a passphrase for an encrypted private key
    pub fn with_passphrase(mut self, passphrase: &str) -> Self {
        self.private_key_passphrase = Some(passphrase.to_string());
        self
    }

    /// Set the expected host-key fingerprint.
    pub fn with_host_key_fingerprint(mut self, fingerprint: impl Into<String>) -> Self {
        self.host_key_fingerprint = Some(fingerprint.into());
        self
    }

    /// Set the host key checking mode
    pub fn with_host_key_mode(mut self, mode: HostKeyCheckingMode) -> Self {
        self.host_key_mode = mode;
        self
    }

    /// Set the OpenSSH-format known-hosts file used for host-key verification.
    pub fn with_known_hosts_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.known_hosts_path = Some(path.into());
        self
    }

    /// Set custom timeouts
    pub fn with_timeouts(mut self, connect: Duration, read: Duration) -> Self {
        self.connect_timeout = connect;
        self.read_timeout = read;
        self
    }

    /// Enable or disable compression
    pub fn with_compression(mut self, enabled: bool) -> Self {
        self.compression = enabled;
        self
    }

    /// Set the preferred SSH cipher algorithms in negotiation order.
    ///
    /// Names are validated when the connection is established.
    pub fn with_preferred_ciphers<I, S>(mut self, ciphers: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.preferred_ciphers = ciphers.into_iter().map(Into::into).collect();
        self
    }

    /// Set the SSH keep-alive interval, or disable keep-alives with `None`.
    pub fn with_keepalive_interval(mut self, interval: Option<Duration>) -> Self {
        self.keepalive_interval = interval;
        self
    }

    /// Get a human-readable target identifier string
    pub fn target(&self) -> String {
        format!("{}@{}:{}", self.username, self.host, self.port)
    }

    /// Check if this configuration has valid authentication credentials
    pub fn has_auth_credentials(&self) -> bool {
        self.password.is_some() || self.private_key_path.is_some()
    }

    /// Resolve the actual private key path, checking common locations
    /// if not explicitly specified. Returns the path to use or None.
    pub fn resolve_key_path(&self) -> Option<PathBuf> {
        if let Some(ref path) = self.private_key_path {
            return Some(PathBuf::from(path));
        }

        // Auto-detect key files in standard locations when no explicit path given
        // Only attempt auto-detection if we have no password auth configured
        if self.password.is_none() {
            let home = dirs::home_dir();
            if let Some(home) = home {
                // Check common key files in order of preference
                for key_name in &["id_ed25519", "id_rsa", "id_ecdsa"] {
                    let candidate = home.join(".ssh").join(key_name);
                    if candidate.exists() {
                        debug!("auto-detected SSH key: {}", candidate.display());
                        return Some(candidate);
                    }
                }
            }
        }

        None
    }
}

// =============================================================================