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 = ShellKind::Posix
1081            .split(input)
1082            .context("invalid input")?
1083            .into_iter();
1084
1085        'outer: while let Some(arg) = tokens.next() {
1086            if ALLOWED_OPTS.contains(&(&arg as &str)) {
1087                args.push(arg.to_string());
1088                continue;
1089            }
1090            if arg == "-p" {
1091                port = tokens.next().and_then(|arg| arg.parse().ok());
1092                continue;
1093            } else if let Some(p) = arg.strip_prefix("-p") {
1094                port = p.parse().ok();
1095                continue;
1096            }
1097            if arg == "-l" {
1098                username = tokens.next();
1099                continue;
1100            } else if let Some(l) = arg.strip_prefix("-l") {
1101                username = Some(l.to_string());
1102                continue;
1103            }
1104            if arg == "-L" || arg.starts_with("-L") {
1105                let forward_spec = if arg == "-L" {
1106                    tokens.next()
1107                } else {
1108                    Some(arg.strip_prefix("-L").unwrap().to_string())
1109                };
1110
1111                if let Some(spec) = forward_spec {
1112                    port_forwards.push(parse_port_forward_spec(&spec)?);
1113                } else {
1114                    anyhow::bail!("Missing port forward format");
1115                }
1116            }
1117
1118            for a in ALLOWED_ARGS {
1119                if arg == *a {
1120                    args.push(arg);
1121                    if let Some(next) = tokens.next() {
1122                        args.push(next);
1123                    }
1124                    continue 'outer;
1125                } else if arg.starts_with(a) {
1126                    args.push(arg);
1127                    continue 'outer;
1128                }
1129            }
1130            if arg.starts_with("-") || hostname.is_some() {
1131                anyhow::bail!("unsupported argument: {:?}", arg);
1132            }
1133            let mut input = &arg as &str;
1134            // Destination might be: username1@username2@ip2@ip1
1135            if let Some((u, rest)) = input.rsplit_once('@') {
1136                input = rest;
1137                username = Some(u.to_string());
1138            }
1139            if let Some((rest, p)) = input.split_once(':') {
1140                input = rest;
1141                port = p.parse().ok()
1142            }
1143            hostname = Some(input.to_string())
1144        }
1145
1146        let Some(hostname) = hostname else {
1147            anyhow::bail!("missing hostname");
1148        };
1149
1150        let port_forwards = match port_forwards.len() {
1151            0 => None,
1152            _ => Some(port_forwards),
1153        };
1154
1155        Ok(Self {
1156            host: hostname,
1157            username,
1158            port,
1159            port_forwards,
1160            args: Some(args),
1161            password: None,
1162            nickname: None,
1163            upload_binary_over_ssh: false,
1164        })
1165    }
1166
1167    pub fn ssh_url(&self) -> String {
1168        let mut result = String::from("ssh://");
1169        if let Some(username) = &self.username {
1170            // Username might be: username1@username2@ip2
1171            let username = urlencoding::encode(username);
1172            result.push_str(&username);
1173            result.push('@');
1174        }
1175        result.push_str(&self.host);
1176        if let Some(port) = self.port {
1177            result.push(':');
1178            result.push_str(&port.to_string());
1179        }
1180        result
1181    }
1182
1183    pub fn additional_args_for_scp(&self) -> Vec<String> {
1184        self.args.iter().flatten().cloned().collect::<Vec<String>>()
1185    }
1186
1187    pub fn additional_args(&self) -> Vec<String> {
1188        let mut args = self.additional_args_for_scp();
1189
1190        if let Some(forwards) = &self.port_forwards {
1191            args.extend(forwards.iter().map(|pf| {
1192                let local_host = match &pf.local_host {
1193                    Some(host) => host,
1194                    None => "localhost",
1195                };
1196                let remote_host = match &pf.remote_host {
1197                    Some(host) => host,
1198                    None => "localhost",
1199                };
1200
1201                format!(
1202                    "-L{}:{}:{}:{}",
1203                    local_host, pf.local_port, remote_host, pf.remote_port
1204                )
1205            }));
1206        }
1207
1208        args
1209    }
1210
1211    fn scp_url(&self) -> String {
1212        if let Some(username) = &self.username {
1213            format!("{}@{}", username, self.host)
1214        } else {
1215            self.host.clone()
1216        }
1217    }
1218
1219    pub fn connection_string(&self) -> String {
1220        let host = if let Some(username) = &self.username {
1221            format!("{}@{}", username, self.host)
1222        } else {
1223            self.host.clone()
1224        };
1225        if let Some(port) = &self.port {
1226            format!("{}:{}", host, port)
1227        } else {
1228            host
1229        }
1230    }
1231}
1232
1233fn build_command(
1234    input_program: Option<String>,
1235    input_args: &[String],
1236    input_env: &HashMap<String, String>,
1237    working_dir: Option<String>,
1238    port_forward: Option<(u16, String, u16)>,
1239    ssh_env: HashMap<String, String>,
1240    ssh_path_style: PathStyle,
1241    ssh_shell: &str,
1242    ssh_args: Vec<String>,
1243) -> Result<CommandTemplate> {
1244    use std::fmt::Write as _;
1245
1246    let shell_kind = ShellKind::new(ssh_shell, false);
1247    let mut exec = String::new();
1248    if let Some(working_dir) = working_dir {
1249        let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1250
1251        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
1252        // replace with with something that works
1253        const TILDE_PREFIX: &'static str = "~/";
1254        if working_dir.starts_with(TILDE_PREFIX) {
1255            let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
1256            write!(exec, "cd \"$HOME/{working_dir}\" && ",)?;
1257        } else {
1258            write!(exec, "cd \"{working_dir}\" && ",)?;
1259        }
1260    } else {
1261        write!(exec, "cd && ")?;
1262    };
1263    write!(exec, "exec env ")?;
1264
1265    for (k, v) in input_env.iter() {
1266        write!(
1267            exec,
1268            "{}={} ",
1269            k,
1270            shell_kind.try_quote(v).context("shell quoting")?
1271        )?;
1272    }
1273
1274    if let Some(input_program) = input_program {
1275        write!(
1276            exec,
1277            "{}",
1278            shell_kind
1279                .try_quote(&input_program)
1280                .context("shell quoting")?
1281        )?;
1282        for arg in input_args {
1283            write!(
1284                exec,
1285                " {}",
1286                shell_kind.try_quote(&arg).context("shell quoting")?
1287            )?;
1288        }
1289    } else {
1290        write!(exec, "{ssh_shell} -l")?;
1291    };
1292
1293    let mut args = Vec::new();
1294    args.extend(ssh_args);
1295
1296    if let Some((local_port, host, remote_port)) = port_forward {
1297        args.push("-L".into());
1298        args.push(format!("{local_port}:{host}:{remote_port}"));
1299    }
1300
1301    args.push("-t".into());
1302    args.push(exec);
1303    Ok(CommandTemplate {
1304        program: "ssh".into(),
1305        args,
1306        env: ssh_env,
1307    })
1308}
1309
1310#[cfg(test)]
1311mod tests {
1312    use super::*;
1313
1314    #[test]
1315    fn test_build_command() -> Result<()> {
1316        let mut input_env = HashMap::default();
1317        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1318        let mut env = HashMap::default();
1319        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1320
1321        let command = build_command(
1322            Some("remote_program".to_string()),
1323            &["arg1".to_string(), "arg2".to_string()],
1324            &input_env,
1325            Some("~/work".to_string()),
1326            None,
1327            env.clone(),
1328            PathStyle::Posix,
1329            "/bin/fish",
1330            vec!["-p".to_string(), "2222".to_string()],
1331        )?;
1332
1333        assert_eq!(command.program, "ssh");
1334        assert_eq!(
1335            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1336            [
1337                "-p",
1338                "2222",
1339                "-t",
1340                "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1341            ]
1342        );
1343        assert_eq!(command.env, env);
1344
1345        let mut input_env = HashMap::default();
1346        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1347        let mut env = HashMap::default();
1348        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1349
1350        let command = build_command(
1351            None,
1352            &["arg1".to_string(), "arg2".to_string()],
1353            &input_env,
1354            None,
1355            Some((1, "foo".to_owned(), 2)),
1356            env.clone(),
1357            PathStyle::Posix,
1358            "/bin/fish",
1359            vec!["-p".to_string(), "2222".to_string()],
1360        )?;
1361
1362        assert_eq!(command.program, "ssh");
1363        assert_eq!(
1364            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1365            [
1366                "-p",
1367                "2222",
1368                "-L",
1369                "1:foo:2",
1370                "-t",
1371                "cd && exec env INPUT_VA=val /bin/fish -l"
1372            ]
1373        );
1374        assert_eq!(command.env, env);
1375
1376        Ok(())
1377    }
1378
1379    #[test]
1380    fn scp_args_exclude_port_forward_flags() {
1381        let options = SshConnectionOptions {
1382            host: "example.com".into(),
1383            args: Some(vec![
1384                "-p".to_string(),
1385                "2222".to_string(),
1386                "-o".to_string(),
1387                "StrictHostKeyChecking=no".to_string(),
1388            ]),
1389            port_forwards: Some(vec![SshPortForwardOption {
1390                local_host: Some("127.0.0.1".to_string()),
1391                local_port: 8080,
1392                remote_host: Some("127.0.0.1".to_string()),
1393                remote_port: 80,
1394            }]),
1395            ..Default::default()
1396        };
1397
1398        let ssh_args = options.additional_args();
1399        assert!(
1400            ssh_args.iter().any(|arg| arg.starts_with("-L")),
1401            "expected ssh args to include port-forward: {ssh_args:?}"
1402        );
1403
1404        let scp_args = options.additional_args_for_scp();
1405        assert_eq!(
1406            scp_args,
1407            vec![
1408                "-p".to_string(),
1409                "2222".to_string(),
1410                "-o".to_string(),
1411                "StrictHostKeyChecking=no".to_string()
1412            ]
1413        );
1414        assert!(
1415            scp_args.iter().all(|arg| !arg.starts_with("-L")),
1416            "scp args should not contain port forward flags: {scp_args:?}"
1417        );
1418    }
1419}