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
  73struct SshSocket {
  74    connection_options: SshConnectionOptions,
  75    #[cfg(not(target_os = "windows"))]
  76    socket_path: std::path::PathBuf,
  77    envs: HashMap<String, String>,
  78    #[cfg(target_os = "windows")]
  79    _proxy: askpass::PasswordProxy,
  80}
  81
  82macro_rules! shell_script {
  83    ($fmt:expr, $($name:ident = $arg:expr),+ $(,)?) => {{
  84        format!(
  85            $fmt,
  86            $(
  87                $name = shlex::try_quote($arg).unwrap()
  88            ),+
  89        )
  90    }};
  91}
  92
  93#[async_trait(?Send)]
  94impl RemoteConnection for SshRemoteConnection {
  95    async fn kill(&self) -> Result<()> {
  96        let Some(mut process) = self.master_process.lock().take() else {
  97            return Ok(());
  98        };
  99        process.kill().ok();
 100        process.status().await?;
 101        Ok(())
 102    }
 103
 104    fn has_been_killed(&self) -> bool {
 105        self.master_process.lock().is_none()
 106    }
 107
 108    fn connection_options(&self) -> RemoteConnectionOptions {
 109        RemoteConnectionOptions::Ssh(self.socket.connection_options.clone())
 110    }
 111
 112    fn shell(&self) -> String {
 113        self.ssh_shell.clone()
 114    }
 115
 116    fn default_system_shell(&self) -> String {
 117        self.ssh_default_system_shell.clone()
 118    }
 119
 120    fn build_command(
 121        &self,
 122        input_program: Option<String>,
 123        input_args: &[String],
 124        input_env: &HashMap<String, String>,
 125        working_dir: Option<String>,
 126        port_forward: Option<(u16, String, u16)>,
 127    ) -> Result<CommandTemplate> {
 128        let Self {
 129            ssh_path_style,
 130            socket,
 131            ssh_shell,
 132            ..
 133        } = self;
 134        let env = socket.envs.clone();
 135        build_command(
 136            input_program,
 137            input_args,
 138            input_env,
 139            working_dir,
 140            port_forward,
 141            env,
 142            *ssh_path_style,
 143            ssh_shell,
 144            socket.ssh_args(),
 145        )
 146    }
 147
 148    fn upload_directory(
 149        &self,
 150        src_path: PathBuf,
 151        dest_path: RemotePathBuf,
 152        cx: &App,
 153    ) -> Task<Result<()>> {
 154        let mut command = util::command::new_smol_command("scp");
 155        let output = self
 156            .socket
 157            .ssh_options(&mut command)
 158            .args(
 159                self.socket
 160                    .connection_options
 161                    .port
 162                    .map(|port| vec!["-P".to_string(), port.to_string()])
 163                    .unwrap_or_default(),
 164            )
 165            .arg("-C")
 166            .arg("-r")
 167            .arg(&src_path)
 168            .arg(format!(
 169                "{}:{}",
 170                self.socket.connection_options.scp_url(),
 171                dest_path
 172            ))
 173            .output();
 174
 175        cx.background_spawn(async move {
 176            let output = output.await?;
 177
 178            anyhow::ensure!(
 179                output.status.success(),
 180                "failed to upload directory {} -> {}: {}",
 181                src_path.display(),
 182                dest_path.to_string(),
 183                String::from_utf8_lossy(&output.stderr)
 184            );
 185
 186            Ok(())
 187        })
 188    }
 189
 190    fn start_proxy(
 191        &self,
 192        unique_identifier: String,
 193        reconnect: bool,
 194        incoming_tx: UnboundedSender<Envelope>,
 195        outgoing_rx: UnboundedReceiver<Envelope>,
 196        connection_activity_tx: Sender<()>,
 197        delegate: Arc<dyn RemoteClientDelegate>,
 198        cx: &mut AsyncApp,
 199    ) -> Task<Result<i32>> {
 200        delegate.set_status(Some("Starting proxy"), cx);
 201
 202        let Some(remote_binary_path) = self.remote_binary_path.clone() else {
 203            return Task::ready(Err(anyhow!("Remote binary path not set")));
 204        };
 205
 206        let mut proxy_args = vec![];
 207        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
 208            if let Some(value) = std::env::var(env_var).ok() {
 209                proxy_args.push(format!("{}='{}'", env_var, value));
 210            }
 211        }
 212        proxy_args.push(remote_binary_path.display(self.path_style()).into_owned());
 213        proxy_args.push("proxy".to_owned());
 214        proxy_args.push("--identifier".to_owned());
 215        proxy_args.push(unique_identifier);
 216
 217        if reconnect {
 218            proxy_args.push("--reconnect".to_owned());
 219        }
 220
 221        let ssh_proxy_process = match self
 222            .socket
 223            .ssh_command("env", &proxy_args)
 224            // IMPORTANT: we kill this process when we drop the task that uses it.
 225            .kill_on_drop(true)
 226            .spawn()
 227        {
 228            Ok(process) => process,
 229            Err(error) => {
 230                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
 231            }
 232        };
 233
 234        super::handle_rpc_messages_over_child_process_stdio(
 235            ssh_proxy_process,
 236            incoming_tx,
 237            outgoing_rx,
 238            connection_activity_tx,
 239            cx,
 240        )
 241    }
 242
 243    fn path_style(&self) -> PathStyle {
 244        self.ssh_path_style
 245    }
 246}
 247
 248impl SshRemoteConnection {
 249    pub(crate) async fn new(
 250        connection_options: SshConnectionOptions,
 251        delegate: Arc<dyn RemoteClientDelegate>,
 252        cx: &mut AsyncApp,
 253    ) -> Result<Self> {
 254        use askpass::AskPassResult;
 255
 256        delegate.set_status(Some("Connecting"), cx);
 257
 258        let url = connection_options.ssh_url();
 259
 260        let temp_dir = tempfile::Builder::new()
 261            .prefix("zed-ssh-session")
 262            .tempdir()?;
 263        let askpass_delegate = askpass::AskPassDelegate::new(cx, {
 264            let delegate = delegate.clone();
 265            move |prompt, tx, cx| delegate.ask_password(prompt, tx, cx)
 266        });
 267
 268        let mut askpass =
 269            askpass::AskPassSession::new(cx.background_executor(), askpass_delegate).await?;
 270
 271        // Start the master SSH process, which does not do anything except for establish
 272        // the connection and keep it open, allowing other ssh commands to reuse it
 273        // via a control socket.
 274        #[cfg(not(target_os = "windows"))]
 275        let socket_path = temp_dir.path().join("ssh.sock");
 276
 277        let mut master_process = {
 278            #[cfg(not(target_os = "windows"))]
 279            let args = [
 280                "-N",
 281                "-o",
 282                "ControlPersist=no",
 283                "-o",
 284                "ControlMaster=yes",
 285                "-o",
 286            ];
 287            // On Windows, `ControlMaster` and `ControlPath` are not supported:
 288            // https://github.com/PowerShell/Win32-OpenSSH/issues/405
 289            // https://github.com/PowerShell/Win32-OpenSSH/wiki/Project-Scope
 290            #[cfg(target_os = "windows")]
 291            let args = ["-N"];
 292            let mut master_process = util::command::new_smol_command("ssh");
 293            master_process
 294                .kill_on_drop(true)
 295                .stdin(Stdio::null())
 296                .stdout(Stdio::piped())
 297                .stderr(Stdio::piped())
 298                .env("SSH_ASKPASS_REQUIRE", "force")
 299                .env("SSH_ASKPASS", askpass.script_path())
 300                .args(connection_options.additional_args())
 301                .args(args);
 302            #[cfg(not(target_os = "windows"))]
 303            master_process.arg(format!("ControlPath={}", socket_path.display()));
 304            master_process.arg(&url).spawn()?
 305        };
 306        // Wait for this ssh process to close its stdout, indicating that authentication
 307        // has completed.
 308        let mut stdout = master_process.stdout.take().unwrap();
 309        let mut output = Vec::new();
 310
 311        let result = select_biased! {
 312            result = askpass.run().fuse() => {
 313                match result {
 314                    AskPassResult::CancelledByUser => {
 315                        master_process.kill().ok();
 316                        anyhow::bail!("SSH connection canceled")
 317                    }
 318                    AskPassResult::Timedout => {
 319                        anyhow::bail!("connecting to host timed out")
 320                    }
 321                }
 322            }
 323            _ = stdout.read_to_end(&mut output).fuse() => {
 324                anyhow::Ok(())
 325            }
 326        };
 327
 328        if let Err(e) = result {
 329            return Err(e.context("Failed to connect to host"));
 330        }
 331
 332        if master_process.try_status()?.is_some() {
 333            output.clear();
 334            let mut stderr = master_process.stderr.take().unwrap();
 335            stderr.read_to_end(&mut output).await?;
 336
 337            let error_message = format!(
 338                "failed to connect: {}",
 339                String::from_utf8_lossy(&output).trim()
 340            );
 341            anyhow::bail!(error_message);
 342        }
 343
 344        #[cfg(not(target_os = "windows"))]
 345        let socket = SshSocket::new(connection_options, socket_path).await?;
 346        #[cfg(target_os = "windows")]
 347        let socket = SshSocket::new(
 348            connection_options,
 349            askpass
 350                .get_password()
 351                .or_else(|| askpass::EncryptedPassword::try_from("").ok())
 352                .context("Failed to fetch askpass password")?,
 353            cx.background_executor().clone(),
 354        )
 355        .await?;
 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    async 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    async fn new(
 672        options: SshConnectionOptions,
 673        password: askpass::EncryptedPassword,
 674        executor: gpui::BackgroundExecutor,
 675    ) -> Result<Self> {
 676        let mut envs = HashMap::default();
 677        let get_password =
 678            move |_| Task::ready(std::ops::ControlFlow::Continue(Ok(password.clone())));
 679
 680        let _proxy = askpass::PasswordProxy::new(get_password, executor).await?;
 681        envs.insert("SSH_ASKPASS_REQUIRE".into(), "force".into());
 682        envs.insert(
 683            "SSH_ASKPASS".into(),
 684            _proxy.script_path().as_ref().display().to_string(),
 685        );
 686
 687        Ok(Self {
 688            connection_options: options,
 689            envs,
 690            _proxy,
 691        })
 692    }
 693
 694    // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
 695    // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
 696    // and passes -l as an argument to sh, not to ls.
 697    // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
 698    // into a machine. You must use `cd` to get back to $HOME.
 699    // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
 700    fn ssh_command(&self, program: &str, args: &[impl AsRef<str>]) -> process::Command {
 701        let mut command = util::command::new_smol_command("ssh");
 702        let mut to_run = shlex::try_quote(program).unwrap().into_owned();
 703        for arg in args {
 704            // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
 705            debug_assert!(
 706                !arg.as_ref().contains('\n'),
 707                "multiline arguments do not work in all shells"
 708            );
 709            to_run.push(' ');
 710            to_run.push_str(&shlex::try_quote(arg.as_ref()).unwrap());
 711        }
 712        let to_run = format!("cd; {to_run}");
 713        self.ssh_options(&mut command)
 714            .arg(self.connection_options.ssh_url())
 715            .arg("-T")
 716            .arg(to_run);
 717        log::debug!("ssh {:?}", command);
 718        command
 719    }
 720
 721    async fn run_command(&self, program: &str, args: &[&str]) -> Result<String> {
 722        let output = self.ssh_command(program, args).output().await?;
 723        anyhow::ensure!(
 724            output.status.success(),
 725            "failed to run command: {}",
 726            String::from_utf8_lossy(&output.stderr)
 727        );
 728        Ok(String::from_utf8_lossy(&output.stdout).to_string())
 729    }
 730
 731    #[cfg(not(target_os = "windows"))]
 732    fn ssh_options<'a>(&self, command: &'a mut process::Command) -> &'a mut process::Command {
 733        command
 734            .stdin(Stdio::piped())
 735            .stdout(Stdio::piped())
 736            .stderr(Stdio::piped())
 737            .args(self.connection_options.additional_args())
 738            .args(["-o", "ControlMaster=no", "-o"])
 739            .arg(format!("ControlPath={}", self.socket_path.display()))
 740    }
 741
 742    #[cfg(target_os = "windows")]
 743    fn ssh_options<'a>(&self, command: &'a mut process::Command) -> &'a mut process::Command {
 744        command
 745            .stdin(Stdio::piped())
 746            .stdout(Stdio::piped())
 747            .stderr(Stdio::piped())
 748            .args(self.connection_options.additional_args())
 749            .envs(self.envs.clone())
 750    }
 751
 752    // On Windows, we need to use `SSH_ASKPASS` to provide the password to ssh.
 753    // On Linux, we use the `ControlPath` option to create a socket file that ssh can use to
 754    #[cfg(not(target_os = "windows"))]
 755    fn ssh_args(&self) -> Vec<String> {
 756        let mut arguments = self.connection_options.additional_args();
 757        arguments.extend(vec![
 758            "-o".to_string(),
 759            "ControlMaster=no".to_string(),
 760            "-o".to_string(),
 761            format!("ControlPath={}", self.socket_path.display()),
 762            self.connection_options.ssh_url(),
 763        ]);
 764        arguments
 765    }
 766
 767    #[cfg(target_os = "windows")]
 768    fn ssh_args(&self) -> Vec<String> {
 769        let mut arguments = self.connection_options.additional_args();
 770        arguments.push(self.connection_options.ssh_url());
 771        arguments
 772    }
 773
 774    async fn platform(&self) -> Result<RemotePlatform> {
 775        let uname = self.run_command("uname", &["-sm"]).await?;
 776        let Some((os, arch)) = uname.split_once(" ") else {
 777            anyhow::bail!("unknown uname: {uname:?}")
 778        };
 779
 780        let os = match os.trim() {
 781            "Darwin" => "macos",
 782            "Linux" => "linux",
 783            _ => anyhow::bail!(
 784                "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
 785            ),
 786        };
 787        // exclude armv5,6,7 as they are 32-bit.
 788        let arch = if arch.starts_with("armv8")
 789            || arch.starts_with("armv9")
 790            || arch.starts_with("arm64")
 791            || arch.starts_with("aarch64")
 792        {
 793            "aarch64"
 794        } else if arch.starts_with("x86") {
 795            "x86_64"
 796        } else {
 797            anyhow::bail!(
 798                "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
 799            )
 800        };
 801
 802        Ok(RemotePlatform { os, arch })
 803    }
 804
 805    async fn shell(&self) -> String {
 806        match self.run_command("sh", &["-c", "echo $SHELL"]).await {
 807            Ok(shell) => shell.trim().to_owned(),
 808            Err(e) => {
 809                log::error!("Failed to get shell: {e}");
 810                "sh".to_owned()
 811            }
 812        }
 813    }
 814}
 815
 816fn parse_port_number(port_str: &str) -> Result<u16> {
 817    port_str
 818        .parse()
 819        .with_context(|| format!("parsing port number: {port_str}"))
 820}
 821
 822fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
 823    let parts: Vec<&str> = spec.split(':').collect();
 824
 825    match parts.len() {
 826        4 => {
 827            let local_port = parse_port_number(parts[1])?;
 828            let remote_port = parse_port_number(parts[3])?;
 829
 830            Ok(SshPortForwardOption {
 831                local_host: Some(parts[0].to_string()),
 832                local_port,
 833                remote_host: Some(parts[2].to_string()),
 834                remote_port,
 835            })
 836        }
 837        3 => {
 838            let local_port = parse_port_number(parts[0])?;
 839            let remote_port = parse_port_number(parts[2])?;
 840
 841            Ok(SshPortForwardOption {
 842                local_host: None,
 843                local_port,
 844                remote_host: Some(parts[1].to_string()),
 845                remote_port,
 846            })
 847        }
 848        _ => anyhow::bail!("Invalid port forward format"),
 849    }
 850}
 851
 852impl SshConnectionOptions {
 853    pub fn parse_command_line(input: &str) -> Result<Self> {
 854        let input = input.trim_start_matches("ssh ");
 855        let mut hostname: Option<String> = None;
 856        let mut username: Option<String> = None;
 857        let mut port: Option<u16> = None;
 858        let mut args = Vec::new();
 859        let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
 860
 861        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
 862        const ALLOWED_OPTS: &[&str] = &[
 863            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
 864        ];
 865        const ALLOWED_ARGS: &[&str] = &[
 866            "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
 867            "-w",
 868        ];
 869
 870        let mut tokens = shlex::split(input).context("invalid input")?.into_iter();
 871
 872        'outer: while let Some(arg) = tokens.next() {
 873            if ALLOWED_OPTS.contains(&(&arg as &str)) {
 874                args.push(arg.to_string());
 875                continue;
 876            }
 877            if arg == "-p" {
 878                port = tokens.next().and_then(|arg| arg.parse().ok());
 879                continue;
 880            } else if let Some(p) = arg.strip_prefix("-p") {
 881                port = p.parse().ok();
 882                continue;
 883            }
 884            if arg == "-l" {
 885                username = tokens.next();
 886                continue;
 887            } else if let Some(l) = arg.strip_prefix("-l") {
 888                username = Some(l.to_string());
 889                continue;
 890            }
 891            if arg == "-L" || arg.starts_with("-L") {
 892                let forward_spec = if arg == "-L" {
 893                    tokens.next()
 894                } else {
 895                    Some(arg.strip_prefix("-L").unwrap().to_string())
 896                };
 897
 898                if let Some(spec) = forward_spec {
 899                    port_forwards.push(parse_port_forward_spec(&spec)?);
 900                } else {
 901                    anyhow::bail!("Missing port forward format");
 902                }
 903            }
 904
 905            for a in ALLOWED_ARGS {
 906                if arg == *a {
 907                    args.push(arg);
 908                    if let Some(next) = tokens.next() {
 909                        args.push(next);
 910                    }
 911                    continue 'outer;
 912                } else if arg.starts_with(a) {
 913                    args.push(arg);
 914                    continue 'outer;
 915                }
 916            }
 917            if arg.starts_with("-") || hostname.is_some() {
 918                anyhow::bail!("unsupported argument: {:?}", arg);
 919            }
 920            let mut input = &arg as &str;
 921            // Destination might be: username1@username2@ip2@ip1
 922            if let Some((u, rest)) = input.rsplit_once('@') {
 923                input = rest;
 924                username = Some(u.to_string());
 925            }
 926            if let Some((rest, p)) = input.split_once(':') {
 927                input = rest;
 928                port = p.parse().ok()
 929            }
 930            hostname = Some(input.to_string())
 931        }
 932
 933        let Some(hostname) = hostname else {
 934            anyhow::bail!("missing hostname");
 935        };
 936
 937        let port_forwards = match port_forwards.len() {
 938            0 => None,
 939            _ => Some(port_forwards),
 940        };
 941
 942        Ok(Self {
 943            host: hostname,
 944            username,
 945            port,
 946            port_forwards,
 947            args: Some(args),
 948            password: None,
 949            nickname: None,
 950            upload_binary_over_ssh: false,
 951        })
 952    }
 953
 954    pub fn ssh_url(&self) -> String {
 955        let mut result = String::from("ssh://");
 956        if let Some(username) = &self.username {
 957            // Username might be: username1@username2@ip2
 958            let username = urlencoding::encode(username);
 959            result.push_str(&username);
 960            result.push('@');
 961        }
 962        result.push_str(&self.host);
 963        if let Some(port) = self.port {
 964            result.push(':');
 965            result.push_str(&port.to_string());
 966        }
 967        result
 968    }
 969
 970    pub fn additional_args(&self) -> Vec<String> {
 971        let mut args = self.args.iter().flatten().cloned().collect::<Vec<String>>();
 972
 973        if let Some(forwards) = &self.port_forwards {
 974            args.extend(forwards.iter().map(|pf| {
 975                let local_host = match &pf.local_host {
 976                    Some(host) => host,
 977                    None => "localhost",
 978                };
 979                let remote_host = match &pf.remote_host {
 980                    Some(host) => host,
 981                    None => "localhost",
 982                };
 983
 984                format!(
 985                    "-L{}:{}:{}:{}",
 986                    local_host, pf.local_port, remote_host, pf.remote_port
 987                )
 988            }));
 989        }
 990
 991        args
 992    }
 993
 994    fn scp_url(&self) -> String {
 995        if let Some(username) = &self.username {
 996            format!("{}@{}", username, self.host)
 997        } else {
 998            self.host.clone()
 999        }
1000    }
1001
1002    pub fn connection_string(&self) -> String {
1003        let host = if let Some(username) = &self.username {
1004            format!("{}@{}", username, self.host)
1005        } else {
1006            self.host.clone()
1007        };
1008        if let Some(port) = &self.port {
1009            format!("{}:{}", host, port)
1010        } else {
1011            host
1012        }
1013    }
1014}
1015
1016fn build_command(
1017    input_program: Option<String>,
1018    input_args: &[String],
1019    input_env: &HashMap<String, String>,
1020    working_dir: Option<String>,
1021    port_forward: Option<(u16, String, u16)>,
1022    ssh_env: HashMap<String, String>,
1023    ssh_path_style: PathStyle,
1024    ssh_shell: &str,
1025    ssh_args: Vec<String>,
1026) -> Result<CommandTemplate> {
1027    use std::fmt::Write as _;
1028
1029    let mut exec = String::new();
1030    if let Some(working_dir) = working_dir {
1031        let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1032
1033        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
1034        // replace with with something that works
1035        const TILDE_PREFIX: &'static str = "~/";
1036        if working_dir.starts_with(TILDE_PREFIX) {
1037            let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
1038            write!(exec, "cd \"$HOME/{working_dir}\" && ",).unwrap();
1039        } else {
1040            write!(exec, "cd \"{working_dir}\" && ",).unwrap();
1041        }
1042    } else {
1043        write!(exec, "cd && ").unwrap();
1044    };
1045    write!(exec, "exec env ").unwrap();
1046
1047    for (k, v) in input_env.iter() {
1048        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
1049            write!(exec, "{}={} ", k, v).unwrap();
1050        }
1051    }
1052
1053    if let Some(input_program) = input_program {
1054        write!(exec, "{}", shlex::try_quote(&input_program).unwrap()).unwrap();
1055        for arg in input_args {
1056            let arg = shlex::try_quote(&arg)?;
1057            write!(exec, " {}", &arg).unwrap();
1058        }
1059    } else {
1060        write!(exec, "{ssh_shell} -l").unwrap();
1061    };
1062
1063    let mut args = Vec::new();
1064    args.extend(ssh_args);
1065
1066    if let Some((local_port, host, remote_port)) = port_forward {
1067        args.push("-L".into());
1068        args.push(format!("{local_port}:{host}:{remote_port}"));
1069    }
1070
1071    args.push("-t".into());
1072    args.push(exec);
1073    Ok(CommandTemplate {
1074        program: "ssh".into(),
1075        args,
1076        env: ssh_env,
1077    })
1078}
1079
1080#[cfg(test)]
1081mod tests {
1082    use super::*;
1083
1084    #[test]
1085    fn test_build_command() -> Result<()> {
1086        let mut input_env = HashMap::default();
1087        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1088        let mut env = HashMap::default();
1089        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1090
1091        let command = build_command(
1092            Some("remote_program".to_string()),
1093            &["arg1".to_string(), "arg2".to_string()],
1094            &input_env,
1095            Some("~/work".to_string()),
1096            None,
1097            env.clone(),
1098            PathStyle::Posix,
1099            "/bin/fish",
1100            vec!["-p".to_string(), "2222".to_string()],
1101        )?;
1102
1103        assert_eq!(command.program, "ssh");
1104        assert_eq!(
1105            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1106            [
1107                "-p",
1108                "2222",
1109                "-t",
1110                "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1111            ]
1112        );
1113        assert_eq!(command.env, env);
1114
1115        let mut input_env = HashMap::default();
1116        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1117        let mut env = HashMap::default();
1118        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1119
1120        let command = build_command(
1121            None,
1122            &["arg1".to_string(), "arg2".to_string()],
1123            &input_env,
1124            None,
1125            Some((1, "foo".to_owned(), 2)),
1126            env.clone(),
1127            PathStyle::Posix,
1128            "/bin/fish",
1129            vec!["-p".to_string(), "2222".to_string()],
1130        )?;
1131
1132        assert_eq!(command.program, "ssh");
1133        assert_eq!(
1134            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1135            [
1136                "-p",
1137                "2222",
1138                "-L",
1139                "1:foo:2",
1140                "-t",
1141                "cd && exec env INPUT_VA=val /bin/fish -l"
1142            ]
1143        );
1144        assert_eq!(command.env, env);
1145
1146        Ok(())
1147    }
1148}