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