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