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 args = shell_kind.args_for_shell(false, script.to_string());
 746        self.socket.run_command("sh", &args).await?;
 747        Ok(())
 748    }
 749
 750    fn build_scp_command(
 751        &self,
 752        src_path: &Path,
 753        dest_path_str: &str,
 754        args: Option<&[&str]>,
 755    ) -> process::Command {
 756        let mut command = util::command::new_smol_command("scp");
 757        self.socket.ssh_options(&mut command, false).args(
 758            self.socket
 759                .connection_options
 760                .port
 761                .map(|port| vec!["-P".to_string(), port.to_string()])
 762                .unwrap_or_default(),
 763        );
 764        if let Some(args) = args {
 765            command.args(args);
 766        }
 767        command.arg(src_path).arg(format!(
 768            "{}:{}",
 769            self.socket.connection_options.scp_url(),
 770            dest_path_str
 771        ));
 772        command
 773    }
 774
 775    fn build_sftp_command(&self) -> process::Command {
 776        let mut command = util::command::new_smol_command("sftp");
 777        self.socket.ssh_options(&mut command, false).args(
 778            self.socket
 779                .connection_options
 780                .port
 781                .map(|port| vec!["-P".to_string(), port.to_string()])
 782                .unwrap_or_default(),
 783        );
 784        command.arg("-b").arg("-");
 785        command.arg(self.socket.connection_options.scp_url());
 786        command.stdin(Stdio::piped());
 787        command
 788    }
 789
 790    async fn upload_file(&self, src_path: &Path, dest_path: &RelPath) -> Result<()> {
 791        log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
 792
 793        let dest_path_str = dest_path.display(self.path_style());
 794
 795        if Self::is_sftp_available().await {
 796            log::debug!("using SFTP for file upload");
 797            let mut command = self.build_sftp_command();
 798            let sftp_batch = format!("put {} {}\n", src_path.display(), dest_path_str);
 799
 800            let mut child = command.spawn()?;
 801            if let Some(mut stdin) = child.stdin.take() {
 802                use futures::AsyncWriteExt;
 803                stdin.write_all(sftp_batch.as_bytes()).await?;
 804                drop(stdin);
 805            }
 806
 807            let output = child.output().await?;
 808            anyhow::ensure!(
 809                output.status.success(),
 810                "failed to upload file via SFTP {} -> {}: {}",
 811                src_path.display(),
 812                dest_path_str,
 813                String::from_utf8_lossy(&output.stderr)
 814            );
 815
 816            Ok(())
 817        } else {
 818            log::debug!("using SCP for file upload");
 819            let mut command = self.build_scp_command(src_path, &dest_path_str, None);
 820            let output = command.output().await?;
 821
 822            anyhow::ensure!(
 823                output.status.success(),
 824                "failed to upload file via SCP {} -> {}: {}",
 825                src_path.display(),
 826                dest_path_str,
 827                String::from_utf8_lossy(&output.stderr)
 828            );
 829
 830            Ok(())
 831        }
 832    }
 833
 834    async fn is_sftp_available() -> bool {
 835        which::which("sftp").is_ok()
 836    }
 837}
 838
 839impl SshSocket {
 840    #[cfg(not(target_os = "windows"))]
 841    async fn new(options: SshConnectionOptions, socket_path: PathBuf) -> Result<Self> {
 842        Ok(Self {
 843            connection_options: options,
 844            envs: HashMap::default(),
 845            socket_path,
 846        })
 847    }
 848
 849    #[cfg(target_os = "windows")]
 850    async fn new(
 851        options: SshConnectionOptions,
 852        password: askpass::EncryptedPassword,
 853        executor: gpui::BackgroundExecutor,
 854    ) -> Result<Self> {
 855        let mut envs = HashMap::default();
 856        let get_password =
 857            move |_| Task::ready(std::ops::ControlFlow::Continue(Ok(password.clone())));
 858
 859        let _proxy = askpass::PasswordProxy::new(get_password, executor).await?;
 860        envs.insert("SSH_ASKPASS_REQUIRE".into(), "force".into());
 861        envs.insert(
 862            "SSH_ASKPASS".into(),
 863            _proxy.script_path().as_ref().display().to_string(),
 864        );
 865
 866        Ok(Self {
 867            connection_options: options,
 868            envs,
 869            _proxy,
 870        })
 871    }
 872
 873    // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
 874    // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
 875    // and passes -l as an argument to sh, not to ls.
 876    // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
 877    // into a machine. You must use `cd` to get back to $HOME.
 878    // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
 879    fn ssh_command(&self, program: &str, args: &[impl AsRef<str>]) -> process::Command {
 880        let shell_kind = ShellKind::Posix;
 881        let mut command = util::command::new_smol_command("ssh");
 882        let mut to_run = shell_kind
 883            .try_quote(program)
 884            .expect("shell quoting")
 885            .into_owned();
 886        for arg in args {
 887            // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
 888            debug_assert!(
 889                !arg.as_ref().contains('\n'),
 890                "multiline arguments do not work in all shells"
 891            );
 892            to_run.push(' ');
 893            to_run.push_str(&shell_kind.try_quote(arg.as_ref()).expect("shell quoting"));
 894        }
 895        let separator = shell_kind.sequential_commands_separator();
 896        let to_run = format!("cd{separator} {to_run}");
 897        self.ssh_options(&mut command, true)
 898            .arg(self.connection_options.ssh_url())
 899            .arg("-T")
 900            .arg(to_run);
 901        log::debug!("ssh {:?}", command);
 902        command
 903    }
 904
 905    async fn run_command(&self, program: &str, args: &[impl AsRef<str>]) -> Result<String> {
 906        let output = self.ssh_command(program, args).output().await?;
 907        anyhow::ensure!(
 908            output.status.success(),
 909            "failed to run command: {}",
 910            String::from_utf8_lossy(&output.stderr)
 911        );
 912        Ok(String::from_utf8_lossy(&output.stdout).to_string())
 913    }
 914
 915    #[cfg(not(target_os = "windows"))]
 916    fn ssh_options<'a>(
 917        &self,
 918        command: &'a mut process::Command,
 919        include_port_forwards: bool,
 920    ) -> &'a mut process::Command {
 921        let args = if include_port_forwards {
 922            self.connection_options.additional_args()
 923        } else {
 924            self.connection_options.additional_args_for_scp()
 925        };
 926
 927        command
 928            .stdin(Stdio::piped())
 929            .stdout(Stdio::piped())
 930            .stderr(Stdio::piped())
 931            .args(args)
 932            .args(["-o", "ControlMaster=no", "-o"])
 933            .arg(format!("ControlPath={}", self.socket_path.display()))
 934    }
 935
 936    #[cfg(target_os = "windows")]
 937    fn ssh_options<'a>(
 938        &self,
 939        command: &'a mut process::Command,
 940        include_port_forwards: bool,
 941    ) -> &'a mut process::Command {
 942        let args = if include_port_forwards {
 943            self.connection_options.additional_args()
 944        } else {
 945            self.connection_options.additional_args_for_scp()
 946        };
 947
 948        command
 949            .stdin(Stdio::piped())
 950            .stdout(Stdio::piped())
 951            .stderr(Stdio::piped())
 952            .args(args)
 953            .envs(self.envs.clone())
 954    }
 955
 956    // On Windows, we need to use `SSH_ASKPASS` to provide the password to ssh.
 957    // On Linux, we use the `ControlPath` option to create a socket file that ssh can use to
 958    #[cfg(not(target_os = "windows"))]
 959    fn ssh_args(&self) -> Vec<String> {
 960        let mut arguments = self.connection_options.additional_args();
 961        arguments.extend(vec![
 962            "-o".to_string(),
 963            "ControlMaster=no".to_string(),
 964            "-o".to_string(),
 965            format!("ControlPath={}", self.socket_path.display()),
 966            self.connection_options.ssh_url(),
 967        ]);
 968        arguments
 969    }
 970
 971    #[cfg(target_os = "windows")]
 972    fn ssh_args(&self) -> Vec<String> {
 973        let mut arguments = self.connection_options.additional_args();
 974        arguments.push(self.connection_options.ssh_url());
 975        arguments
 976    }
 977
 978    async fn platform(&self, shell: ShellKind) -> Result<RemotePlatform> {
 979        let program = if shell == ShellKind::Nushell {
 980            "^uname"
 981        } else {
 982            "uname"
 983        };
 984        let uname = self.run_command(program, &["-sm"]).await?;
 985        let Some((os, arch)) = uname.split_once(" ") else {
 986            anyhow::bail!("unknown uname: {uname:?}")
 987        };
 988
 989        let os = match os.trim() {
 990            "Darwin" => "macos",
 991            "Linux" => "linux",
 992            _ => anyhow::bail!(
 993                "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
 994            ),
 995        };
 996        // exclude armv5,6,7 as they are 32-bit.
 997        let arch = if arch.starts_with("armv8")
 998            || arch.starts_with("armv9")
 999            || arch.starts_with("arm64")
1000            || arch.starts_with("aarch64")
1001        {
1002            "aarch64"
1003        } else if arch.starts_with("x86") {
1004            "x86_64"
1005        } else {
1006            anyhow::bail!(
1007                "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
1008            )
1009        };
1010
1011        Ok(RemotePlatform { os, arch })
1012    }
1013
1014    async fn shell(&self) -> String {
1015        match self.run_command("sh", &["-c", "echo $SHELL"]).await {
1016            Ok(shell) => shell.trim().to_owned(),
1017            Err(e) => {
1018                log::error!("Failed to get shell: {e}");
1019                "sh".to_owned()
1020            }
1021        }
1022    }
1023}
1024
1025fn parse_port_number(port_str: &str) -> Result<u16> {
1026    port_str
1027        .parse()
1028        .with_context(|| format!("parsing port number: {port_str}"))
1029}
1030
1031fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
1032    let parts: Vec<&str> = spec.split(':').collect();
1033
1034    match parts.len() {
1035        4 => {
1036            let local_port = parse_port_number(parts[1])?;
1037            let remote_port = parse_port_number(parts[3])?;
1038
1039            Ok(SshPortForwardOption {
1040                local_host: Some(parts[0].to_string()),
1041                local_port,
1042                remote_host: Some(parts[2].to_string()),
1043                remote_port,
1044            })
1045        }
1046        3 => {
1047            let local_port = parse_port_number(parts[0])?;
1048            let remote_port = parse_port_number(parts[2])?;
1049
1050            Ok(SshPortForwardOption {
1051                local_host: None,
1052                local_port,
1053                remote_host: Some(parts[1].to_string()),
1054                remote_port,
1055            })
1056        }
1057        _ => anyhow::bail!("Invalid port forward format"),
1058    }
1059}
1060
1061impl SshConnectionOptions {
1062    pub fn parse_command_line(input: &str) -> Result<Self> {
1063        let input = input.trim_start_matches("ssh ");
1064        let mut hostname: Option<String> = None;
1065        let mut username: Option<String> = None;
1066        let mut port: Option<u16> = None;
1067        let mut args = Vec::new();
1068        let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
1069
1070        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
1071        const ALLOWED_OPTS: &[&str] = &[
1072            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
1073        ];
1074        const ALLOWED_ARGS: &[&str] = &[
1075            "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
1076            "-w",
1077        ];
1078
1079        let mut tokens = ShellKind::Posix
1080            .split(input)
1081            .context("invalid input")?
1082            .into_iter();
1083
1084        'outer: while let Some(arg) = tokens.next() {
1085            if ALLOWED_OPTS.contains(&(&arg as &str)) {
1086                args.push(arg.to_string());
1087                continue;
1088            }
1089            if arg == "-p" {
1090                port = tokens.next().and_then(|arg| arg.parse().ok());
1091                continue;
1092            } else if let Some(p) = arg.strip_prefix("-p") {
1093                port = p.parse().ok();
1094                continue;
1095            }
1096            if arg == "-l" {
1097                username = tokens.next();
1098                continue;
1099            } else if let Some(l) = arg.strip_prefix("-l") {
1100                username = Some(l.to_string());
1101                continue;
1102            }
1103            if arg == "-L" || arg.starts_with("-L") {
1104                let forward_spec = if arg == "-L" {
1105                    tokens.next()
1106                } else {
1107                    Some(arg.strip_prefix("-L").unwrap().to_string())
1108                };
1109
1110                if let Some(spec) = forward_spec {
1111                    port_forwards.push(parse_port_forward_spec(&spec)?);
1112                } else {
1113                    anyhow::bail!("Missing port forward format");
1114                }
1115            }
1116
1117            for a in ALLOWED_ARGS {
1118                if arg == *a {
1119                    args.push(arg);
1120                    if let Some(next) = tokens.next() {
1121                        args.push(next);
1122                    }
1123                    continue 'outer;
1124                } else if arg.starts_with(a) {
1125                    args.push(arg);
1126                    continue 'outer;
1127                }
1128            }
1129            if arg.starts_with("-") || hostname.is_some() {
1130                anyhow::bail!("unsupported argument: {:?}", arg);
1131            }
1132            let mut input = &arg as &str;
1133            // Destination might be: username1@username2@ip2@ip1
1134            if let Some((u, rest)) = input.rsplit_once('@') {
1135                input = rest;
1136                username = Some(u.to_string());
1137            }
1138            if let Some((rest, p)) = input.split_once(':') {
1139                input = rest;
1140                port = p.parse().ok()
1141            }
1142            hostname = Some(input.to_string())
1143        }
1144
1145        let Some(hostname) = hostname else {
1146            anyhow::bail!("missing hostname");
1147        };
1148
1149        let port_forwards = match port_forwards.len() {
1150            0 => None,
1151            _ => Some(port_forwards),
1152        };
1153
1154        Ok(Self {
1155            host: hostname,
1156            username,
1157            port,
1158            port_forwards,
1159            args: Some(args),
1160            password: None,
1161            nickname: None,
1162            upload_binary_over_ssh: false,
1163        })
1164    }
1165
1166    pub fn ssh_url(&self) -> String {
1167        let mut result = String::from("ssh://");
1168        if let Some(username) = &self.username {
1169            // Username might be: username1@username2@ip2
1170            let username = urlencoding::encode(username);
1171            result.push_str(&username);
1172            result.push('@');
1173        }
1174        result.push_str(&self.host);
1175        if let Some(port) = self.port {
1176            result.push(':');
1177            result.push_str(&port.to_string());
1178        }
1179        result
1180    }
1181
1182    pub fn additional_args_for_scp(&self) -> Vec<String> {
1183        self.args.iter().flatten().cloned().collect::<Vec<String>>()
1184    }
1185
1186    pub fn additional_args(&self) -> Vec<String> {
1187        let mut args = self.additional_args_for_scp();
1188
1189        if let Some(forwards) = &self.port_forwards {
1190            args.extend(forwards.iter().map(|pf| {
1191                let local_host = match &pf.local_host {
1192                    Some(host) => host,
1193                    None => "localhost",
1194                };
1195                let remote_host = match &pf.remote_host {
1196                    Some(host) => host,
1197                    None => "localhost",
1198                };
1199
1200                format!(
1201                    "-L{}:{}:{}:{}",
1202                    local_host, pf.local_port, remote_host, pf.remote_port
1203                )
1204            }));
1205        }
1206
1207        args
1208    }
1209
1210    fn scp_url(&self) -> String {
1211        if let Some(username) = &self.username {
1212            format!("{}@{}", username, self.host)
1213        } else {
1214            self.host.clone()
1215        }
1216    }
1217
1218    pub fn connection_string(&self) -> String {
1219        let host = if let Some(username) = &self.username {
1220            format!("{}@{}", username, self.host)
1221        } else {
1222            self.host.clone()
1223        };
1224        if let Some(port) = &self.port {
1225            format!("{}:{}", host, port)
1226        } else {
1227            host
1228        }
1229    }
1230}
1231
1232fn build_command(
1233    input_program: Option<String>,
1234    input_args: &[String],
1235    input_env: &HashMap<String, String>,
1236    working_dir: Option<String>,
1237    port_forward: Option<(u16, String, u16)>,
1238    ssh_env: HashMap<String, String>,
1239    ssh_path_style: PathStyle,
1240    ssh_shell: &str,
1241    ssh_args: Vec<String>,
1242) -> Result<CommandTemplate> {
1243    use std::fmt::Write as _;
1244
1245    let shell_kind = ShellKind::new(ssh_shell, false);
1246    let mut exec = String::new();
1247    if let Some(working_dir) = working_dir {
1248        let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1249
1250        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
1251        // replace with with something that works
1252        const TILDE_PREFIX: &'static str = "~/";
1253        if working_dir.starts_with(TILDE_PREFIX) {
1254            let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
1255            write!(exec, "cd \"$HOME/{working_dir}\" && ",)?;
1256        } else {
1257            write!(exec, "cd \"{working_dir}\" && ",)?;
1258        }
1259    } else {
1260        write!(exec, "cd && ")?;
1261    };
1262    write!(exec, "exec env ")?;
1263
1264    for (k, v) in input_env.iter() {
1265        write!(
1266            exec,
1267            "{}={} ",
1268            k,
1269            shell_kind.try_quote(v).context("shell quoting")?
1270        )?;
1271    }
1272
1273    if let Some(input_program) = input_program {
1274        write!(
1275            exec,
1276            "{}",
1277            shell_kind
1278                .try_quote(&input_program)
1279                .context("shell quoting")?
1280        )?;
1281        for arg in input_args {
1282            let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
1283            write!(exec, " {}", &arg)?;
1284        }
1285    } else {
1286        write!(exec, "{ssh_shell} -l")?;
1287    };
1288
1289    let mut args = Vec::new();
1290    args.extend(ssh_args);
1291
1292    if let Some((local_port, host, remote_port)) = port_forward {
1293        args.push("-L".into());
1294        args.push(format!("{local_port}:{host}:{remote_port}"));
1295    }
1296
1297    args.push("-t".into());
1298    args.push(exec);
1299    Ok(CommandTemplate {
1300        program: "ssh".into(),
1301        args,
1302        env: ssh_env,
1303    })
1304}
1305
1306#[cfg(test)]
1307mod tests {
1308    use super::*;
1309
1310    #[test]
1311    fn test_build_command() -> Result<()> {
1312        let mut input_env = HashMap::default();
1313        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1314        let mut env = HashMap::default();
1315        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1316
1317        let command = build_command(
1318            Some("remote_program".to_string()),
1319            &["arg1".to_string(), "arg2".to_string()],
1320            &input_env,
1321            Some("~/work".to_string()),
1322            None,
1323            env.clone(),
1324            PathStyle::Posix,
1325            "/bin/fish",
1326            vec!["-p".to_string(), "2222".to_string()],
1327        )?;
1328
1329        assert_eq!(command.program, "ssh");
1330        assert_eq!(
1331            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1332            [
1333                "-p",
1334                "2222",
1335                "-t",
1336                "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1337            ]
1338        );
1339        assert_eq!(command.env, env);
1340
1341        let mut input_env = HashMap::default();
1342        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1343        let mut env = HashMap::default();
1344        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1345
1346        let command = build_command(
1347            None,
1348            &["arg1".to_string(), "arg2".to_string()],
1349            &input_env,
1350            None,
1351            Some((1, "foo".to_owned(), 2)),
1352            env.clone(),
1353            PathStyle::Posix,
1354            "/bin/fish",
1355            vec!["-p".to_string(), "2222".to_string()],
1356        )?;
1357
1358        assert_eq!(command.program, "ssh");
1359        assert_eq!(
1360            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1361            [
1362                "-p",
1363                "2222",
1364                "-L",
1365                "1:foo:2",
1366                "-t",
1367                "cd && exec env INPUT_VA=val /bin/fish -l"
1368            ]
1369        );
1370        assert_eq!(command.env, env);
1371
1372        Ok(())
1373    }
1374
1375    #[test]
1376    fn scp_args_exclude_port_forward_flags() {
1377        let options = SshConnectionOptions {
1378            host: "example.com".into(),
1379            args: Some(vec![
1380                "-p".to_string(),
1381                "2222".to_string(),
1382                "-o".to_string(),
1383                "StrictHostKeyChecking=no".to_string(),
1384            ]),
1385            port_forwards: Some(vec![SshPortForwardOption {
1386                local_host: Some("127.0.0.1".to_string()),
1387                local_port: 8080,
1388                remote_host: Some("127.0.0.1".to_string()),
1389                remote_port: 80,
1390            }]),
1391            ..Default::default()
1392        };
1393
1394        let ssh_args = options.additional_args();
1395        assert!(
1396            ssh_args.iter().any(|arg| arg.starts_with("-L")),
1397            "expected ssh args to include port-forward: {ssh_args:?}"
1398        );
1399
1400        let scp_args = options.additional_args_for_scp();
1401        assert_eq!(
1402            scp_args,
1403            vec![
1404                "-p".to_string(),
1405                "2222".to_string(),
1406                "-o".to_string(),
1407                "StrictHostKeyChecking=no".to_string()
1408            ]
1409        );
1410        assert!(
1411            scp_args.iter().all(|arg| !arg.starts_with("-L")),
1412            "scp args should not contain port forward flags: {scp_args:?}"
1413        );
1414    }
1415}