ssh.rs

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