ssh.rs

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