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
 206macro_rules! shell_script {
 207    ($fmt:expr, $($name:ident = $arg:expr),+ $(,)?) => {{
 208        format!(
 209            $fmt,
 210            $(
 211                $name = shlex::try_quote($arg).unwrap()
 212            ),+
 213        )
 214    }};
 215}
 216
 217#[async_trait(?Send)]
 218impl RemoteConnection for SshRemoteConnection {
 219    async fn kill(&self) -> Result<()> {
 220        let Some(mut process) = self.master_process.lock().take() else {
 221            return Ok(());
 222        };
 223        process.as_mut().kill().ok();
 224        process.as_mut().status().await?;
 225        Ok(())
 226    }
 227
 228    fn has_been_killed(&self) -> bool {
 229        self.master_process.lock().is_none()
 230    }
 231
 232    fn connection_options(&self) -> RemoteConnectionOptions {
 233        RemoteConnectionOptions::Ssh(self.socket.connection_options.clone())
 234    }
 235
 236    fn shell(&self) -> String {
 237        self.ssh_shell.clone()
 238    }
 239
 240    fn default_system_shell(&self) -> String {
 241        self.ssh_default_system_shell.clone()
 242    }
 243
 244    fn build_command(
 245        &self,
 246        input_program: Option<String>,
 247        input_args: &[String],
 248        input_env: &HashMap<String, String>,
 249        working_dir: Option<String>,
 250        port_forward: Option<(u16, String, u16)>,
 251    ) -> Result<CommandTemplate> {
 252        let Self {
 253            ssh_path_style,
 254            socket,
 255            ssh_shell,
 256            ..
 257        } = self;
 258        let env = socket.envs.clone();
 259        build_command(
 260            input_program,
 261            input_args,
 262            input_env,
 263            working_dir,
 264            port_forward,
 265            env,
 266            *ssh_path_style,
 267            ssh_shell,
 268            socket.ssh_args(),
 269        )
 270    }
 271
 272    fn build_forward_ports_command(
 273        &self,
 274        forwards: Vec<(u16, String, u16)>,
 275    ) -> Result<CommandTemplate> {
 276        let Self { socket, .. } = self;
 277        let mut args = socket.ssh_args();
 278        args.push("-N".into());
 279        for (local_port, host, remote_port) in forwards {
 280            args.push("-L".into());
 281            args.push(format!("{local_port}:{host}:{remote_port}"));
 282        }
 283        Ok(CommandTemplate {
 284            program: "ssh".into(),
 285            args,
 286            env: Default::default(),
 287        })
 288    }
 289
 290    fn upload_directory(
 291        &self,
 292        src_path: PathBuf,
 293        dest_path: RemotePathBuf,
 294        cx: &App,
 295    ) -> Task<Result<()>> {
 296        let dest_path_str = dest_path.to_string();
 297        let src_path_display = src_path.display().to_string();
 298
 299        let mut sftp_command = self.build_sftp_command();
 300        let mut scp_command =
 301            self.build_scp_command(&src_path, &dest_path_str, Some(&["-C", "-r"]));
 302
 303        cx.background_spawn(async move {
 304            if Self::is_sftp_available().await {
 305                log::debug!("using SFTP for directory upload");
 306                let mut child = sftp_command.spawn()?;
 307                if let Some(mut stdin) = child.stdin.take() {
 308                    use futures::AsyncWriteExt;
 309                    let sftp_batch = format!("put -r {} {}\n", src_path.display(), dest_path_str);
 310                    stdin.write_all(sftp_batch.as_bytes()).await?;
 311                    drop(stdin);
 312                }
 313
 314                let output = child.output().await?;
 315                anyhow::ensure!(
 316                    output.status.success(),
 317                    "failed to upload directory via SFTP {} -> {}: {}",
 318                    src_path_display,
 319                    dest_path_str,
 320                    String::from_utf8_lossy(&output.stderr)
 321                );
 322
 323                return Ok(());
 324            }
 325
 326            log::debug!("using SCP for directory upload");
 327            let output = scp_command.output().await?;
 328
 329            anyhow::ensure!(
 330                output.status.success(),
 331                "failed to upload directory via SCP {} -> {}: {}",
 332                src_path_display,
 333                dest_path_str,
 334                String::from_utf8_lossy(&output.stderr)
 335            );
 336
 337            Ok(())
 338        })
 339    }
 340
 341    fn start_proxy(
 342        &self,
 343        unique_identifier: String,
 344        reconnect: bool,
 345        incoming_tx: UnboundedSender<Envelope>,
 346        outgoing_rx: UnboundedReceiver<Envelope>,
 347        connection_activity_tx: Sender<()>,
 348        delegate: Arc<dyn RemoteClientDelegate>,
 349        cx: &mut AsyncApp,
 350    ) -> Task<Result<i32>> {
 351        delegate.set_status(Some("Starting proxy"), cx);
 352
 353        let Some(remote_binary_path) = self.remote_binary_path.clone() else {
 354            return Task::ready(Err(anyhow!("Remote binary path not set")));
 355        };
 356
 357        let mut proxy_args = vec![];
 358        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
 359            if let Some(value) = std::env::var(env_var).ok() {
 360                proxy_args.push(format!("{}='{}'", env_var, value));
 361            }
 362        }
 363        proxy_args.push(remote_binary_path.display(self.path_style()).into_owned());
 364        proxy_args.push("proxy".to_owned());
 365        proxy_args.push("--identifier".to_owned());
 366        proxy_args.push(unique_identifier);
 367
 368        if reconnect {
 369            proxy_args.push("--reconnect".to_owned());
 370        }
 371
 372        let ssh_proxy_process = match self
 373            .socket
 374            .ssh_command("env", &proxy_args)
 375            // IMPORTANT: we kill this process when we drop the task that uses it.
 376            .kill_on_drop(true)
 377            .spawn()
 378        {
 379            Ok(process) => process,
 380            Err(error) => {
 381                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
 382            }
 383        };
 384
 385        super::handle_rpc_messages_over_child_process_stdio(
 386            ssh_proxy_process,
 387            incoming_tx,
 388            outgoing_rx,
 389            connection_activity_tx,
 390            cx,
 391        )
 392    }
 393
 394    fn path_style(&self) -> PathStyle {
 395        self.ssh_path_style
 396    }
 397}
 398
 399impl SshRemoteConnection {
 400    pub(crate) async fn new(
 401        connection_options: SshConnectionOptions,
 402        delegate: Arc<dyn RemoteClientDelegate>,
 403        cx: &mut AsyncApp,
 404    ) -> Result<Self> {
 405        use askpass::AskPassResult;
 406
 407        let url = connection_options.ssh_url();
 408
 409        let temp_dir = tempfile::Builder::new()
 410            .prefix("zed-ssh-session")
 411            .tempdir()?;
 412        let askpass_delegate = askpass::AskPassDelegate::new(cx, {
 413            let delegate = delegate.clone();
 414            move |prompt, tx, cx| delegate.ask_password(prompt, tx, cx)
 415        });
 416
 417        let mut askpass =
 418            askpass::AskPassSession::new(cx.background_executor(), askpass_delegate).await?;
 419
 420        delegate.set_status(Some("Connecting"), cx);
 421
 422        // Start the master SSH process, which does not do anything except for establish
 423        // the connection and keep it open, allowing other ssh commands to reuse it
 424        // via a control socket.
 425        #[cfg(not(target_os = "windows"))]
 426        let socket_path = temp_dir.path().join("ssh.sock");
 427
 428        #[cfg(target_os = "windows")]
 429        let mut master_process = MasterProcess::new(
 430            askpass.script_path().as_ref(),
 431            connection_options.additional_args(),
 432            &url,
 433        )?;
 434        #[cfg(not(target_os = "windows"))]
 435        let mut master_process = MasterProcess::new(
 436            askpass.script_path().as_ref(),
 437            connection_options.additional_args(),
 438            &socket_path,
 439            &url,
 440        )?;
 441
 442        let result = select_biased! {
 443            result = askpass.run().fuse() => {
 444                match result {
 445                    AskPassResult::CancelledByUser => {
 446                        master_process.as_mut().kill().ok();
 447                        anyhow::bail!("SSH connection canceled")
 448                    }
 449                    AskPassResult::Timedout => {
 450                        anyhow::bail!("connecting to host timed out")
 451                    }
 452                }
 453            }
 454            _ = master_process.wait_connected().fuse() => {
 455                anyhow::Ok(())
 456            }
 457        };
 458
 459        if let Err(e) = result {
 460            return Err(e.context("Failed to connect to host"));
 461        }
 462
 463        if master_process.as_mut().try_status()?.is_some() {
 464            let mut output = Vec::new();
 465            output.clear();
 466            let mut stderr = master_process.as_mut().stderr.take().unwrap();
 467            stderr.read_to_end(&mut output).await?;
 468
 469            let error_message = format!(
 470                "failed to connect: {}",
 471                String::from_utf8_lossy(&output).trim()
 472            );
 473            anyhow::bail!(error_message);
 474        }
 475
 476        #[cfg(not(target_os = "windows"))]
 477        let socket = SshSocket::new(connection_options, socket_path).await?;
 478        #[cfg(target_os = "windows")]
 479        let socket = SshSocket::new(
 480            connection_options,
 481            askpass
 482                .get_password()
 483                .or_else(|| askpass::EncryptedPassword::try_from("").ok())
 484                .context("Failed to fetch askpass password")?,
 485            cx.background_executor().clone(),
 486        )
 487        .await?;
 488        drop(askpass);
 489
 490        let ssh_shell = socket.shell().await;
 491        let ssh_platform = socket.platform(ShellKind::new(&ssh_shell, false)).await?;
 492        let ssh_path_style = match ssh_platform.os {
 493            "windows" => PathStyle::Windows,
 494            _ => PathStyle::Posix,
 495        };
 496        let ssh_default_system_shell = String::from("/bin/sh");
 497
 498        let mut this = Self {
 499            socket,
 500            master_process: Mutex::new(Some(master_process)),
 501            _temp_dir: temp_dir,
 502            remote_binary_path: None,
 503            ssh_path_style,
 504            ssh_platform,
 505            ssh_shell,
 506            ssh_default_system_shell,
 507        };
 508
 509        let (release_channel, version, commit) = cx.update(|cx| {
 510            (
 511                ReleaseChannel::global(cx),
 512                AppVersion::global(cx),
 513                AppCommitSha::try_global(cx),
 514            )
 515        })?;
 516        this.remote_binary_path = Some(
 517            this.ensure_server_binary(&delegate, release_channel, version, commit, cx)
 518                .await?,
 519        );
 520
 521        Ok(this)
 522    }
 523
 524    async fn ensure_server_binary(
 525        &self,
 526        delegate: &Arc<dyn RemoteClientDelegate>,
 527        release_channel: ReleaseChannel,
 528        version: SemanticVersion,
 529        commit: Option<AppCommitSha>,
 530        cx: &mut AsyncApp,
 531    ) -> Result<Arc<RelPath>> {
 532        let version_str = match release_channel {
 533            ReleaseChannel::Nightly => {
 534                let commit = commit.map(|s| s.full()).unwrap_or_default();
 535                format!("{}-{}", version, commit)
 536            }
 537            ReleaseChannel::Dev => "build".to_string(),
 538            _ => version.to_string(),
 539        };
 540        let binary_name = format!(
 541            "zed-remote-server-{}-{}",
 542            release_channel.dev_name(),
 543            version_str
 544        );
 545        let dst_path =
 546            paths::remote_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
 547
 548        #[cfg(debug_assertions)]
 549        if let Some(remote_server_path) =
 550            super::build_remote_server_from_source(&self.ssh_platform, delegate.as_ref(), cx)
 551                .await?
 552        {
 553            let tmp_path = paths::remote_server_dir_relative().join(
 554                RelPath::unix(&format!(
 555                    "download-{}-{}",
 556                    std::process::id(),
 557                    remote_server_path.file_name().unwrap().to_string_lossy()
 558                ))
 559                .unwrap(),
 560            );
 561            self.upload_local_server_binary(&remote_server_path, &tmp_path, delegate, cx)
 562                .await?;
 563            self.extract_server_binary(&dst_path, &tmp_path, delegate, cx)
 564                .await?;
 565            return Ok(dst_path);
 566        }
 567
 568        if self
 569            .socket
 570            .run_command(&dst_path.display(self.path_style()), &["version"])
 571            .await
 572            .is_ok()
 573        {
 574            return Ok(dst_path);
 575        }
 576
 577        let wanted_version = cx.update(|cx| match release_channel {
 578            ReleaseChannel::Nightly => Ok(None),
 579            ReleaseChannel::Dev => {
 580                anyhow::bail!(
 581                    "ZED_BUILD_REMOTE_SERVER is not set and no remote server exists at ({:?})",
 582                    dst_path
 583                )
 584            }
 585            _ => Ok(Some(AppVersion::global(cx))),
 586        })??;
 587
 588        let tmp_path_gz = remote_server_dir_relative().join(
 589            RelPath::unix(&format!(
 590                "{}-download-{}.gz",
 591                binary_name,
 592                std::process::id()
 593            ))
 594            .unwrap(),
 595        );
 596        if !self.socket.connection_options.upload_binary_over_ssh
 597            && let Some((url, body)) = delegate
 598                .get_download_params(self.ssh_platform, release_channel, wanted_version, cx)
 599                .await?
 600        {
 601            match self
 602                .download_binary_on_server(&url, &body, &tmp_path_gz, delegate, cx)
 603                .await
 604            {
 605                Ok(_) => {
 606                    self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
 607                        .await?;
 608                    return Ok(dst_path);
 609                }
 610                Err(e) => {
 611                    log::error!(
 612                        "Failed to download binary on server, attempting to upload server: {}",
 613                        e
 614                    )
 615                }
 616            }
 617        }
 618
 619        let src_path = delegate
 620            .download_server_binary_locally(self.ssh_platform, release_channel, wanted_version, cx)
 621            .await?;
 622        self.upload_local_server_binary(&src_path, &tmp_path_gz, delegate, cx)
 623            .await?;
 624        self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
 625            .await?;
 626        Ok(dst_path)
 627    }
 628
 629    async fn download_binary_on_server(
 630        &self,
 631        url: &str,
 632        body: &str,
 633        tmp_path_gz: &RelPath,
 634        delegate: &Arc<dyn RemoteClientDelegate>,
 635        cx: &mut AsyncApp,
 636    ) -> Result<()> {
 637        if let Some(parent) = tmp_path_gz.parent() {
 638            self.socket
 639                .run_command("mkdir", &["-p", parent.display(self.path_style()).as_ref()])
 640                .await?;
 641        }
 642
 643        delegate.set_status(Some("Downloading remote development server on host"), cx);
 644
 645        match self
 646            .socket
 647            .run_command(
 648                "curl",
 649                &[
 650                    "-f",
 651                    "-L",
 652                    "-X",
 653                    "GET",
 654                    "-H",
 655                    "Content-Type: application/json",
 656                    "-d",
 657                    body,
 658                    url,
 659                    "-o",
 660                    &tmp_path_gz.display(self.path_style()),
 661                ],
 662            )
 663            .await
 664        {
 665            Ok(_) => {}
 666            Err(e) => {
 667                if self.socket.run_command("which", &["curl"]).await.is_ok() {
 668                    return Err(e);
 669                }
 670
 671                match self
 672                    .socket
 673                    .run_command(
 674                        "wget",
 675                        &[
 676                            "--header=Content-Type: application/json",
 677                            "--body-data",
 678                            body,
 679                            url,
 680                            "-O",
 681                            &tmp_path_gz.display(self.path_style()),
 682                        ],
 683                    )
 684                    .await
 685                {
 686                    Ok(_) => {}
 687                    Err(e) => {
 688                        if self.socket.run_command("which", &["wget"]).await.is_ok() {
 689                            return Err(e);
 690                        } else {
 691                            anyhow::bail!("Neither curl nor wget is available");
 692                        }
 693                    }
 694                }
 695            }
 696        }
 697
 698        Ok(())
 699    }
 700
 701    async fn upload_local_server_binary(
 702        &self,
 703        src_path: &Path,
 704        tmp_path_gz: &RelPath,
 705        delegate: &Arc<dyn RemoteClientDelegate>,
 706        cx: &mut AsyncApp,
 707    ) -> Result<()> {
 708        if let Some(parent) = tmp_path_gz.parent() {
 709            self.socket
 710                .run_command("mkdir", &["-p", parent.display(self.path_style()).as_ref()])
 711                .await?;
 712        }
 713
 714        let src_stat = fs::metadata(&src_path).await?;
 715        let size = src_stat.len();
 716
 717        let t0 = Instant::now();
 718        delegate.set_status(Some("Uploading remote development server"), cx);
 719        log::info!(
 720            "uploading remote development server to {:?} ({}kb)",
 721            tmp_path_gz,
 722            size / 1024
 723        );
 724        self.upload_file(src_path, tmp_path_gz)
 725            .await
 726            .context("failed to upload server binary")?;
 727        log::info!("uploaded remote development server in {:?}", t0.elapsed());
 728        Ok(())
 729    }
 730
 731    async fn extract_server_binary(
 732        &self,
 733        dst_path: &RelPath,
 734        tmp_path: &RelPath,
 735        delegate: &Arc<dyn RemoteClientDelegate>,
 736        cx: &mut AsyncApp,
 737    ) -> Result<()> {
 738        delegate.set_status(Some("Extracting remote development server"), cx);
 739        let server_mode = 0o755;
 740
 741        let orig_tmp_path = tmp_path.display(self.path_style());
 742        let script = if let Some(tmp_path) = orig_tmp_path.strip_suffix(".gz") {
 743            shell_script!(
 744                "gunzip -f {orig_tmp_path} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
 745                server_mode = &format!("{:o}", server_mode),
 746                dst_path = &dst_path.display(self.path_style()),
 747            )
 748        } else {
 749            shell_script!(
 750                "chmod {server_mode} {orig_tmp_path} && mv {orig_tmp_path} {dst_path}",
 751                server_mode = &format!("{:o}", server_mode),
 752                dst_path = &dst_path.display(self.path_style())
 753            )
 754        };
 755        self.socket.run_command("sh", &["-c", &script]).await?;
 756        Ok(())
 757    }
 758
 759    fn build_scp_command(
 760        &self,
 761        src_path: &Path,
 762        dest_path_str: &str,
 763        args: Option<&[&str]>,
 764    ) -> process::Command {
 765        let mut command = util::command::new_smol_command("scp");
 766        self.socket.ssh_options(&mut command, false).args(
 767            self.socket
 768                .connection_options
 769                .port
 770                .map(|port| vec!["-P".to_string(), port.to_string()])
 771                .unwrap_or_default(),
 772        );
 773        if let Some(args) = args {
 774            command.args(args);
 775        }
 776        command.arg(src_path).arg(format!(
 777            "{}:{}",
 778            self.socket.connection_options.scp_url(),
 779            dest_path_str
 780        ));
 781        command
 782    }
 783
 784    fn build_sftp_command(&self) -> process::Command {
 785        let mut command = util::command::new_smol_command("sftp");
 786        self.socket.ssh_options(&mut command, false).args(
 787            self.socket
 788                .connection_options
 789                .port
 790                .map(|port| vec!["-P".to_string(), port.to_string()])
 791                .unwrap_or_default(),
 792        );
 793        command.arg("-b").arg("-");
 794        command.arg(self.socket.connection_options.scp_url());
 795        command.stdin(Stdio::piped());
 796        command
 797    }
 798
 799    async fn upload_file(&self, src_path: &Path, dest_path: &RelPath) -> Result<()> {
 800        log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
 801
 802        let dest_path_str = dest_path.display(self.path_style());
 803
 804        if Self::is_sftp_available().await {
 805            log::debug!("using SFTP for file upload");
 806            let mut command = self.build_sftp_command();
 807            let sftp_batch = format!("put {} {}\n", src_path.display(), dest_path_str);
 808
 809            let mut child = command.spawn()?;
 810            if let Some(mut stdin) = child.stdin.take() {
 811                use futures::AsyncWriteExt;
 812                stdin.write_all(sftp_batch.as_bytes()).await?;
 813                drop(stdin);
 814            }
 815
 816            let output = child.output().await?;
 817            anyhow::ensure!(
 818                output.status.success(),
 819                "failed to upload file via SFTP {} -> {}: {}",
 820                src_path.display(),
 821                dest_path_str,
 822                String::from_utf8_lossy(&output.stderr)
 823            );
 824
 825            Ok(())
 826        } else {
 827            log::debug!("using SCP for file upload");
 828            let mut command = self.build_scp_command(src_path, &dest_path_str, None);
 829            let output = command.output().await?;
 830
 831            anyhow::ensure!(
 832                output.status.success(),
 833                "failed to upload file via SCP {} -> {}: {}",
 834                src_path.display(),
 835                dest_path_str,
 836                String::from_utf8_lossy(&output.stderr)
 837            );
 838
 839            Ok(())
 840        }
 841    }
 842
 843    async fn is_sftp_available() -> bool {
 844        which::which("sftp").is_ok()
 845    }
 846}
 847
 848impl SshSocket {
 849    #[cfg(not(target_os = "windows"))]
 850    async fn new(options: SshConnectionOptions, socket_path: PathBuf) -> Result<Self> {
 851        Ok(Self {
 852            connection_options: options,
 853            envs: HashMap::default(),
 854            socket_path,
 855        })
 856    }
 857
 858    #[cfg(target_os = "windows")]
 859    async fn new(
 860        options: SshConnectionOptions,
 861        password: askpass::EncryptedPassword,
 862        executor: gpui::BackgroundExecutor,
 863    ) -> Result<Self> {
 864        let mut envs = HashMap::default();
 865        let get_password =
 866            move |_| Task::ready(std::ops::ControlFlow::Continue(Ok(password.clone())));
 867
 868        let _proxy = askpass::PasswordProxy::new(get_password, executor).await?;
 869        envs.insert("SSH_ASKPASS_REQUIRE".into(), "force".into());
 870        envs.insert(
 871            "SSH_ASKPASS".into(),
 872            _proxy.script_path().as_ref().display().to_string(),
 873        );
 874
 875        Ok(Self {
 876            connection_options: options,
 877            envs,
 878            _proxy,
 879        })
 880    }
 881
 882    // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
 883    // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
 884    // and passes -l as an argument to sh, not to ls.
 885    // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
 886    // into a machine. You must use `cd` to get back to $HOME.
 887    // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
 888    fn ssh_command(&self, program: &str, args: &[impl AsRef<str>]) -> process::Command {
 889        let mut command = util::command::new_smol_command("ssh");
 890        let mut to_run = shlex::try_quote(program).unwrap().into_owned();
 891        for arg in args {
 892            // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
 893            debug_assert!(
 894                !arg.as_ref().contains('\n'),
 895                "multiline arguments do not work in all shells"
 896            );
 897            to_run.push(' ');
 898            to_run.push_str(&shlex::try_quote(arg.as_ref()).unwrap());
 899        }
 900        let to_run = format!("cd; {to_run}");
 901        self.ssh_options(&mut command, true)
 902            .arg(self.connection_options.ssh_url())
 903            .arg("-T")
 904            .arg(to_run);
 905        log::debug!("ssh {:?}", command);
 906        command
 907    }
 908
 909    async fn run_command(&self, program: &str, args: &[&str]) -> Result<String> {
 910        let output = self.ssh_command(program, args).output().await?;
 911        anyhow::ensure!(
 912            output.status.success(),
 913            "failed to run command: {}",
 914            String::from_utf8_lossy(&output.stderr)
 915        );
 916        Ok(String::from_utf8_lossy(&output.stdout).to_string())
 917    }
 918
 919    #[cfg(not(target_os = "windows"))]
 920    fn ssh_options<'a>(
 921        &self,
 922        command: &'a mut process::Command,
 923        include_port_forwards: bool,
 924    ) -> &'a mut process::Command {
 925        let args = if include_port_forwards {
 926            self.connection_options.additional_args()
 927        } else {
 928            self.connection_options.additional_args_for_scp()
 929        };
 930
 931        command
 932            .stdin(Stdio::piped())
 933            .stdout(Stdio::piped())
 934            .stderr(Stdio::piped())
 935            .args(args)
 936            .args(["-o", "ControlMaster=no", "-o"])
 937            .arg(format!("ControlPath={}", self.socket_path.display()))
 938    }
 939
 940    #[cfg(target_os = "windows")]
 941    fn ssh_options<'a>(
 942        &self,
 943        command: &'a mut process::Command,
 944        include_port_forwards: bool,
 945    ) -> &'a mut process::Command {
 946        let args = if include_port_forwards {
 947            self.connection_options.additional_args()
 948        } else {
 949            self.connection_options.additional_args_for_scp()
 950        };
 951
 952        command
 953            .stdin(Stdio::piped())
 954            .stdout(Stdio::piped())
 955            .stderr(Stdio::piped())
 956            .args(args)
 957            .envs(self.envs.clone())
 958    }
 959
 960    // On Windows, we need to use `SSH_ASKPASS` to provide the password to ssh.
 961    // On Linux, we use the `ControlPath` option to create a socket file that ssh can use to
 962    #[cfg(not(target_os = "windows"))]
 963    fn ssh_args(&self) -> Vec<String> {
 964        let mut arguments = self.connection_options.additional_args();
 965        arguments.extend(vec![
 966            "-o".to_string(),
 967            "ControlMaster=no".to_string(),
 968            "-o".to_string(),
 969            format!("ControlPath={}", self.socket_path.display()),
 970            self.connection_options.ssh_url(),
 971        ]);
 972        arguments
 973    }
 974
 975    #[cfg(target_os = "windows")]
 976    fn ssh_args(&self) -> Vec<String> {
 977        let mut arguments = self.connection_options.additional_args();
 978        arguments.push(self.connection_options.ssh_url());
 979        arguments
 980    }
 981
 982    async fn platform(&self, shell: ShellKind) -> Result<RemotePlatform> {
 983        let program = if shell == ShellKind::Nushell {
 984            "^uname"
 985        } else {
 986            "uname"
 987        };
 988        let uname = self.run_command(program, &["-sm"]).await?;
 989        let Some((os, arch)) = uname.split_once(" ") else {
 990            anyhow::bail!("unknown uname: {uname:?}")
 991        };
 992
 993        let os = match os.trim() {
 994            "Darwin" => "macos",
 995            "Linux" => "linux",
 996            _ => anyhow::bail!(
 997                "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
 998            ),
 999        };
1000        // exclude armv5,6,7 as they are 32-bit.
1001        let arch = if arch.starts_with("armv8")
1002            || arch.starts_with("armv9")
1003            || arch.starts_with("arm64")
1004            || arch.starts_with("aarch64")
1005        {
1006            "aarch64"
1007        } else if arch.starts_with("x86") {
1008            "x86_64"
1009        } else {
1010            anyhow::bail!(
1011                "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
1012            )
1013        };
1014
1015        Ok(RemotePlatform { os, arch })
1016    }
1017
1018    async fn shell(&self) -> String {
1019        match self.run_command("sh", &["-c", "echo $SHELL"]).await {
1020            Ok(shell) => shell.trim().to_owned(),
1021            Err(e) => {
1022                log::error!("Failed to get shell: {e}");
1023                "sh".to_owned()
1024            }
1025        }
1026    }
1027}
1028
1029fn parse_port_number(port_str: &str) -> Result<u16> {
1030    port_str
1031        .parse()
1032        .with_context(|| format!("parsing port number: {port_str}"))
1033}
1034
1035fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
1036    let parts: Vec<&str> = spec.split(':').collect();
1037
1038    match parts.len() {
1039        4 => {
1040            let local_port = parse_port_number(parts[1])?;
1041            let remote_port = parse_port_number(parts[3])?;
1042
1043            Ok(SshPortForwardOption {
1044                local_host: Some(parts[0].to_string()),
1045                local_port,
1046                remote_host: Some(parts[2].to_string()),
1047                remote_port,
1048            })
1049        }
1050        3 => {
1051            let local_port = parse_port_number(parts[0])?;
1052            let remote_port = parse_port_number(parts[2])?;
1053
1054            Ok(SshPortForwardOption {
1055                local_host: None,
1056                local_port,
1057                remote_host: Some(parts[1].to_string()),
1058                remote_port,
1059            })
1060        }
1061        _ => anyhow::bail!("Invalid port forward format"),
1062    }
1063}
1064
1065impl SshConnectionOptions {
1066    pub fn parse_command_line(input: &str) -> Result<Self> {
1067        let input = input.trim_start_matches("ssh ");
1068        let mut hostname: Option<String> = None;
1069        let mut username: Option<String> = None;
1070        let mut port: Option<u16> = None;
1071        let mut args = Vec::new();
1072        let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
1073
1074        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
1075        const ALLOWED_OPTS: &[&str] = &[
1076            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
1077        ];
1078        const ALLOWED_ARGS: &[&str] = &[
1079            "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
1080            "-w",
1081        ];
1082
1083        let mut tokens = shlex::split(input).context("invalid input")?.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 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}\" && ",).unwrap();
1256        } else {
1257            write!(exec, "cd \"{working_dir}\" && ",).unwrap();
1258        }
1259    } else {
1260        write!(exec, "cd && ").unwrap();
1261    };
1262    write!(exec, "exec env ").unwrap();
1263
1264    for (k, v) in input_env.iter() {
1265        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
1266            write!(exec, "{}={} ", k, v).unwrap();
1267        }
1268    }
1269
1270    if let Some(input_program) = input_program {
1271        write!(exec, "{}", shlex::try_quote(&input_program).unwrap()).unwrap();
1272        for arg in input_args {
1273            let arg = shlex::try_quote(&arg)?;
1274            write!(exec, " {}", &arg).unwrap();
1275        }
1276    } else {
1277        write!(exec, "{ssh_shell} -l").unwrap();
1278    };
1279
1280    let mut args = Vec::new();
1281    args.extend(ssh_args);
1282
1283    if let Some((local_port, host, remote_port)) = port_forward {
1284        args.push("-L".into());
1285        args.push(format!("{local_port}:{host}:{remote_port}"));
1286    }
1287
1288    args.push("-t".into());
1289    args.push(exec);
1290    Ok(CommandTemplate {
1291        program: "ssh".into(),
1292        args,
1293        env: ssh_env,
1294    })
1295}
1296
1297#[cfg(test)]
1298mod tests {
1299    use super::*;
1300
1301    #[test]
1302    fn test_build_command() -> Result<()> {
1303        let mut input_env = HashMap::default();
1304        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1305        let mut env = HashMap::default();
1306        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1307
1308        let command = build_command(
1309            Some("remote_program".to_string()),
1310            &["arg1".to_string(), "arg2".to_string()],
1311            &input_env,
1312            Some("~/work".to_string()),
1313            None,
1314            env.clone(),
1315            PathStyle::Posix,
1316            "/bin/fish",
1317            vec!["-p".to_string(), "2222".to_string()],
1318        )?;
1319
1320        assert_eq!(command.program, "ssh");
1321        assert_eq!(
1322            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1323            [
1324                "-p",
1325                "2222",
1326                "-t",
1327                "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1328            ]
1329        );
1330        assert_eq!(command.env, env);
1331
1332        let mut input_env = HashMap::default();
1333        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1334        let mut env = HashMap::default();
1335        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1336
1337        let command = build_command(
1338            None,
1339            &["arg1".to_string(), "arg2".to_string()],
1340            &input_env,
1341            None,
1342            Some((1, "foo".to_owned(), 2)),
1343            env.clone(),
1344            PathStyle::Posix,
1345            "/bin/fish",
1346            vec!["-p".to_string(), "2222".to_string()],
1347        )?;
1348
1349        assert_eq!(command.program, "ssh");
1350        assert_eq!(
1351            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1352            [
1353                "-p",
1354                "2222",
1355                "-L",
1356                "1:foo:2",
1357                "-t",
1358                "cd && exec env INPUT_VA=val /bin/fish -l"
1359            ]
1360        );
1361        assert_eq!(command.env, env);
1362
1363        Ok(())
1364    }
1365
1366    #[test]
1367    fn scp_args_exclude_port_forward_flags() {
1368        let options = SshConnectionOptions {
1369            host: "example.com".into(),
1370            args: Some(vec![
1371                "-p".to_string(),
1372                "2222".to_string(),
1373                "-o".to_string(),
1374                "StrictHostKeyChecking=no".to_string(),
1375            ]),
1376            port_forwards: Some(vec![SshPortForwardOption {
1377                local_host: Some("127.0.0.1".to_string()),
1378                local_port: 8080,
1379                remote_host: Some("127.0.0.1".to_string()),
1380                remote_port: 80,
1381            }]),
1382            ..Default::default()
1383        };
1384
1385        let ssh_args = options.additional_args();
1386        assert!(
1387            ssh_args.iter().any(|arg| arg.starts_with("-L")),
1388            "expected ssh args to include port-forward: {ssh_args:?}"
1389        );
1390
1391        let scp_args = options.additional_args_for_scp();
1392        assert_eq!(
1393            scp_args,
1394            vec![
1395                "-p".to_string(),
1396                "2222".to_string(),
1397                "-o".to_string(),
1398                "StrictHostKeyChecking=no".to_string()
1399            ]
1400        );
1401        assert!(
1402            scp_args.iter().all(|arg| !arg.starts_with("-L")),
1403            "scp args should not contain port forward flags: {scp_args:?}"
1404        );
1405    }
1406}