ssh.rs

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