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(
 508                    "sh",
 509                    &[
 510                        "-c",
 511                        &shell_script!(
 512                            "mkdir -p {parent}",
 513                            parent = parent.display(self.path_style()).as_ref()
 514                        ),
 515                    ],
 516                )
 517                .await?;
 518        }
 519
 520        delegate.set_status(Some("Downloading remote development server on host"), cx);
 521
 522        match self
 523            .socket
 524            .run_command(
 525                "curl",
 526                &[
 527                    "-f",
 528                    "-L",
 529                    "-X",
 530                    "GET",
 531                    "-H",
 532                    "Content-Type: application/json",
 533                    "-d",
 534                    body,
 535                    url,
 536                    "-o",
 537                    &tmp_path_gz.display(self.path_style()),
 538                ],
 539            )
 540            .await
 541        {
 542            Ok(_) => {}
 543            Err(e) => {
 544                if self.socket.run_command("which", &["curl"]).await.is_ok() {
 545                    return Err(e);
 546                }
 547
 548                match self
 549                    .socket
 550                    .run_command(
 551                        "wget",
 552                        &[
 553                            "--header=Content-Type: application/json",
 554                            "--body-data",
 555                            body,
 556                            url,
 557                            "-O",
 558                            &tmp_path_gz.display(self.path_style()),
 559                        ],
 560                    )
 561                    .await
 562                {
 563                    Ok(_) => {}
 564                    Err(e) => {
 565                        if self.socket.run_command("which", &["wget"]).await.is_ok() {
 566                            return Err(e);
 567                        } else {
 568                            anyhow::bail!("Neither curl nor wget is available");
 569                        }
 570                    }
 571                }
 572            }
 573        }
 574
 575        Ok(())
 576    }
 577
 578    async fn upload_local_server_binary(
 579        &self,
 580        src_path: &Path,
 581        tmp_path_gz: &RelPath,
 582        delegate: &Arc<dyn RemoteClientDelegate>,
 583        cx: &mut AsyncApp,
 584    ) -> Result<()> {
 585        if let Some(parent) = tmp_path_gz.parent() {
 586            self.socket
 587                .run_command(
 588                    "sh",
 589                    &[
 590                        "-c",
 591                        &shell_script!(
 592                            "mkdir -p {parent}",
 593                            parent = parent.display(self.path_style()).as_ref()
 594                        ),
 595                    ],
 596                )
 597                .await?;
 598        }
 599
 600        let src_stat = fs::metadata(&src_path).await?;
 601        let size = src_stat.len();
 602
 603        let t0 = Instant::now();
 604        delegate.set_status(Some("Uploading remote development server"), cx);
 605        log::info!(
 606            "uploading remote development server to {:?} ({}kb)",
 607            tmp_path_gz,
 608            size / 1024
 609        );
 610        self.upload_file(src_path, tmp_path_gz)
 611            .await
 612            .context("failed to upload server binary")?;
 613        log::info!("uploaded remote development server in {:?}", t0.elapsed());
 614        Ok(())
 615    }
 616
 617    async fn extract_server_binary(
 618        &self,
 619        dst_path: &RelPath,
 620        tmp_path: &RelPath,
 621        delegate: &Arc<dyn RemoteClientDelegate>,
 622        cx: &mut AsyncApp,
 623    ) -> Result<()> {
 624        delegate.set_status(Some("Extracting remote development server"), cx);
 625        let server_mode = 0o755;
 626
 627        let orig_tmp_path = tmp_path.display(self.path_style());
 628        let script = if let Some(tmp_path) = orig_tmp_path.strip_suffix(".gz") {
 629            shell_script!(
 630                "gunzip -f {orig_tmp_path} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
 631                server_mode = &format!("{:o}", server_mode),
 632                dst_path = &dst_path.display(self.path_style()),
 633            )
 634        } else {
 635            shell_script!(
 636                "chmod {server_mode} {orig_tmp_path} && mv {orig_tmp_path} {dst_path}",
 637                server_mode = &format!("{:o}", server_mode),
 638                dst_path = &dst_path.display(self.path_style())
 639            )
 640        };
 641        self.socket.run_command("sh", &["-c", &script]).await?;
 642        Ok(())
 643    }
 644
 645    async fn upload_file(&self, src_path: &Path, dest_path: &RelPath) -> Result<()> {
 646        log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
 647        let mut command = util::command::new_smol_command("scp");
 648        let output = self
 649            .socket
 650            .ssh_options(&mut command)
 651            .args(
 652                self.socket
 653                    .connection_options
 654                    .port
 655                    .map(|port| vec!["-P".to_string(), port.to_string()])
 656                    .unwrap_or_default(),
 657            )
 658            .arg(src_path)
 659            .arg(format!(
 660                "{}:{}",
 661                self.socket.connection_options.scp_url(),
 662                dest_path.display(self.path_style())
 663            ))
 664            .output()
 665            .await?;
 666
 667        anyhow::ensure!(
 668            output.status.success(),
 669            "failed to upload file {} -> {}: {}",
 670            src_path.display(),
 671            dest_path.display(self.path_style()),
 672            String::from_utf8_lossy(&output.stderr)
 673        );
 674        Ok(())
 675    }
 676}
 677
 678impl SshSocket {
 679    #[cfg(not(target_os = "windows"))]
 680    fn new(options: SshConnectionOptions, socket_path: PathBuf) -> Result<Self> {
 681        Ok(Self {
 682            connection_options: options,
 683            envs: HashMap::default(),
 684            socket_path,
 685        })
 686    }
 687
 688    #[cfg(target_os = "windows")]
 689    fn new(
 690        options: SshConnectionOptions,
 691        temp_dir: &TempDir,
 692        password: askpass::EncryptedPassword,
 693    ) -> Result<Self> {
 694        let askpass_script = temp_dir.path().join("askpass.bat");
 695        std::fs::write(&askpass_script, "@ECHO OFF\necho %ZED_SSH_ASKPASS%")?;
 696        let mut envs = HashMap::default();
 697        envs.insert("SSH_ASKPASS_REQUIRE".into(), "force".into());
 698        envs.insert("SSH_ASKPASS".into(), askpass_script.display().to_string());
 699
 700        Ok(Self {
 701            connection_options: options,
 702            envs,
 703            password,
 704        })
 705    }
 706
 707    // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
 708    // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
 709    // and passes -l as an argument to sh, not to ls.
 710    // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
 711    // into a machine. You must use `cd` to get back to $HOME.
 712    // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
 713    fn ssh_command(&self, program: &str, args: &[impl AsRef<str>]) -> process::Command {
 714        let mut command = util::command::new_smol_command("ssh");
 715        let mut to_run = shlex::try_quote(program).unwrap().into_owned();
 716        for arg in args {
 717            // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
 718            debug_assert!(
 719                !arg.as_ref().contains('\n'),
 720                "multiline arguments do not work in all shells"
 721            );
 722            to_run.push(' ');
 723            to_run.push_str(&shlex::try_quote(arg.as_ref()).unwrap());
 724        }
 725        let to_run = format!("cd; {to_run}");
 726        self.ssh_options(&mut command)
 727            .arg(self.connection_options.ssh_url())
 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("sh", &["-c", "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    write!(exec, "{ssh_shell} ").unwrap();
1067    if let Some(input_program) = input_program {
1068        let mut script = shlex::try_quote(&input_program)?.into_owned();
1069        for arg in input_args {
1070            let arg = shlex::try_quote(&arg)?;
1071            script.push_str(" ");
1072            script.push_str(&arg);
1073        }
1074        write!(exec, "-c {}", shlex::try_quote(&script).unwrap()).unwrap();
1075    } else {
1076        write!(exec, "-l").unwrap();
1077    };
1078
1079    let mut args = Vec::new();
1080    args.extend(ssh_args);
1081
1082    if let Some((local_port, host, remote_port)) = port_forward {
1083        args.push("-L".into());
1084        args.push(format!("{local_port}:{host}:{remote_port}"));
1085    }
1086
1087    args.push("-t".into());
1088    args.push(exec);
1089    Ok(CommandTemplate {
1090        program: "ssh".into(),
1091        args,
1092        env: ssh_env,
1093    })
1094}
1095
1096#[cfg(test)]
1097mod tests {
1098    use super::*;
1099
1100    #[test]
1101    fn test_build_command() -> Result<()> {
1102        let mut input_env = HashMap::default();
1103        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1104        let mut env = HashMap::default();
1105        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1106
1107        let command = build_command(
1108            Some("remote_program".to_string()),
1109            &["arg1".to_string(), "arg2".to_string()],
1110            &input_env,
1111            Some("~/work".to_string()),
1112            None,
1113            env.clone(),
1114            PathStyle::Posix,
1115            "/bin/fish",
1116            vec!["-p".to_string(), "2222".to_string()],
1117        )?;
1118
1119        assert_eq!(command.program, "ssh");
1120        assert_eq!(
1121            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1122            [
1123                "-p",
1124                "2222",
1125                "-t",
1126                "exec env -C \"$HOME/work\" INPUT_VA=val /bin/fish -c 'remote_program arg1 arg2'"
1127            ]
1128        );
1129        assert_eq!(command.env, env);
1130
1131        let mut input_env = HashMap::default();
1132        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1133        let mut env = HashMap::default();
1134        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1135
1136        let command = build_command(
1137            None,
1138            &["arg1".to_string(), "arg2".to_string()],
1139            &input_env,
1140            None,
1141            Some((1, "foo".to_owned(), 2)),
1142            env.clone(),
1143            PathStyle::Posix,
1144            "/bin/fish",
1145            vec!["-p".to_string(), "2222".to_string()],
1146        )?;
1147
1148        assert_eq!(command.program, "ssh");
1149        assert_eq!(
1150            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1151            [
1152                "-p",
1153                "2222",
1154                "-L",
1155                "1:foo:2",
1156                "-t",
1157                "exec env -C \"$HOME\" INPUT_VA=val /bin/fish -l"
1158            ]
1159        );
1160        assert_eq!(command.env, env);
1161
1162        Ok(())
1163    }
1164}