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