ssh.rs

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