ssh.rs

   1use crate::{
   2    RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
   3    remote_client::{CommandTemplate, Interactive, RemoteConnection, RemoteConnectionOptions},
   4    transport::{parse_platform, parse_shell},
   5};
   6use anyhow::{Context as _, Result, anyhow};
   7use async_trait::async_trait;
   8use collections::HashMap;
   9use futures::{
  10    AsyncReadExt as _, FutureExt as _,
  11    channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender},
  12    select_biased,
  13};
  14use gpui::{App, AppContext as _, AsyncApp, Task};
  15use parking_lot::Mutex;
  16use paths::remote_server_dir_relative;
  17use release_channel::{AppVersion, ReleaseChannel};
  18use rpc::proto::Envelope;
  19use semver::Version;
  20pub use settings::SshPortForwardOption;
  21use smol::{
  22    fs,
  23    process::{self, Child, Stdio},
  24};
  25use std::{
  26    net::IpAddr,
  27    path::{Path, PathBuf},
  28    sync::Arc,
  29    time::Instant,
  30};
  31use tempfile::TempDir;
  32use util::{
  33    paths::{PathStyle, RemotePathBuf},
  34    rel_path::RelPath,
  35    shell::ShellKind,
  36};
  37
  38pub(crate) struct SshRemoteConnection {
  39    socket: SshSocket,
  40    master_process: Mutex<Option<MasterProcess>>,
  41    remote_binary_path: Option<Arc<RelPath>>,
  42    ssh_platform: RemotePlatform,
  43    ssh_path_style: PathStyle,
  44    ssh_shell: String,
  45    ssh_shell_kind: ShellKind,
  46    ssh_default_system_shell: String,
  47    _temp_dir: TempDir,
  48}
  49
  50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
  51pub enum SshConnectionHost {
  52    IpAddr(IpAddr),
  53    Hostname(String),
  54}
  55
  56impl SshConnectionHost {
  57    pub fn to_bracketed_string(&self) -> String {
  58        match self {
  59            Self::IpAddr(IpAddr::V4(ip)) => ip.to_string(),
  60            Self::IpAddr(IpAddr::V6(ip)) => format!("[{}]", ip),
  61            Self::Hostname(hostname) => hostname.clone(),
  62        }
  63    }
  64
  65    pub fn to_string(&self) -> String {
  66        match self {
  67            Self::IpAddr(ip) => ip.to_string(),
  68            Self::Hostname(hostname) => hostname.clone(),
  69        }
  70    }
  71}
  72
  73impl From<&str> for SshConnectionHost {
  74    fn from(value: &str) -> Self {
  75        if let Ok(address) = value.parse() {
  76            Self::IpAddr(address)
  77        } else {
  78            Self::Hostname(value.to_string())
  79        }
  80    }
  81}
  82
  83impl From<String> for SshConnectionHost {
  84    fn from(value: String) -> Self {
  85        if let Ok(address) = value.parse() {
  86            Self::IpAddr(address)
  87        } else {
  88            Self::Hostname(value)
  89        }
  90    }
  91}
  92
  93impl Default for SshConnectionHost {
  94    fn default() -> Self {
  95        Self::Hostname(Default::default())
  96    }
  97}
  98
  99#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
 100pub struct SshConnectionOptions {
 101    pub host: SshConnectionHost,
 102    pub username: Option<String>,
 103    pub port: Option<u16>,
 104    pub password: Option<String>,
 105    pub args: Option<Vec<String>>,
 106    pub port_forwards: Option<Vec<SshPortForwardOption>>,
 107    pub connection_timeout: Option<u16>,
 108
 109    pub nickname: Option<String>,
 110    pub upload_binary_over_ssh: bool,
 111}
 112
 113impl From<settings::SshConnection> for SshConnectionOptions {
 114    fn from(val: settings::SshConnection) -> Self {
 115        SshConnectionOptions {
 116            host: val.host.to_string().into(),
 117            username: val.username,
 118            port: val.port,
 119            password: None,
 120            args: Some(val.args),
 121            nickname: val.nickname,
 122            upload_binary_over_ssh: val.upload_binary_over_ssh.unwrap_or_default(),
 123            port_forwards: val.port_forwards,
 124            connection_timeout: val.connection_timeout,
 125        }
 126    }
 127}
 128
 129struct SshSocket {
 130    connection_options: SshConnectionOptions,
 131    #[cfg(not(target_os = "windows"))]
 132    socket_path: std::path::PathBuf,
 133    envs: HashMap<String, String>,
 134    #[cfg(target_os = "windows")]
 135    _proxy: askpass::PasswordProxy,
 136}
 137
 138struct MasterProcess {
 139    process: Child,
 140}
 141
 142#[cfg(not(target_os = "windows"))]
 143impl MasterProcess {
 144    pub fn new(
 145        askpass_script_path: &std::ffi::OsStr,
 146        additional_args: Vec<String>,
 147        socket_path: &std::path::Path,
 148        destination: &str,
 149    ) -> Result<Self> {
 150        let args = [
 151            "-N",
 152            "-o",
 153            "ControlPersist=no",
 154            "-o",
 155            "ControlMaster=yes",
 156            "-o",
 157        ];
 158
 159        let mut master_process = util::command::new_smol_command("ssh");
 160        master_process
 161            .kill_on_drop(true)
 162            .stdin(Stdio::null())
 163            .stdout(Stdio::piped())
 164            .stderr(Stdio::piped())
 165            .env("SSH_ASKPASS_REQUIRE", "force")
 166            .env("SSH_ASKPASS", askpass_script_path)
 167            .args(additional_args)
 168            .args(args);
 169
 170        master_process.arg(format!("ControlPath={}", socket_path.display()));
 171
 172        let process = master_process.arg(&destination).spawn()?;
 173
 174        Ok(MasterProcess { process })
 175    }
 176
 177    pub async fn wait_connected(&mut self) -> Result<()> {
 178        let Some(mut stdout) = self.process.stdout.take() else {
 179            anyhow::bail!("ssh process stdout capture failed");
 180        };
 181
 182        let mut output = Vec::new();
 183        stdout.read_to_end(&mut output).await?;
 184        Ok(())
 185    }
 186}
 187
 188#[cfg(target_os = "windows")]
 189impl MasterProcess {
 190    const CONNECTION_ESTABLISHED_MAGIC: &str = "ZED_SSH_CONNECTION_ESTABLISHED";
 191
 192    pub fn new(
 193        askpass_script_path: &std::ffi::OsStr,
 194        additional_args: Vec<String>,
 195        destination: &str,
 196    ) -> Result<Self> {
 197        // On Windows, `ControlMaster` and `ControlPath` are not supported:
 198        // https://github.com/PowerShell/Win32-OpenSSH/issues/405
 199        // https://github.com/PowerShell/Win32-OpenSSH/wiki/Project-Scope
 200        //
 201        // Using an ugly workaround to detect connection establishment
 202        // -N doesn't work with JumpHosts as windows openssh never closes stdin in that case
 203        let args = [
 204            "-t",
 205            &format!("echo '{}'; exec $0", Self::CONNECTION_ESTABLISHED_MAGIC),
 206        ];
 207
 208        let mut master_process = util::command::new_smol_command("ssh");
 209        master_process
 210            .kill_on_drop(true)
 211            .stdin(Stdio::null())
 212            .stdout(Stdio::piped())
 213            .stderr(Stdio::piped())
 214            .env("SSH_ASKPASS_REQUIRE", "force")
 215            .env("SSH_ASKPASS", askpass_script_path)
 216            .args(additional_args)
 217            .arg(destination)
 218            .args(args);
 219
 220        let process = master_process.spawn()?;
 221
 222        Ok(MasterProcess { process })
 223    }
 224
 225    pub async fn wait_connected(&mut self) -> Result<()> {
 226        use smol::io::AsyncBufReadExt;
 227
 228        let Some(stdout) = self.process.stdout.take() else {
 229            anyhow::bail!("ssh process stdout capture failed");
 230        };
 231
 232        let mut reader = smol::io::BufReader::new(stdout);
 233
 234        let mut line = String::new();
 235
 236        loop {
 237            let n = reader.read_line(&mut line).await?;
 238            if n == 0 {
 239                anyhow::bail!("ssh process exited before connection established");
 240            }
 241
 242            if line.contains(Self::CONNECTION_ESTABLISHED_MAGIC) {
 243                return Ok(());
 244            }
 245        }
 246    }
 247}
 248
 249impl AsRef<Child> for MasterProcess {
 250    fn as_ref(&self) -> &Child {
 251        &self.process
 252    }
 253}
 254
 255impl AsMut<Child> for MasterProcess {
 256    fn as_mut(&mut self) -> &mut Child {
 257        &mut self.process
 258    }
 259}
 260
 261#[async_trait(?Send)]
 262impl RemoteConnection for SshRemoteConnection {
 263    async fn kill(&self) -> Result<()> {
 264        let Some(mut process) = self.master_process.lock().take() else {
 265            return Ok(());
 266        };
 267        process.as_mut().kill().ok();
 268        process.as_mut().status().await?;
 269        Ok(())
 270    }
 271
 272    fn has_been_killed(&self) -> bool {
 273        self.master_process.lock().is_none()
 274    }
 275
 276    fn connection_options(&self) -> RemoteConnectionOptions {
 277        RemoteConnectionOptions::Ssh(self.socket.connection_options.clone())
 278    }
 279
 280    fn shell(&self) -> String {
 281        self.ssh_shell.clone()
 282    }
 283
 284    fn default_system_shell(&self) -> String {
 285        self.ssh_default_system_shell.clone()
 286    }
 287
 288    fn build_command(
 289        &self,
 290        input_program: Option<String>,
 291        input_args: &[String],
 292        input_env: &HashMap<String, String>,
 293        working_dir: Option<String>,
 294        port_forward: Option<(u16, String, u16)>,
 295        interactive: Interactive,
 296    ) -> Result<CommandTemplate> {
 297        let Self {
 298            ssh_path_style,
 299            socket,
 300            ssh_shell_kind,
 301            ssh_shell,
 302            ..
 303        } = self;
 304        let env = socket.envs.clone();
 305        build_command(
 306            input_program,
 307            input_args,
 308            input_env,
 309            working_dir,
 310            port_forward,
 311            env,
 312            *ssh_path_style,
 313            ssh_shell,
 314            *ssh_shell_kind,
 315            socket.ssh_args(),
 316            interactive,
 317        )
 318    }
 319
 320    fn build_forward_ports_command(
 321        &self,
 322        forwards: Vec<(u16, String, u16)>,
 323    ) -> Result<CommandTemplate> {
 324        let Self { socket, .. } = self;
 325        let mut args = socket.ssh_args();
 326        args.push("-N".into());
 327        for (local_port, host, remote_port) in forwards {
 328            args.push("-L".into());
 329            args.push(format!("{local_port}:{host}:{remote_port}"));
 330        }
 331        Ok(CommandTemplate {
 332            program: "ssh".into(),
 333            args,
 334            env: Default::default(),
 335        })
 336    }
 337
 338    fn upload_directory(
 339        &self,
 340        src_path: PathBuf,
 341        dest_path: RemotePathBuf,
 342        cx: &App,
 343    ) -> Task<Result<()>> {
 344        let dest_path_str = dest_path.to_string();
 345        let src_path_display = src_path.display().to_string();
 346
 347        let mut sftp_command = self.build_sftp_command();
 348        let mut scp_command =
 349            self.build_scp_command(&src_path, &dest_path_str, Some(&["-C", "-r"]));
 350
 351        cx.background_spawn(async move {
 352            // We will try SFTP first, and if that fails, we will fall back to SCP.
 353            // If SCP fails also, we give up and return an error.
 354            // The reason we allow a fallback from SFTP to SCP is that if the user has to specify a password,
 355            // depending on the implementation of SSH stack, SFTP may disable interactive password prompts in batch mode.
 356            // This is for example the case on Windows as evidenced by this implementation snippet:
 357            // https://github.com/PowerShell/openssh-portable/blob/b8c08ef9da9450a94a9c5ef717d96a7bd83f3332/sshconnect2.c#L417
 358            if Self::is_sftp_available().await {
 359                log::debug!("using SFTP for directory upload");
 360                let mut child = sftp_command.spawn()?;
 361                if let Some(mut stdin) = child.stdin.take() {
 362                    use futures::AsyncWriteExt;
 363                    let sftp_batch = format!("put -r \"{src_path_display}\" \"{dest_path_str}\"\n");
 364                    stdin.write_all(sftp_batch.as_bytes()).await?;
 365                    stdin.flush().await?;
 366                }
 367
 368                let output = child.output().await?;
 369                if output.status.success() {
 370                    return Ok(());
 371                }
 372
 373                let stderr = String::from_utf8_lossy(&output.stderr);
 374                log::debug!("failed to upload directory via SFTP {src_path_display} -> {dest_path_str}: {stderr}");
 375            }
 376
 377            log::debug!("using SCP for directory upload");
 378            let output = scp_command.output().await?;
 379
 380            if output.status.success() {
 381                return Ok(());
 382            }
 383
 384            let stderr = String::from_utf8_lossy(&output.stderr);
 385            log::debug!("failed to upload directory via SCP {src_path_display} -> {dest_path_str}: {stderr}");
 386
 387            anyhow::bail!(
 388                "failed to upload directory via SFTP/SCP {} -> {}: {}",
 389                src_path_display,
 390                dest_path_str,
 391                stderr,
 392            );
 393        })
 394    }
 395
 396    fn start_proxy(
 397        &self,
 398        unique_identifier: String,
 399        reconnect: bool,
 400        incoming_tx: UnboundedSender<Envelope>,
 401        outgoing_rx: UnboundedReceiver<Envelope>,
 402        connection_activity_tx: Sender<()>,
 403        delegate: Arc<dyn RemoteClientDelegate>,
 404        cx: &mut AsyncApp,
 405    ) -> Task<Result<i32>> {
 406        const VARS: [&str; 3] = ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"];
 407        delegate.set_status(Some("Starting proxy"), cx);
 408
 409        let Some(remote_binary_path) = self.remote_binary_path.clone() else {
 410            return Task::ready(Err(anyhow!("Remote binary path not set")));
 411        };
 412
 413        let mut ssh_command = if self.ssh_platform.os.is_windows() {
 414            // TODO: Set the `VARS` environment variables, we do not have `env` on windows
 415            // so this needs a different approach
 416            let mut proxy_args = vec![];
 417            proxy_args.push("proxy".to_owned());
 418            proxy_args.push("--identifier".to_owned());
 419            proxy_args.push(unique_identifier);
 420
 421            if reconnect {
 422                proxy_args.push("--reconnect".to_owned());
 423            }
 424            self.socket.ssh_command(
 425                self.ssh_shell_kind,
 426                &remote_binary_path.display(self.path_style()),
 427                &proxy_args,
 428                false,
 429            )
 430        } else {
 431            let mut proxy_args = vec![];
 432            for env_var in VARS {
 433                if let Some(value) = std::env::var(env_var).ok() {
 434                    proxy_args.push(format!("{}='{}'", env_var, value));
 435                }
 436            }
 437            proxy_args.push(remote_binary_path.display(self.path_style()).into_owned());
 438            proxy_args.push("proxy".to_owned());
 439            proxy_args.push("--identifier".to_owned());
 440            proxy_args.push(unique_identifier);
 441
 442            if reconnect {
 443                proxy_args.push("--reconnect".to_owned());
 444            }
 445            self.socket
 446                .ssh_command(self.ssh_shell_kind, "env", &proxy_args, false)
 447        };
 448
 449        let ssh_proxy_process = match ssh_command
 450            // IMPORTANT: we kill this process when we drop the task that uses it.
 451            .kill_on_drop(true)
 452            .spawn()
 453        {
 454            Ok(process) => process,
 455            Err(error) => {
 456                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
 457            }
 458        };
 459
 460        super::handle_rpc_messages_over_child_process_stdio(
 461            ssh_proxy_process,
 462            incoming_tx,
 463            outgoing_rx,
 464            connection_activity_tx,
 465            cx,
 466        )
 467    }
 468
 469    fn path_style(&self) -> PathStyle {
 470        self.ssh_path_style
 471    }
 472
 473    fn has_wsl_interop(&self) -> bool {
 474        false
 475    }
 476}
 477
 478impl SshRemoteConnection {
 479    pub(crate) async fn new(
 480        connection_options: SshConnectionOptions,
 481        delegate: Arc<dyn RemoteClientDelegate>,
 482        cx: &mut AsyncApp,
 483    ) -> Result<Self> {
 484        use askpass::AskPassResult;
 485
 486        let destination = connection_options.ssh_destination();
 487
 488        let temp_dir = tempfile::Builder::new()
 489            .prefix("zed-ssh-session")
 490            .tempdir()?;
 491        let askpass_delegate = askpass::AskPassDelegate::new(cx, {
 492            let delegate = delegate.clone();
 493            move |prompt, tx, cx| delegate.ask_password(prompt, tx, cx)
 494        });
 495
 496        let mut askpass =
 497            askpass::AskPassSession::new(cx.background_executor().clone(), askpass_delegate)
 498                .await?;
 499
 500        delegate.set_status(Some("Connecting"), cx);
 501
 502        // Start the master SSH process, which does not do anything except for establish
 503        // the connection and keep it open, allowing other ssh commands to reuse it
 504        // via a control socket.
 505        #[cfg(not(target_os = "windows"))]
 506        let socket_path = temp_dir.path().join("ssh.sock");
 507
 508        #[cfg(target_os = "windows")]
 509        let mut master_process = MasterProcess::new(
 510            askpass.script_path().as_ref(),
 511            connection_options.additional_args(),
 512            &destination,
 513        )?;
 514        #[cfg(not(target_os = "windows"))]
 515        let mut master_process = MasterProcess::new(
 516            askpass.script_path().as_ref(),
 517            connection_options.additional_args(),
 518            &socket_path,
 519            &destination,
 520        )?;
 521
 522        let result = select_biased! {
 523            result = askpass.run().fuse() => {
 524                match result {
 525                    AskPassResult::CancelledByUser => {
 526                        master_process.as_mut().kill().ok();
 527                        anyhow::bail!("SSH connection canceled")
 528                    }
 529                    AskPassResult::Timedout => {
 530                        anyhow::bail!("connecting to host timed out")
 531                    }
 532                }
 533            }
 534            _ = master_process.wait_connected().fuse() => {
 535                anyhow::Ok(())
 536            }
 537        };
 538
 539        if let Err(e) = result {
 540            return Err(e.context("Failed to connect to host"));
 541        }
 542
 543        if master_process.as_mut().try_status()?.is_some() {
 544            let mut output = Vec::new();
 545            output.clear();
 546            let mut stderr = master_process.as_mut().stderr.take().unwrap();
 547            stderr.read_to_end(&mut output).await?;
 548
 549            let error_message = format!(
 550                "failed to connect: {}",
 551                String::from_utf8_lossy(&output).trim()
 552            );
 553            anyhow::bail!(error_message);
 554        }
 555
 556        #[cfg(not(target_os = "windows"))]
 557        let socket = SshSocket::new(connection_options, socket_path).await?;
 558        #[cfg(target_os = "windows")]
 559        let socket = SshSocket::new(
 560            connection_options,
 561            askpass
 562                .get_password()
 563                .or_else(|| askpass::EncryptedPassword::try_from("").ok())
 564                .context("Failed to fetch askpass password")?,
 565            cx.background_executor().clone(),
 566        )
 567        .await?;
 568        drop(askpass);
 569
 570        let is_windows = socket.probe_is_windows().await;
 571        log::info!("Remote is windows: {}", is_windows);
 572
 573        let ssh_shell = socket.shell(is_windows).await;
 574        log::info!("Remote shell discovered: {}", ssh_shell);
 575
 576        let ssh_shell_kind = ShellKind::new(&ssh_shell, is_windows);
 577        let ssh_platform = socket.platform(ssh_shell_kind, is_windows).await?;
 578        log::info!("Remote platform discovered: {:?}", ssh_platform);
 579
 580        let (ssh_path_style, ssh_default_system_shell) = match ssh_platform.os {
 581            RemoteOs::Windows => (PathStyle::Windows, ssh_shell.clone()),
 582            _ => (PathStyle::Posix, String::from("/bin/sh")),
 583        };
 584
 585        let mut this = Self {
 586            socket,
 587            master_process: Mutex::new(Some(master_process)),
 588            _temp_dir: temp_dir,
 589            remote_binary_path: None,
 590            ssh_path_style,
 591            ssh_platform,
 592            ssh_shell,
 593            ssh_shell_kind,
 594            ssh_default_system_shell,
 595        };
 596
 597        let (release_channel, version) =
 598            cx.update(|cx| (ReleaseChannel::global(cx), AppVersion::global(cx)));
 599        this.remote_binary_path = Some(
 600            this.ensure_server_binary(&delegate, release_channel, version, cx)
 601                .await?,
 602        );
 603
 604        Ok(this)
 605    }
 606
 607    async fn ensure_server_binary(
 608        &self,
 609        delegate: &Arc<dyn RemoteClientDelegate>,
 610        release_channel: ReleaseChannel,
 611        version: Version,
 612        cx: &mut AsyncApp,
 613    ) -> Result<Arc<RelPath>> {
 614        let version_str = match release_channel {
 615            ReleaseChannel::Dev => "build".to_string(),
 616            _ => version.to_string(),
 617        };
 618        let binary_name = format!(
 619            "zed-remote-server-{}-{}{}",
 620            release_channel.dev_name(),
 621            version_str,
 622            if self.ssh_platform.os.is_windows() {
 623                ".exe"
 624            } else {
 625                ""
 626            }
 627        );
 628        let dst_path =
 629            paths::remote_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
 630
 631        let binary_exists_on_server = self
 632            .socket
 633            .run_command(
 634                self.ssh_shell_kind,
 635                &dst_path.display(self.path_style()),
 636                &["version"],
 637                true,
 638            )
 639            .await
 640            .is_ok();
 641
 642        #[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
 643        if let Some(remote_server_path) = super::build_remote_server_from_source(
 644            &self.ssh_platform,
 645            delegate.as_ref(),
 646            binary_exists_on_server,
 647            cx,
 648        )
 649        .await?
 650        {
 651            let tmp_path = paths::remote_server_dir_relative().join(
 652                RelPath::unix(&format!(
 653                    "download-{}-{}",
 654                    std::process::id(),
 655                    remote_server_path.file_name().unwrap().to_string_lossy()
 656                ))
 657                .unwrap(),
 658            );
 659            self.upload_local_server_binary(&remote_server_path, &tmp_path, delegate, cx)
 660                .await?;
 661            self.extract_server_binary(&dst_path, &tmp_path, delegate, cx)
 662                .await?;
 663            return Ok(dst_path);
 664        }
 665
 666        if binary_exists_on_server {
 667            return Ok(dst_path);
 668        }
 669
 670        let wanted_version = cx.update(|cx| match release_channel {
 671            ReleaseChannel::Nightly => Ok(None),
 672            ReleaseChannel::Dev => {
 673                anyhow::bail!(
 674                    "ZED_BUILD_REMOTE_SERVER is not set and no remote server exists at ({:?})",
 675                    dst_path
 676                )
 677            }
 678            _ => Ok(Some(AppVersion::global(cx))),
 679        })?;
 680
 681        let tmp_path_gz = remote_server_dir_relative().join(
 682            RelPath::unix(&format!(
 683                "{}-download-{}.gz",
 684                binary_name,
 685                std::process::id()
 686            ))
 687            .unwrap(),
 688        );
 689        if !self.socket.connection_options.upload_binary_over_ssh
 690            && let Some(url) = delegate
 691                .get_download_url(
 692                    self.ssh_platform,
 693                    release_channel,
 694                    wanted_version.clone(),
 695                    cx,
 696                )
 697                .await?
 698        {
 699            match self
 700                .download_binary_on_server(&url, &tmp_path_gz, delegate, cx)
 701                .await
 702            {
 703                Ok(_) => {
 704                    self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
 705                        .await
 706                        .context("extracting server binary")?;
 707                    return Ok(dst_path);
 708                }
 709                Err(e) => {
 710                    log::error!(
 711                        "Failed to download binary on server, attempting to download locally and then upload it the server: {e:#}",
 712                    )
 713                }
 714            }
 715        }
 716
 717        let src_path = delegate
 718            .download_server_binary_locally(
 719                self.ssh_platform,
 720                release_channel,
 721                wanted_version.clone(),
 722                cx,
 723            )
 724            .await
 725            .context("downloading server binary locally")?;
 726        self.upload_local_server_binary(&src_path, &tmp_path_gz, delegate, cx)
 727            .await
 728            .context("uploading server binary")?;
 729        self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
 730            .await
 731            .context("extracting server binary")?;
 732        Ok(dst_path)
 733    }
 734
 735    async fn download_binary_on_server(
 736        &self,
 737        url: &str,
 738        tmp_path_gz: &RelPath,
 739        delegate: &Arc<dyn RemoteClientDelegate>,
 740        cx: &mut AsyncApp,
 741    ) -> Result<()> {
 742        if let Some(parent) = tmp_path_gz.parent() {
 743            let res = self
 744                .socket
 745                .run_command(
 746                    self.ssh_shell_kind,
 747                    "mkdir",
 748                    &["-p", parent.display(self.path_style()).as_ref()],
 749                    true,
 750                )
 751                .await;
 752            if !self.ssh_platform.os.is_windows() {
 753                // mkdir fails on windows if the path already exists ...
 754                res?;
 755            }
 756        }
 757
 758        delegate.set_status(Some("Downloading remote development server on host"), cx);
 759
 760        let connection_timeout = self
 761            .socket
 762            .connection_options
 763            .connection_timeout
 764            .unwrap_or(10)
 765            .to_string();
 766
 767        match self
 768            .socket
 769            .run_command(
 770                self.ssh_shell_kind,
 771                "curl",
 772                &[
 773                    "-f",
 774                    "-L",
 775                    "--connect-timeout",
 776                    &connection_timeout,
 777                    url,
 778                    "-o",
 779                    &tmp_path_gz.display(self.path_style()),
 780                ],
 781                true,
 782            )
 783            .await
 784        {
 785            Ok(_) => {}
 786            Err(e) => {
 787                if self
 788                    .socket
 789                    .run_command(self.ssh_shell_kind, "which", &["curl"], true)
 790                    .await
 791                    .is_ok()
 792                {
 793                    return Err(e);
 794                }
 795
 796                log::info!("curl is not available, trying wget");
 797                match self
 798                    .socket
 799                    .run_command(
 800                        self.ssh_shell_kind,
 801                        "wget",
 802                        &[
 803                            "--connect-timeout",
 804                            &connection_timeout,
 805                            "--tries",
 806                            "1",
 807                            url,
 808                            "-O",
 809                            &tmp_path_gz.display(self.path_style()),
 810                        ],
 811                        true,
 812                    )
 813                    .await
 814                {
 815                    Ok(_) => {}
 816                    Err(e) => {
 817                        if self
 818                            .socket
 819                            .run_command(self.ssh_shell_kind, "which", &["wget"], true)
 820                            .await
 821                            .is_ok()
 822                        {
 823                            return Err(e);
 824                        } else {
 825                            anyhow::bail!("Neither curl nor wget is available");
 826                        }
 827                    }
 828                }
 829            }
 830        }
 831
 832        Ok(())
 833    }
 834
 835    async fn upload_local_server_binary(
 836        &self,
 837        src_path: &Path,
 838        tmp_path_gz: &RelPath,
 839        delegate: &Arc<dyn RemoteClientDelegate>,
 840        cx: &mut AsyncApp,
 841    ) -> Result<()> {
 842        if let Some(parent) = tmp_path_gz.parent() {
 843            let res = self
 844                .socket
 845                .run_command(
 846                    self.ssh_shell_kind,
 847                    "mkdir",
 848                    &["-p", parent.display(self.path_style()).as_ref()],
 849                    true,
 850                )
 851                .await;
 852            if !self.ssh_platform.os.is_windows() {
 853                // mkdir fails on windows if the path already exists ...
 854                res?;
 855            }
 856        }
 857
 858        let src_stat = fs::metadata(&src_path)
 859            .await
 860            .with_context(|| format!("failed to get metadata for {:?}", src_path))?;
 861        let size = src_stat.len();
 862
 863        let t0 = Instant::now();
 864        delegate.set_status(Some("Uploading remote development server"), cx);
 865        log::info!(
 866            "uploading remote development server to {:?} ({}kb)",
 867            tmp_path_gz,
 868            size / 1024
 869        );
 870        self.upload_file(src_path, tmp_path_gz)
 871            .await
 872            .context("failed to upload server binary")?;
 873        log::info!("uploaded remote development server in {:?}", t0.elapsed());
 874        Ok(())
 875    }
 876
 877    async fn extract_server_binary(
 878        &self,
 879        dst_path: &RelPath,
 880        tmp_path: &RelPath,
 881        delegate: &Arc<dyn RemoteClientDelegate>,
 882        cx: &mut AsyncApp,
 883    ) -> Result<()> {
 884        delegate.set_status(Some("Extracting remote development server"), cx);
 885        let server_mode = 0o755;
 886
 887        let shell_kind = ShellKind::Posix;
 888        let orig_tmp_path = tmp_path.display(self.path_style());
 889        let server_mode = format!("{:o}", server_mode);
 890        let server_mode = shell_kind
 891            .try_quote(&server_mode)
 892            .context("shell quoting")?;
 893        let dst_path = dst_path.display(self.path_style());
 894        let dst_path = shell_kind.try_quote(&dst_path).context("shell quoting")?;
 895        let script = if let Some(tmp_path) = orig_tmp_path.strip_suffix(".gz") {
 896            let orig_tmp_path = shell_kind
 897                .try_quote(&orig_tmp_path)
 898                .context("shell quoting")?;
 899            let tmp_path = shell_kind.try_quote(&tmp_path).context("shell quoting")?;
 900            format!(
 901                "gunzip -f {orig_tmp_path} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
 902            )
 903        } else {
 904            let orig_tmp_path = shell_kind
 905                .try_quote(&orig_tmp_path)
 906                .context("shell quoting")?;
 907            format!("chmod {server_mode} {orig_tmp_path} && mv {orig_tmp_path} {dst_path}",)
 908        };
 909        let args = shell_kind.args_for_shell(false, script.to_string());
 910        self.socket
 911            .run_command(self.ssh_shell_kind, "sh", &args, true)
 912            .await?;
 913        Ok(())
 914    }
 915
 916    fn build_scp_command(
 917        &self,
 918        src_path: &Path,
 919        dest_path_str: &str,
 920        args: Option<&[&str]>,
 921    ) -> process::Command {
 922        let mut command = util::command::new_smol_command("scp");
 923        self.socket.ssh_options(&mut command, false).args(
 924            self.socket
 925                .connection_options
 926                .port
 927                .map(|port| vec!["-P".to_string(), port.to_string()])
 928                .unwrap_or_default(),
 929        );
 930        if let Some(args) = args {
 931            command.args(args);
 932        }
 933        command.arg(src_path).arg(format!(
 934            "{}:{}",
 935            self.socket.connection_options.scp_destination(),
 936            dest_path_str
 937        ));
 938        command
 939    }
 940
 941    fn build_sftp_command(&self) -> process::Command {
 942        let mut command = util::command::new_smol_command("sftp");
 943        self.socket.ssh_options(&mut command, false).args(
 944            self.socket
 945                .connection_options
 946                .port
 947                .map(|port| vec!["-P".to_string(), port.to_string()])
 948                .unwrap_or_default(),
 949        );
 950        command.arg("-b").arg("-");
 951        command.arg(self.socket.connection_options.scp_destination());
 952        command.stdin(Stdio::piped());
 953        command
 954    }
 955
 956    async fn upload_file(&self, src_path: &Path, dest_path: &RelPath) -> Result<()> {
 957        log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
 958
 959        let src_path_display = src_path.display().to_string();
 960        let dest_path_str = dest_path.display(self.path_style());
 961
 962        // We will try SFTP first, and if that fails, we will fall back to SCP.
 963        // If SCP fails also, we give up and return an error.
 964        // The reason we allow a fallback from SFTP to SCP is that if the user has to specify a password,
 965        // depending on the implementation of SSH stack, SFTP may disable interactive password prompts in batch mode.
 966        // This is for example the case on Windows as evidenced by this implementation snippet:
 967        // https://github.com/PowerShell/openssh-portable/blob/b8c08ef9da9450a94a9c5ef717d96a7bd83f3332/sshconnect2.c#L417
 968        if Self::is_sftp_available().await {
 969            log::debug!("using SFTP for file upload");
 970            let mut command = self.build_sftp_command();
 971            let sftp_batch = format!("put {src_path_display} {dest_path_str}\n");
 972
 973            let mut child = command.spawn()?;
 974            if let Some(mut stdin) = child.stdin.take() {
 975                use futures::AsyncWriteExt;
 976                stdin.write_all(sftp_batch.as_bytes()).await?;
 977                stdin.flush().await?;
 978            }
 979
 980            let output = child.output().await?;
 981            if output.status.success() {
 982                return Ok(());
 983            }
 984
 985            let stderr = String::from_utf8_lossy(&output.stderr);
 986            log::debug!(
 987                "failed to upload file via SFTP {src_path_display} -> {dest_path_str}: {stderr}"
 988            );
 989        }
 990
 991        log::debug!("using SCP for file upload");
 992        let mut command = self.build_scp_command(src_path, &dest_path_str, None);
 993        let output = command.output().await?;
 994
 995        if output.status.success() {
 996            return Ok(());
 997        }
 998
 999        let stderr = String::from_utf8_lossy(&output.stderr);
1000        log::debug!(
1001            "failed to upload file via SCP {src_path_display} -> {dest_path_str}: {stderr}",
1002        );
1003        anyhow::bail!(
1004            "failed to upload file via STFP/SCP {} -> {}: {}",
1005            src_path_display,
1006            dest_path_str,
1007            stderr,
1008        );
1009    }
1010
1011    async fn is_sftp_available() -> bool {
1012        which::which("sftp").is_ok()
1013    }
1014}
1015
1016impl SshSocket {
1017    #[cfg(not(target_os = "windows"))]
1018    async fn new(options: SshConnectionOptions, socket_path: PathBuf) -> Result<Self> {
1019        Ok(Self {
1020            connection_options: options,
1021            envs: HashMap::default(),
1022            socket_path,
1023        })
1024    }
1025
1026    #[cfg(target_os = "windows")]
1027    async fn new(
1028        options: SshConnectionOptions,
1029        password: askpass::EncryptedPassword,
1030        executor: gpui::BackgroundExecutor,
1031    ) -> Result<Self> {
1032        let mut envs = HashMap::default();
1033        let get_password =
1034            move |_| Task::ready(std::ops::ControlFlow::Continue(Ok(password.clone())));
1035
1036        let _proxy = askpass::PasswordProxy::new(get_password, executor).await?;
1037        envs.insert("SSH_ASKPASS_REQUIRE".into(), "force".into());
1038        envs.insert(
1039            "SSH_ASKPASS".into(),
1040            _proxy.script_path().as_ref().display().to_string(),
1041        );
1042
1043        Ok(Self {
1044            connection_options: options,
1045            envs,
1046            _proxy,
1047        })
1048    }
1049
1050    // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
1051    // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
1052    // and passes -l as an argument to sh, not to ls.
1053    // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
1054    // into a machine. You must use `cd` to get back to $HOME.
1055    // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
1056    fn ssh_command(
1057        &self,
1058        shell_kind: ShellKind,
1059        program: &str,
1060        args: &[impl AsRef<str>],
1061        allow_pseudo_tty: bool,
1062    ) -> process::Command {
1063        let mut command = util::command::new_smol_command("ssh");
1064        let program = shell_kind.prepend_command_prefix(program);
1065        let mut to_run = shell_kind
1066            .try_quote_prefix_aware(&program)
1067            .expect("shell quoting")
1068            .into_owned();
1069        for arg in args {
1070            // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
1071            debug_assert!(
1072                !arg.as_ref().contains('\n'),
1073                "multiline arguments do not work in all shells"
1074            );
1075            to_run.push(' ');
1076            to_run.push_str(&shell_kind.try_quote(arg.as_ref()).expect("shell quoting"));
1077        }
1078        let separator = shell_kind.sequential_commands_separator();
1079        let to_run = format!("cd{separator} {to_run}");
1080        self.ssh_options(&mut command, true)
1081            .arg(self.connection_options.ssh_destination());
1082        if !allow_pseudo_tty {
1083            command.arg("-T");
1084        }
1085        command.arg(to_run);
1086        log::debug!("ssh {:?}", command);
1087        command
1088    }
1089
1090    async fn run_command(
1091        &self,
1092        shell_kind: ShellKind,
1093        program: &str,
1094        args: &[impl AsRef<str>],
1095        allow_pseudo_tty: bool,
1096    ) -> Result<String> {
1097        let mut command = self.ssh_command(shell_kind, program, args, allow_pseudo_tty);
1098        let output = command.output().await?;
1099        log::debug!("{:?}: {:?}", command, output);
1100        anyhow::ensure!(
1101            output.status.success(),
1102            "failed to run command {command:?}: {}",
1103            String::from_utf8_lossy(&output.stderr)
1104        );
1105        Ok(String::from_utf8_lossy(&output.stdout).to_string())
1106    }
1107
1108    #[cfg(not(target_os = "windows"))]
1109    fn ssh_options<'a>(
1110        &self,
1111        command: &'a mut process::Command,
1112        include_port_forwards: bool,
1113    ) -> &'a mut process::Command {
1114        let args = if include_port_forwards {
1115            self.connection_options.additional_args()
1116        } else {
1117            self.connection_options.additional_args_for_scp()
1118        };
1119
1120        command
1121            .stdin(Stdio::piped())
1122            .stdout(Stdio::piped())
1123            .stderr(Stdio::piped())
1124            .args(args)
1125            .args(["-o", "ControlMaster=no", "-o"])
1126            .arg(format!("ControlPath={}", self.socket_path.display()))
1127    }
1128
1129    #[cfg(target_os = "windows")]
1130    fn ssh_options<'a>(
1131        &self,
1132        command: &'a mut process::Command,
1133        include_port_forwards: bool,
1134    ) -> &'a mut process::Command {
1135        let args = if include_port_forwards {
1136            self.connection_options.additional_args()
1137        } else {
1138            self.connection_options.additional_args_for_scp()
1139        };
1140
1141        command
1142            .stdin(Stdio::piped())
1143            .stdout(Stdio::piped())
1144            .stderr(Stdio::piped())
1145            .args(args)
1146            .envs(self.envs.clone())
1147    }
1148
1149    // On Windows, we need to use `SSH_ASKPASS` to provide the password to ssh.
1150    // On Linux, we use the `ControlPath` option to create a socket file that ssh can use to
1151    #[cfg(not(target_os = "windows"))]
1152    fn ssh_args(&self) -> Vec<String> {
1153        let mut arguments = self.connection_options.additional_args();
1154        arguments.extend(vec![
1155            "-o".to_string(),
1156            "ControlMaster=no".to_string(),
1157            "-o".to_string(),
1158            format!("ControlPath={}", self.socket_path.display()),
1159            self.connection_options.ssh_destination(),
1160        ]);
1161        arguments
1162    }
1163
1164    #[cfg(target_os = "windows")]
1165    fn ssh_args(&self) -> Vec<String> {
1166        let mut arguments = self.connection_options.additional_args();
1167        arguments.push(self.connection_options.ssh_destination());
1168        arguments
1169    }
1170
1171    async fn platform(&self, shell: ShellKind, is_windows: bool) -> Result<RemotePlatform> {
1172        if is_windows {
1173            self.platform_windows(shell).await
1174        } else {
1175            self.platform_posix(shell).await
1176        }
1177    }
1178
1179    async fn platform_posix(&self, shell: ShellKind) -> Result<RemotePlatform> {
1180        let output = self
1181            .run_command(shell, "uname", &["-sm"], false)
1182            .await
1183            .context("Failed to run 'uname -sm' to determine platform")?;
1184        parse_platform(&output)
1185    }
1186
1187    async fn platform_windows(&self, shell: ShellKind) -> Result<RemotePlatform> {
1188        let output = self
1189            .run_command(
1190                shell,
1191                "cmd",
1192                &["/c", "echo", "%PROCESSOR_ARCHITECTURE%"],
1193                false,
1194            )
1195            .await
1196            .context(
1197                "Failed to run 'echo %PROCESSOR_ARCHITECTURE%' to determine Windows architecture",
1198            )?;
1199
1200        Ok(RemotePlatform {
1201            os: RemoteOs::Windows,
1202            arch: match output.trim() {
1203                "AMD64" => RemoteArch::X86_64,
1204                "ARM64" => RemoteArch::Aarch64,
1205                arch => anyhow::bail!(
1206                    "Prebuilt remote servers are not yet available for windows-{arch}. See https://zed.dev/docs/remote-development"
1207                ),
1208            },
1209        })
1210    }
1211
1212    /// Probes whether the remote host is running Windows.
1213    ///
1214    /// This is done by attempting to run a simple Windows-specific command.
1215    /// If it succeeds and returns Windows-like output, we assume it's Windows.
1216    async fn probe_is_windows(&self) -> bool {
1217        match self
1218            .run_command(ShellKind::PowerShell, "cmd", &["/c", "ver"], false)
1219            .await
1220        {
1221            // Windows 'ver' command outputs something like "Microsoft Windows [Version 10.0.19045.5011]"
1222            Ok(output) => output.trim().contains("indows"),
1223            Err(_) => false,
1224        }
1225    }
1226
1227    async fn shell(&self, is_windows: bool) -> String {
1228        if is_windows {
1229            self.shell_windows().await
1230        } else {
1231            self.shell_posix().await
1232        }
1233    }
1234
1235    async fn shell_posix(&self) -> String {
1236        const DEFAULT_SHELL: &str = "sh";
1237        match self
1238            .run_command(ShellKind::Posix, "sh", &["-c", "echo $SHELL"], false)
1239            .await
1240        {
1241            Ok(output) => parse_shell(&output, DEFAULT_SHELL),
1242            Err(e) => {
1243                log::error!("Failed to detect remote shell: {e}");
1244                DEFAULT_SHELL.to_owned()
1245            }
1246        }
1247    }
1248
1249    async fn shell_windows(&self) -> String {
1250        // powershell is always the default, and cannot really be removed from the system
1251        // so we can rely on that fact and reasonably assume that we will be running in a
1252        // powershell environment
1253        "powershell.exe".to_owned()
1254    }
1255}
1256
1257fn parse_port_number(port_str: &str) -> Result<u16> {
1258    port_str
1259        .parse()
1260        .with_context(|| format!("parsing port number: {port_str}"))
1261}
1262
1263fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
1264    let parts: Vec<&str> = spec.split(':').collect();
1265
1266    match parts.len() {
1267        4 => {
1268            let local_port = parse_port_number(parts[1])?;
1269            let remote_port = parse_port_number(parts[3])?;
1270
1271            Ok(SshPortForwardOption {
1272                local_host: Some(parts[0].to_string()),
1273                local_port,
1274                remote_host: Some(parts[2].to_string()),
1275                remote_port,
1276            })
1277        }
1278        3 => {
1279            let local_port = parse_port_number(parts[0])?;
1280            let remote_port = parse_port_number(parts[2])?;
1281
1282            Ok(SshPortForwardOption {
1283                local_host: None,
1284                local_port,
1285                remote_host: Some(parts[1].to_string()),
1286                remote_port,
1287            })
1288        }
1289        _ => anyhow::bail!("Invalid port forward format"),
1290    }
1291}
1292
1293impl SshConnectionOptions {
1294    pub fn parse_command_line(input: &str) -> Result<Self> {
1295        let input = input.trim_start_matches("ssh ");
1296        let mut hostname: Option<String> = None;
1297        let mut username: Option<String> = None;
1298        let mut port: Option<u16> = None;
1299        let mut args = Vec::new();
1300        let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
1301
1302        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
1303        const ALLOWED_OPTS: &[&str] = &[
1304            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
1305        ];
1306        const ALLOWED_ARGS: &[&str] = &[
1307            "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
1308            "-w",
1309        ];
1310
1311        let mut tokens = ShellKind::Posix
1312            .split(input)
1313            .context("invalid input")?
1314            .into_iter();
1315
1316        'outer: while let Some(arg) = tokens.next() {
1317            if ALLOWED_OPTS.contains(&(&arg as &str)) {
1318                args.push(arg.to_string());
1319                continue;
1320            }
1321            if arg == "-p" {
1322                port = tokens.next().and_then(|arg| arg.parse().ok());
1323                continue;
1324            } else if let Some(p) = arg.strip_prefix("-p") {
1325                port = p.parse().ok();
1326                continue;
1327            }
1328            if arg == "-l" {
1329                username = tokens.next();
1330                continue;
1331            } else if let Some(l) = arg.strip_prefix("-l") {
1332                username = Some(l.to_string());
1333                continue;
1334            }
1335            if arg == "-L" || arg.starts_with("-L") {
1336                let forward_spec = if arg == "-L" {
1337                    tokens.next()
1338                } else {
1339                    Some(arg.strip_prefix("-L").unwrap().to_string())
1340                };
1341
1342                if let Some(spec) = forward_spec {
1343                    port_forwards.push(parse_port_forward_spec(&spec)?);
1344                } else {
1345                    anyhow::bail!("Missing port forward format");
1346                }
1347            }
1348
1349            for a in ALLOWED_ARGS {
1350                if arg == *a {
1351                    args.push(arg);
1352                    if let Some(next) = tokens.next() {
1353                        args.push(next);
1354                    }
1355                    continue 'outer;
1356                } else if arg.starts_with(a) {
1357                    args.push(arg);
1358                    continue 'outer;
1359                }
1360            }
1361            if arg.starts_with("-") || hostname.is_some() {
1362                anyhow::bail!("unsupported argument: {:?}", arg);
1363            }
1364            let mut input = &arg as &str;
1365            // Destination might be: username1@username2@ip2@ip1
1366            if let Some((u, rest)) = input.rsplit_once('@') {
1367                input = rest;
1368                username = Some(u.to_string());
1369            }
1370
1371            // Handle port parsing, accounting for IPv6 addresses
1372            // IPv6 addresses can be: 2001:db8::1 or [2001:db8::1]:22
1373            if input.starts_with('[') {
1374                if let Some((rest, p)) = input.rsplit_once("]:") {
1375                    input = rest.strip_prefix('[').unwrap_or(rest);
1376                    port = p.parse().ok();
1377                } else if input.ends_with(']') {
1378                    input = input.strip_prefix('[').unwrap_or(input);
1379                    input = input.strip_suffix(']').unwrap_or(input);
1380                }
1381            } else if let Some((rest, p)) = input.rsplit_once(':')
1382                && !rest.contains(":")
1383            {
1384                input = rest;
1385                port = p.parse().ok();
1386            }
1387
1388            hostname = Some(input.to_string())
1389        }
1390
1391        let Some(hostname) = hostname else {
1392            anyhow::bail!("missing hostname");
1393        };
1394
1395        let port_forwards = match port_forwards.len() {
1396            0 => None,
1397            _ => Some(port_forwards),
1398        };
1399
1400        Ok(Self {
1401            host: hostname.into(),
1402            username,
1403            port,
1404            port_forwards,
1405            args: Some(args),
1406            password: None,
1407            nickname: None,
1408            upload_binary_over_ssh: false,
1409            connection_timeout: None,
1410        })
1411    }
1412
1413    pub fn ssh_destination(&self) -> String {
1414        let mut result = String::default();
1415        if let Some(username) = &self.username {
1416            // Username might be: username1@username2@ip2
1417            let username = urlencoding::encode(username);
1418            result.push_str(&username);
1419            result.push('@');
1420        }
1421
1422        result.push_str(&self.host.to_string());
1423        result
1424    }
1425
1426    pub fn additional_args_for_scp(&self) -> Vec<String> {
1427        self.args.iter().flatten().cloned().collect::<Vec<String>>()
1428    }
1429
1430    pub fn additional_args(&self) -> Vec<String> {
1431        let mut args = self.additional_args_for_scp();
1432
1433        if let Some(timeout) = self.connection_timeout {
1434            args.extend(["-o".to_string(), format!("ConnectTimeout={}", timeout)]);
1435        }
1436
1437        if let Some(port) = self.port {
1438            args.push("-p".to_string());
1439            args.push(port.to_string());
1440        }
1441
1442        if let Some(forwards) = &self.port_forwards {
1443            args.extend(forwards.iter().map(|pf| {
1444                let local_host = match &pf.local_host {
1445                    Some(host) => host,
1446                    None => "localhost",
1447                };
1448                let remote_host = match &pf.remote_host {
1449                    Some(host) => host,
1450                    None => "localhost",
1451                };
1452
1453                format!(
1454                    "-L{}:{}:{}:{}",
1455                    local_host, pf.local_port, remote_host, pf.remote_port
1456                )
1457            }));
1458        }
1459
1460        args
1461    }
1462
1463    fn scp_destination(&self) -> String {
1464        if let Some(username) = &self.username {
1465            format!("{}@{}", username, self.host.to_bracketed_string())
1466        } else {
1467            self.host.to_string()
1468        }
1469    }
1470
1471    pub fn connection_string(&self) -> String {
1472        let host = if let Some(port) = &self.port {
1473            format!("{}:{}", self.host.to_bracketed_string(), port)
1474        } else {
1475            self.host.to_string()
1476        };
1477
1478        if let Some(username) = &self.username {
1479            format!("{}@{}", username, host)
1480        } else {
1481            host
1482        }
1483    }
1484}
1485
1486fn build_command(
1487    input_program: Option<String>,
1488    input_args: &[String],
1489    input_env: &HashMap<String, String>,
1490    working_dir: Option<String>,
1491    port_forward: Option<(u16, String, u16)>,
1492    ssh_env: HashMap<String, String>,
1493    ssh_path_style: PathStyle,
1494    ssh_shell: &str,
1495    ssh_shell_kind: ShellKind,
1496    ssh_args: Vec<String>,
1497    interactive: Interactive,
1498) -> Result<CommandTemplate> {
1499    use std::fmt::Write as _;
1500
1501    let mut exec = String::new();
1502    if let Some(working_dir) = working_dir {
1503        let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1504
1505        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
1506        // replace with something that works
1507        const TILDE_PREFIX: &'static str = "~/";
1508        if working_dir.starts_with(TILDE_PREFIX) {
1509            let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
1510            write!(
1511                exec,
1512                "cd \"$HOME/{working_dir}\" {} ",
1513                ssh_shell_kind.sequential_and_commands_separator()
1514            )?;
1515        } else {
1516            write!(
1517                exec,
1518                "cd \"{working_dir}\" {} ",
1519                ssh_shell_kind.sequential_and_commands_separator()
1520            )?;
1521        }
1522    } else {
1523        write!(
1524            exec,
1525            "cd {} ",
1526            ssh_shell_kind.sequential_and_commands_separator()
1527        )?;
1528    };
1529    write!(exec, "exec env ")?;
1530
1531    for (k, v) in input_env.iter() {
1532        write!(
1533            exec,
1534            "{}={} ",
1535            k,
1536            ssh_shell_kind.try_quote(v).context("shell quoting")?
1537        )?;
1538    }
1539
1540    if let Some(input_program) = input_program {
1541        write!(
1542            exec,
1543            "{}",
1544            ssh_shell_kind
1545                .try_quote_prefix_aware(&input_program)
1546                .context("shell quoting")?
1547        )?;
1548        for arg in input_args {
1549            let arg = ssh_shell_kind.try_quote(&arg).context("shell quoting")?;
1550            write!(exec, " {}", &arg)?;
1551        }
1552    } else {
1553        write!(exec, "{ssh_shell} -l")?;
1554    };
1555
1556    let mut args = Vec::new();
1557    args.extend(ssh_args);
1558
1559    if let Some((local_port, host, remote_port)) = port_forward {
1560        args.push("-L".into());
1561        args.push(format!("{local_port}:{host}:{remote_port}"));
1562    }
1563
1564    // -q suppresses the "Connection to ... closed." message that SSH prints when
1565    // the connection terminates with -t (pseudo-terminal allocation)
1566    args.push("-q".into());
1567    match interactive {
1568        // -t forces pseudo-TTY allocation (for interactive use)
1569        Interactive::Yes => args.push("-t".into()),
1570        // -T disables pseudo-TTY allocation (for non-interactive piped stdio)
1571        Interactive::No => args.push("-T".into()),
1572    }
1573    args.push(exec);
1574
1575    Ok(CommandTemplate {
1576        program: "ssh".into(),
1577        args,
1578        env: ssh_env,
1579    })
1580}
1581
1582#[cfg(test)]
1583mod tests {
1584    use super::*;
1585
1586    #[test]
1587    fn test_build_command() -> Result<()> {
1588        let mut input_env = HashMap::default();
1589        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1590        let mut env = HashMap::default();
1591        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1592
1593        // Test non-interactive command (interactive=false should use -T)
1594        let command = build_command(
1595            Some("remote_program".to_string()),
1596            &["arg1".to_string(), "arg2".to_string()],
1597            &input_env,
1598            Some("~/work".to_string()),
1599            None,
1600            env.clone(),
1601            PathStyle::Posix,
1602            "/bin/bash",
1603            ShellKind::Posix,
1604            vec!["-o".to_string(), "ControlMaster=auto".to_string()],
1605            Interactive::No,
1606        )?;
1607        assert_eq!(command.program, "ssh");
1608        // Should contain -T for non-interactive
1609        assert!(command.args.iter().any(|arg| arg == "-T"));
1610        assert!(!command.args.iter().any(|arg| arg == "-t"));
1611
1612        // Test interactive command (interactive=true should use -t)
1613        let command = build_command(
1614            Some("remote_program".to_string()),
1615            &["arg1".to_string(), "arg2".to_string()],
1616            &input_env,
1617            Some("~/work".to_string()),
1618            None,
1619            env.clone(),
1620            PathStyle::Posix,
1621            "/bin/fish",
1622            ShellKind::Fish,
1623            vec!["-p".to_string(), "2222".to_string()],
1624            Interactive::Yes,
1625        )?;
1626
1627        assert_eq!(command.program, "ssh");
1628        assert_eq!(
1629            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1630            [
1631                "-p",
1632                "2222",
1633                "-q",
1634                "-t",
1635                "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1636            ]
1637        );
1638        assert_eq!(command.env, env);
1639
1640        let mut input_env = HashMap::default();
1641        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1642        let mut env = HashMap::default();
1643        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1644
1645        let command = build_command(
1646            None,
1647            &[],
1648            &input_env,
1649            None,
1650            Some((1, "foo".to_owned(), 2)),
1651            env.clone(),
1652            PathStyle::Posix,
1653            "/bin/fish",
1654            ShellKind::Fish,
1655            vec!["-p".to_string(), "2222".to_string()],
1656            Interactive::Yes,
1657        )?;
1658
1659        assert_eq!(command.program, "ssh");
1660        assert_eq!(
1661            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1662            [
1663                "-p",
1664                "2222",
1665                "-L",
1666                "1:foo:2",
1667                "-q",
1668                "-t",
1669                "cd && exec env INPUT_VA=val /bin/fish -l"
1670            ]
1671        );
1672        assert_eq!(command.env, env);
1673
1674        Ok(())
1675    }
1676
1677    #[test]
1678    fn scp_args_exclude_port_forward_flags() {
1679        let options = SshConnectionOptions {
1680            host: "example.com".into(),
1681            args: Some(vec![
1682                "-p".to_string(),
1683                "2222".to_string(),
1684                "-o".to_string(),
1685                "StrictHostKeyChecking=no".to_string(),
1686            ]),
1687            port_forwards: Some(vec![SshPortForwardOption {
1688                local_host: Some("127.0.0.1".to_string()),
1689                local_port: 8080,
1690                remote_host: Some("127.0.0.1".to_string()),
1691                remote_port: 80,
1692            }]),
1693            ..Default::default()
1694        };
1695
1696        let ssh_args = options.additional_args();
1697        assert!(
1698            ssh_args.iter().any(|arg| arg.starts_with("-L")),
1699            "expected ssh args to include port-forward: {ssh_args:?}"
1700        );
1701
1702        let scp_args = options.additional_args_for_scp();
1703        assert_eq!(
1704            scp_args,
1705            vec![
1706                "-p".to_string(),
1707                "2222".to_string(),
1708                "-o".to_string(),
1709                "StrictHostKeyChecking=no".to_string(),
1710            ]
1711        );
1712    }
1713
1714    #[test]
1715    fn test_host_parsing() -> Result<()> {
1716        let opts = SshConnectionOptions::parse_command_line("user@2001:db8::1")?;
1717        assert_eq!(opts.host, "2001:db8::1".into());
1718        assert_eq!(opts.username, Some("user".to_string()));
1719        assert_eq!(opts.port, None);
1720
1721        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]:2222")?;
1722        assert_eq!(opts.host, "2001:db8::1".into());
1723        assert_eq!(opts.username, Some("user".to_string()));
1724        assert_eq!(opts.port, Some(2222));
1725
1726        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]")?;
1727        assert_eq!(opts.host, "2001:db8::1".into());
1728        assert_eq!(opts.username, Some("user".to_string()));
1729        assert_eq!(opts.port, None);
1730
1731        let opts = SshConnectionOptions::parse_command_line("2001:db8::1")?;
1732        assert_eq!(opts.host, "2001:db8::1".into());
1733        assert_eq!(opts.username, None);
1734        assert_eq!(opts.port, None);
1735
1736        let opts = SshConnectionOptions::parse_command_line("[2001:db8::1]:2222")?;
1737        assert_eq!(opts.host, "2001:db8::1".into());
1738        assert_eq!(opts.username, None);
1739        assert_eq!(opts.port, Some(2222));
1740
1741        let opts = SshConnectionOptions::parse_command_line("user@example.com:2222")?;
1742        assert_eq!(opts.host, "example.com".into());
1743        assert_eq!(opts.username, Some("user".to_string()));
1744        assert_eq!(opts.port, Some(2222));
1745
1746        let opts = SshConnectionOptions::parse_command_line("user@192.168.1.1:2222")?;
1747        assert_eq!(opts.host, "192.168.1.1".into());
1748        assert_eq!(opts.username, Some("user".to_string()));
1749        assert_eq!(opts.port, Some(2222));
1750
1751        Ok(())
1752    }
1753}