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