ssh.rs

   1use crate::{
   2    RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
   3    remote_client::{CommandTemplate, Interactive, RemoteConnection, RemoteConnectionOptions},
   4    transport::{parse_platform, parse_shell},
   5};
   6use anyhow::{Context as _, Result, anyhow};
   7use async_trait::async_trait;
   8use collections::HashMap;
   9use futures::{
  10    AsyncReadExt as _, FutureExt as _,
  11    channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender},
  12    select_biased,
  13};
  14use gpui::{App, AppContext as _, AsyncApp, Task};
  15use parking_lot::Mutex;
  16use paths::remote_server_dir_relative;
  17use release_channel::{AppVersion, ReleaseChannel};
  18use rpc::proto::Envelope;
  19use semver::Version;
  20pub use settings::SshPortForwardOption;
  21use smol::{
  22    fs,
  23    process::{self, Child, Stdio},
  24};
  25use std::{
  26    net::IpAddr,
  27    path::{Path, PathBuf},
  28    sync::Arc,
  29    time::Instant,
  30};
  31use tempfile::TempDir;
  32use util::{
  33    paths::{PathStyle, RemotePathBuf},
  34    rel_path::RelPath,
  35    shell::ShellKind,
  36};
  37
  38pub(crate) struct SshRemoteConnection {
  39    socket: SshSocket,
  40    master_process: Mutex<Option<MasterProcess>>,
  41    remote_binary_path: Option<Arc<RelPath>>,
  42    ssh_platform: RemotePlatform,
  43    ssh_path_style: PathStyle,
  44    ssh_shell: String,
  45    ssh_shell_kind: ShellKind,
  46    ssh_default_system_shell: String,
  47    _temp_dir: TempDir,
  48}
  49
  50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
  51pub enum SshConnectionHost {
  52    IpAddr(IpAddr),
  53    Hostname(String),
  54}
  55
  56impl SshConnectionHost {
  57    pub fn to_bracketed_string(&self) -> String {
  58        match self {
  59            Self::IpAddr(IpAddr::V4(ip)) => ip.to_string(),
  60            Self::IpAddr(IpAddr::V6(ip)) => format!("[{}]", ip),
  61            Self::Hostname(hostname) => hostname.clone(),
  62        }
  63    }
  64
  65    pub fn to_string(&self) -> String {
  66        match self {
  67            Self::IpAddr(ip) => ip.to_string(),
  68            Self::Hostname(hostname) => hostname.clone(),
  69        }
  70    }
  71}
  72
  73impl From<&str> for SshConnectionHost {
  74    fn from(value: &str) -> Self {
  75        if let Ok(address) = value.parse() {
  76            Self::IpAddr(address)
  77        } else {
  78            Self::Hostname(value.to_string())
  79        }
  80    }
  81}
  82
  83impl From<String> for SshConnectionHost {
  84    fn from(value: String) -> Self {
  85        if let Ok(address) = value.parse() {
  86            Self::IpAddr(address)
  87        } else {
  88            Self::Hostname(value)
  89        }
  90    }
  91}
  92
  93impl Default for SshConnectionHost {
  94    fn default() -> Self {
  95        Self::Hostname(Default::default())
  96    }
  97}
  98
  99#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
 100pub struct SshConnectionOptions {
 101    pub host: SshConnectionHost,
 102    pub username: Option<String>,
 103    pub port: Option<u16>,
 104    pub password: Option<String>,
 105    pub args: Option<Vec<String>>,
 106    pub port_forwards: Option<Vec<SshPortForwardOption>>,
 107    pub connection_timeout: Option<u16>,
 108
 109    pub nickname: Option<String>,
 110    pub upload_binary_over_ssh: bool,
 111}
 112
 113impl From<settings::SshConnection> for SshConnectionOptions {
 114    fn from(val: settings::SshConnection) -> Self {
 115        SshConnectionOptions {
 116            host: val.host.to_string().into(),
 117            username: val.username,
 118            port: val.port,
 119            password: None,
 120            args: Some(val.args),
 121            nickname: val.nickname,
 122            upload_binary_over_ssh: val.upload_binary_over_ssh.unwrap_or_default(),
 123            port_forwards: val.port_forwards,
 124            connection_timeout: val.connection_timeout,
 125        }
 126    }
 127}
 128
 129struct SshSocket {
 130    connection_options: SshConnectionOptions,
 131    #[cfg(not(target_os = "windows"))]
 132    socket_path: std::path::PathBuf,
 133    envs: HashMap<String, String>,
 134    #[cfg(target_os = "windows")]
 135    _proxy: askpass::PasswordProxy,
 136}
 137
 138struct MasterProcess {
 139    process: Child,
 140}
 141
 142#[cfg(not(target_os = "windows"))]
 143impl MasterProcess {
 144    pub fn new(
 145        askpass_script_path: &std::ffi::OsStr,
 146        additional_args: Vec<String>,
 147        socket_path: &std::path::Path,
 148        destination: &str,
 149    ) -> Result<Self> {
 150        let args = [
 151            "-N",
 152            "-o",
 153            "ControlPersist=no",
 154            "-o",
 155            "ControlMaster=yes",
 156            "-o",
 157        ];
 158
 159        let mut master_process = util::command::new_smol_command("ssh");
 160        master_process
 161            .kill_on_drop(true)
 162            .stdin(Stdio::null())
 163            .stdout(Stdio::piped())
 164            .stderr(Stdio::piped())
 165            .env("SSH_ASKPASS_REQUIRE", "force")
 166            .env("SSH_ASKPASS", askpass_script_path)
 167            .args(additional_args)
 168            .args(args);
 169
 170        master_process.arg(format!("ControlPath={}", socket_path.display()));
 171
 172        let process = master_process.arg(&destination).spawn()?;
 173
 174        Ok(MasterProcess { process })
 175    }
 176
 177    pub async fn wait_connected(&mut self) -> Result<()> {
 178        let Some(mut stdout) = self.process.stdout.take() else {
 179            anyhow::bail!("ssh process stdout capture failed");
 180        };
 181
 182        let mut output = Vec::new();
 183        stdout.read_to_end(&mut output).await?;
 184        Ok(())
 185    }
 186}
 187
 188#[cfg(target_os = "windows")]
 189impl MasterProcess {
 190    const CONNECTION_ESTABLISHED_MAGIC: &str = "ZED_SSH_CONNECTION_ESTABLISHED";
 191
 192    pub fn new(
 193        askpass_script_path: &std::ffi::OsStr,
 194        additional_args: Vec<String>,
 195        destination: &str,
 196    ) -> Result<Self> {
 197        // On Windows, `ControlMaster` and `ControlPath` are not supported:
 198        // https://github.com/PowerShell/Win32-OpenSSH/issues/405
 199        // https://github.com/PowerShell/Win32-OpenSSH/wiki/Project-Scope
 200        //
 201        // Using an ugly workaround to detect connection establishment
 202        // -N doesn't work with JumpHosts as windows openssh never closes stdin in that case
 203        let args = [
 204            "-t",
 205            &format!("echo '{}'; exec $0", Self::CONNECTION_ESTABLISHED_MAGIC),
 206        ];
 207
 208        let mut master_process = util::command::new_smol_command("ssh");
 209        master_process
 210            .kill_on_drop(true)
 211            .stdin(Stdio::null())
 212            .stdout(Stdio::piped())
 213            .stderr(Stdio::piped())
 214            .env("SSH_ASKPASS_REQUIRE", "force")
 215            .env("SSH_ASKPASS", askpass_script_path)
 216            .args(additional_args)
 217            .arg(destination)
 218            .args(args);
 219
 220        let process = master_process.spawn()?;
 221
 222        Ok(MasterProcess { process })
 223    }
 224
 225    pub async fn wait_connected(&mut self) -> Result<()> {
 226        use smol::io::AsyncBufReadExt;
 227
 228        let Some(stdout) = self.process.stdout.take() else {
 229            anyhow::bail!("ssh process stdout capture failed");
 230        };
 231
 232        let mut reader = smol::io::BufReader::new(stdout);
 233
 234        let mut line = String::new();
 235
 236        loop {
 237            let n = reader.read_line(&mut line).await?;
 238            if n == 0 {
 239                anyhow::bail!("ssh process exited before connection established");
 240            }
 241
 242            if line.contains(Self::CONNECTION_ESTABLISHED_MAGIC) {
 243                return Ok(());
 244            }
 245        }
 246    }
 247}
 248
 249impl AsRef<Child> for MasterProcess {
 250    fn as_ref(&self) -> &Child {
 251        &self.process
 252    }
 253}
 254
 255impl AsMut<Child> for MasterProcess {
 256    fn as_mut(&mut self) -> &mut Child {
 257        &mut self.process
 258    }
 259}
 260
 261#[async_trait(?Send)]
 262impl RemoteConnection for SshRemoteConnection {
 263    async fn kill(&self) -> Result<()> {
 264        let Some(mut process) = self.master_process.lock().take() else {
 265            return Ok(());
 266        };
 267        process.as_mut().kill().ok();
 268        process.as_mut().status().await?;
 269        Ok(())
 270    }
 271
 272    fn has_been_killed(&self) -> bool {
 273        self.master_process.lock().is_none()
 274    }
 275
 276    fn connection_options(&self) -> RemoteConnectionOptions {
 277        RemoteConnectionOptions::Ssh(self.socket.connection_options.clone())
 278    }
 279
 280    fn shell(&self) -> String {
 281        self.ssh_shell.clone()
 282    }
 283
 284    fn default_system_shell(&self) -> String {
 285        self.ssh_default_system_shell.clone()
 286    }
 287
 288    fn build_command(
 289        &self,
 290        input_program: Option<String>,
 291        input_args: &[String],
 292        input_env: &HashMap<String, String>,
 293        working_dir: Option<String>,
 294        port_forward: Option<(u16, String, u16)>,
 295        interactive: Interactive,
 296    ) -> Result<CommandTemplate> {
 297        let Self {
 298            ssh_path_style,
 299            socket,
 300            ssh_shell_kind,
 301            ssh_shell,
 302            ..
 303        } = self;
 304        let env = socket.envs.clone();
 305        build_command(
 306            input_program,
 307            input_args,
 308            input_env,
 309            working_dir,
 310            port_forward,
 311            env,
 312            *ssh_path_style,
 313            ssh_shell,
 314            *ssh_shell_kind,
 315            socket.ssh_args(),
 316            interactive,
 317        )
 318    }
 319
 320    fn build_forward_ports_command(
 321        &self,
 322        forwards: Vec<(u16, String, u16)>,
 323    ) -> Result<CommandTemplate> {
 324        let Self { socket, .. } = self;
 325        let mut args = socket.ssh_args();
 326        args.push("-N".into());
 327        for (local_port, host, remote_port) in forwards {
 328            args.push("-L".into());
 329            args.push(format!("{local_port}:{host}:{remote_port}"));
 330        }
 331        Ok(CommandTemplate {
 332            program: "ssh".into(),
 333            args,
 334            env: Default::default(),
 335        })
 336    }
 337
 338    fn upload_directory(
 339        &self,
 340        src_path: PathBuf,
 341        dest_path: RemotePathBuf,
 342        cx: &App,
 343    ) -> Task<Result<()>> {
 344        let dest_path_str = dest_path.to_string();
 345        let src_path_display = src_path.display().to_string();
 346
 347        let mut sftp_command = self.build_sftp_command();
 348        let mut scp_command =
 349            self.build_scp_command(&src_path, &dest_path_str, Some(&["-C", "-r"]));
 350
 351        cx.background_spawn(async move {
 352            // We will try SFTP first, and if that fails, we will fall back to SCP.
 353            // If SCP fails also, we give up and return an error.
 354            // The reason we allow a fallback from SFTP to SCP is that if the user has to specify a password,
 355            // depending on the implementation of SSH stack, SFTP may disable interactive password prompts in batch mode.
 356            // This is for example the case on Windows as evidenced by this implementation snippet:
 357            // https://github.com/PowerShell/openssh-portable/blob/b8c08ef9da9450a94a9c5ef717d96a7bd83f3332/sshconnect2.c#L417
 358            if Self::is_sftp_available().await {
 359                log::debug!("using SFTP for directory upload");
 360                let mut child = sftp_command.spawn()?;
 361                if let Some(mut stdin) = child.stdin.take() {
 362                    use futures::AsyncWriteExt;
 363                    let sftp_batch = format!("put -r \"{src_path_display}\" \"{dest_path_str}\"\n");
 364                    stdin.write_all(sftp_batch.as_bytes()).await?;
 365                    stdin.flush().await?;
 366                }
 367
 368                let output = child.output().await?;
 369                if output.status.success() {
 370                    return Ok(());
 371                }
 372
 373                let stderr = String::from_utf8_lossy(&output.stderr);
 374                log::debug!("failed to upload directory via SFTP {src_path_display} -> {dest_path_str}: {stderr}");
 375            }
 376
 377            log::debug!("using SCP for directory upload");
 378            let output = scp_command.output().await?;
 379
 380            if output.status.success() {
 381                return Ok(());
 382            }
 383
 384            let stderr = String::from_utf8_lossy(&output.stderr);
 385            log::debug!("failed to upload directory via SCP {src_path_display} -> {dest_path_str}: {stderr}");
 386
 387            anyhow::bail!(
 388                "failed to upload directory via SFTP/SCP {} -> {}: {}",
 389                src_path_display,
 390                dest_path_str,
 391                stderr,
 392            );
 393        })
 394    }
 395
 396    fn start_proxy(
 397        &self,
 398        unique_identifier: String,
 399        reconnect: bool,
 400        incoming_tx: UnboundedSender<Envelope>,
 401        outgoing_rx: UnboundedReceiver<Envelope>,
 402        connection_activity_tx: Sender<()>,
 403        delegate: Arc<dyn RemoteClientDelegate>,
 404        cx: &mut AsyncApp,
 405    ) -> Task<Result<i32>> {
 406        const VARS: [&str; 3] = ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"];
 407        delegate.set_status(Some("Starting proxy"), cx);
 408
 409        let Some(remote_binary_path) = self.remote_binary_path.clone() else {
 410            return Task::ready(Err(anyhow!("Remote binary path not set")));
 411        };
 412
 413        let mut ssh_command = if self.ssh_platform.os.is_windows() {
 414            // TODO: Set the `VARS` environment variables, we do not have `env` on windows
 415            // so this needs a different approach
 416            let mut proxy_args = vec![];
 417            proxy_args.push("proxy".to_owned());
 418            proxy_args.push("--identifier".to_owned());
 419            proxy_args.push(unique_identifier);
 420
 421            if reconnect {
 422                proxy_args.push("--reconnect".to_owned());
 423            }
 424            self.socket.ssh_command(
 425                self.ssh_shell_kind,
 426                &remote_binary_path.display(self.path_style()),
 427                &proxy_args,
 428                false,
 429            )
 430        } else {
 431            let mut proxy_args = vec![];
 432            for env_var in VARS {
 433                if let Some(value) = std::env::var(env_var).ok() {
 434                    proxy_args.push(format!("{}='{}'", env_var, value));
 435                }
 436            }
 437            proxy_args.push(remote_binary_path.display(self.path_style()).into_owned());
 438            proxy_args.push("proxy".to_owned());
 439            proxy_args.push("--identifier".to_owned());
 440            proxy_args.push(unique_identifier);
 441
 442            if reconnect {
 443                proxy_args.push("--reconnect".to_owned());
 444            }
 445            self.socket
 446                .ssh_command(self.ssh_shell_kind, "env", &proxy_args, false)
 447        };
 448
 449        let ssh_proxy_process = match ssh_command
 450            // IMPORTANT: we kill this process when we drop the task that uses it.
 451            .kill_on_drop(true)
 452            .spawn()
 453        {
 454            Ok(process) => process,
 455            Err(error) => {
 456                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
 457            }
 458        };
 459
 460        super::handle_rpc_messages_over_child_process_stdio(
 461            ssh_proxy_process,
 462            incoming_tx,
 463            outgoing_rx,
 464            connection_activity_tx,
 465            cx,
 466        )
 467    }
 468
 469    fn path_style(&self) -> PathStyle {
 470        self.ssh_path_style
 471    }
 472
 473    fn has_wsl_interop(&self) -> bool {
 474        false
 475    }
 476}
 477
 478impl SshRemoteConnection {
 479    pub(crate) async fn new(
 480        connection_options: SshConnectionOptions,
 481        delegate: Arc<dyn RemoteClientDelegate>,
 482        cx: &mut AsyncApp,
 483    ) -> Result<Self> {
 484        use askpass::AskPassResult;
 485
 486        let destination = connection_options.ssh_destination();
 487
 488        let temp_dir = tempfile::Builder::new()
 489            .prefix("zed-ssh-session")
 490            .tempdir()?;
 491        let askpass_delegate = askpass::AskPassDelegate::new(cx, {
 492            let delegate = delegate.clone();
 493            move |prompt, tx, cx| delegate.ask_password(prompt, tx, cx)
 494        });
 495
 496        let mut askpass =
 497            askpass::AskPassSession::new(cx.background_executor().clone(), askpass_delegate)
 498                .await?;
 499
 500        delegate.set_status(Some("Connecting"), cx);
 501
 502        // Start the master SSH process, which does not do anything except for establish
 503        // the connection and keep it open, allowing other ssh commands to reuse it
 504        // via a control socket.
 505        #[cfg(not(target_os = "windows"))]
 506        let socket_path = temp_dir.path().join("ssh.sock");
 507
 508        #[cfg(target_os = "windows")]
 509        let mut master_process = MasterProcess::new(
 510            askpass.script_path().as_ref(),
 511            connection_options.additional_args(),
 512            &destination,
 513        )?;
 514        #[cfg(not(target_os = "windows"))]
 515        let mut master_process = MasterProcess::new(
 516            askpass.script_path().as_ref(),
 517            connection_options.additional_args(),
 518            &socket_path,
 519            &destination,
 520        )?;
 521
 522        let result = select_biased! {
 523            result = askpass.run().fuse() => {
 524                match result {
 525                    AskPassResult::CancelledByUser => {
 526                        master_process.as_mut().kill().ok();
 527                        anyhow::bail!("SSH connection canceled")
 528                    }
 529                    AskPassResult::Timedout => {
 530                        anyhow::bail!("connecting to host timed out")
 531                    }
 532                }
 533            }
 534            _ = master_process.wait_connected().fuse() => {
 535                anyhow::Ok(())
 536            }
 537        };
 538
 539        if let Err(e) = result {
 540            return Err(e.context("Failed to connect to host"));
 541        }
 542
 543        if master_process.as_mut().try_status()?.is_some() {
 544            let mut output = Vec::new();
 545            output.clear();
 546            let mut stderr = master_process.as_mut().stderr.take().unwrap();
 547            stderr.read_to_end(&mut output).await?;
 548
 549            let error_message = format!(
 550                "failed to connect: {}",
 551                String::from_utf8_lossy(&output).trim()
 552            );
 553            anyhow::bail!(error_message);
 554        }
 555
 556        #[cfg(not(target_os = "windows"))]
 557        let socket = SshSocket::new(connection_options, socket_path).await?;
 558        #[cfg(target_os = "windows")]
 559        let socket = SshSocket::new(
 560            connection_options,
 561            askpass
 562                .get_password()
 563                .or_else(|| askpass::EncryptedPassword::try_from("").ok())
 564                .context("Failed to fetch askpass password")?,
 565            cx.background_executor().clone(),
 566        )
 567        .await?;
 568        drop(askpass);
 569
 570        let is_windows = socket.probe_is_windows().await;
 571        log::info!("Remote is windows: {}", is_windows);
 572
 573        let ssh_shell = socket.shell(is_windows).await;
 574        log::info!("Remote shell discovered: {}", ssh_shell);
 575
 576        let ssh_shell_kind = ShellKind::new(&ssh_shell, is_windows);
 577        let ssh_platform = socket.platform(ssh_shell_kind, is_windows).await?;
 578        log::info!("Remote platform discovered: {:?}", ssh_platform);
 579
 580        let (ssh_path_style, ssh_default_system_shell) = match ssh_platform.os {
 581            RemoteOs::Windows => (PathStyle::Windows, ssh_shell.clone()),
 582            _ => (PathStyle::Posix, String::from("/bin/sh")),
 583        };
 584
 585        let mut this = Self {
 586            socket,
 587            master_process: Mutex::new(Some(master_process)),
 588            _temp_dir: temp_dir,
 589            remote_binary_path: None,
 590            ssh_path_style,
 591            ssh_platform,
 592            ssh_shell,
 593            ssh_shell_kind,
 594            ssh_default_system_shell,
 595        };
 596
 597        let (release_channel, version) =
 598            cx.update(|cx| (ReleaseChannel::global(cx), AppVersion::global(cx)));
 599        this.remote_binary_path = Some(
 600            this.ensure_server_binary(&delegate, release_channel, version, cx)
 601                .await?,
 602        );
 603
 604        Ok(this)
 605    }
 606
 607    async fn ensure_server_binary(
 608        &self,
 609        delegate: &Arc<dyn RemoteClientDelegate>,
 610        release_channel: ReleaseChannel,
 611        version: Version,
 612        cx: &mut AsyncApp,
 613    ) -> Result<Arc<RelPath>> {
 614        let version_str = match release_channel {
 615            ReleaseChannel::Dev => "build".to_string(),
 616            _ => version.to_string(),
 617        };
 618        let binary_name = format!(
 619            "zed-remote-server-{}-{}{}",
 620            release_channel.dev_name(),
 621            version_str,
 622            if self.ssh_platform.os.is_windows() {
 623                ".exe"
 624            } else {
 625                ""
 626            }
 627        );
 628        let dst_path =
 629            paths::remote_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
 630
 631        let binary_exists_on_server = self
 632            .socket
 633            .run_command(
 634                self.ssh_shell_kind,
 635                &dst_path.display(self.path_style()),
 636                &["version"],
 637                true,
 638            )
 639            .await
 640            .is_ok();
 641
 642        #[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
 643        if let Some(remote_server_path) = super::build_remote_server_from_source(
 644            &self.ssh_platform,
 645            delegate.as_ref(),
 646            binary_exists_on_server,
 647            cx,
 648        )
 649        .await?
 650        {
 651            let tmp_path = paths::remote_server_dir_relative().join(
 652                RelPath::unix(&format!(
 653                    "download-{}-{}",
 654                    std::process::id(),
 655                    remote_server_path.file_name().unwrap().to_string_lossy()
 656                ))
 657                .unwrap(),
 658            );
 659            self.upload_local_server_binary(&remote_server_path, &tmp_path, delegate, cx)
 660                .await?;
 661            self.extract_server_binary(&dst_path, &tmp_path, delegate, cx)
 662                .await?;
 663            return Ok(dst_path);
 664        }
 665
 666        if binary_exists_on_server {
 667            return Ok(dst_path);
 668        }
 669
 670        let wanted_version = cx.update(|cx| match release_channel {
 671            ReleaseChannel::Nightly => Ok(None),
 672            ReleaseChannel::Dev => {
 673                anyhow::bail!(
 674                    "ZED_BUILD_REMOTE_SERVER is not set and no remote server exists at ({:?})",
 675                    dst_path
 676                )
 677            }
 678            _ => Ok(Some(AppVersion::global(cx))),
 679        })?;
 680
 681        let tmp_path_compressed = remote_server_dir_relative().join(
 682            RelPath::unix(&format!(
 683                "{}-download-{}.{}",
 684                binary_name,
 685                std::process::id(),
 686                if self.ssh_platform.os.is_windows() {
 687                    "zip"
 688                } else {
 689                    "gz"
 690                }
 691            ))
 692            .unwrap(),
 693        );
 694        if !self.socket.connection_options.upload_binary_over_ssh
 695            && let Some(url) = delegate
 696                .get_download_url(
 697                    self.ssh_platform,
 698                    release_channel,
 699                    wanted_version.clone(),
 700                    cx,
 701                )
 702                .await?
 703        {
 704            match self
 705                .download_binary_on_server(&url, &tmp_path_compressed, delegate, cx)
 706                .await
 707            {
 708                Ok(_) => {
 709                    self.extract_server_binary(&dst_path, &tmp_path_compressed, delegate, cx)
 710                        .await
 711                        .context("extracting server binary")?;
 712                    return Ok(dst_path);
 713                }
 714                Err(e) => {
 715                    log::error!(
 716                        "Failed to download binary on server, attempting to download locally and then upload it the server: {e:#}",
 717                    )
 718                }
 719            }
 720        }
 721
 722        let src_path = delegate
 723            .download_server_binary_locally(
 724                self.ssh_platform,
 725                release_channel,
 726                wanted_version.clone(),
 727                cx,
 728            )
 729            .await
 730            .context("downloading server binary locally")?;
 731        self.upload_local_server_binary(&src_path, &tmp_path_compressed, delegate, cx)
 732            .await
 733            .context("uploading server binary")?;
 734        self.extract_server_binary(&dst_path, &tmp_path_compressed, delegate, cx)
 735            .await
 736            .context("extracting server binary")?;
 737        Ok(dst_path)
 738    }
 739
 740    async fn download_binary_on_server(
 741        &self,
 742        url: &str,
 743        tmp_path: &RelPath,
 744        delegate: &Arc<dyn RemoteClientDelegate>,
 745        cx: &mut AsyncApp,
 746    ) -> Result<()> {
 747        if let Some(parent) = tmp_path.parent() {
 748            let res = self
 749                .socket
 750                .run_command(
 751                    self.ssh_shell_kind,
 752                    "mkdir",
 753                    &["-p", parent.display(self.path_style()).as_ref()],
 754                    true,
 755                )
 756                .await;
 757            if !self.ssh_platform.os.is_windows() {
 758                // mkdir fails on windows if the path already exists ...
 759                res?;
 760            }
 761        }
 762
 763        delegate.set_status(Some("Downloading remote development server on host"), cx);
 764
 765        let connection_timeout = self
 766            .socket
 767            .connection_options
 768            .connection_timeout
 769            .unwrap_or(10)
 770            .to_string();
 771
 772        match self
 773            .socket
 774            .run_command(
 775                self.ssh_shell_kind,
 776                "curl",
 777                &[
 778                    "-f",
 779                    "-L",
 780                    "--connect-timeout",
 781                    &connection_timeout,
 782                    url,
 783                    "-o",
 784                    &tmp_path.display(self.path_style()),
 785                ],
 786                true,
 787            )
 788            .await
 789        {
 790            Ok(_) => {}
 791            Err(e) => {
 792                if self
 793                    .socket
 794                    .run_command(self.ssh_shell_kind, "which", &["curl"], true)
 795                    .await
 796                    .is_ok()
 797                {
 798                    return Err(e);
 799                }
 800
 801                log::info!("curl is not available, trying wget");
 802                match self
 803                    .socket
 804                    .run_command(
 805                        self.ssh_shell_kind,
 806                        "wget",
 807                        &[
 808                            "--connect-timeout",
 809                            &connection_timeout,
 810                            "--tries",
 811                            "1",
 812                            url,
 813                            "-O",
 814                            &tmp_path.display(self.path_style()),
 815                        ],
 816                        true,
 817                    )
 818                    .await
 819                {
 820                    Ok(_) => {}
 821                    Err(e) => {
 822                        if self
 823                            .socket
 824                            .run_command(self.ssh_shell_kind, "which", &["wget"], true)
 825                            .await
 826                            .is_ok()
 827                        {
 828                            return Err(e);
 829                        } else {
 830                            anyhow::bail!("Neither curl nor wget is available");
 831                        }
 832                    }
 833                }
 834            }
 835        }
 836
 837        Ok(())
 838    }
 839
 840    async fn upload_local_server_binary(
 841        &self,
 842        src_path: &Path,
 843        tmp_path: &RelPath,
 844        delegate: &Arc<dyn RemoteClientDelegate>,
 845        cx: &mut AsyncApp,
 846    ) -> Result<()> {
 847        if let Some(parent) = tmp_path.parent() {
 848            let res = self
 849                .socket
 850                .run_command(
 851                    self.ssh_shell_kind,
 852                    "mkdir",
 853                    &["-p", parent.display(self.path_style()).as_ref()],
 854                    true,
 855                )
 856                .await;
 857            if !self.ssh_platform.os.is_windows() {
 858                // mkdir fails on windows if the path already exists ...
 859                res?;
 860            }
 861        }
 862
 863        let src_stat = fs::metadata(&src_path)
 864            .await
 865            .with_context(|| format!("failed to get metadata for {:?}", src_path))?;
 866        let size = src_stat.len();
 867
 868        let t0 = Instant::now();
 869        delegate.set_status(Some("Uploading remote development server"), cx);
 870        log::info!(
 871            "uploading remote development server to {:?} ({}kb)",
 872            tmp_path,
 873            size / 1024
 874        );
 875        self.upload_file(src_path, tmp_path)
 876            .await
 877            .context("failed to upload server binary")?;
 878        log::info!("uploaded remote development server in {:?}", t0.elapsed());
 879        Ok(())
 880    }
 881
 882    async fn extract_server_binary(
 883        &self,
 884        dst_path: &RelPath,
 885        tmp_path: &RelPath,
 886        delegate: &Arc<dyn RemoteClientDelegate>,
 887        cx: &mut AsyncApp,
 888    ) -> Result<()> {
 889        delegate.set_status(Some("Extracting remote development server"), cx);
 890
 891        if self.ssh_platform.os.is_windows() {
 892            self.extract_server_binary_windows(dst_path, tmp_path).await
 893        } else {
 894            self.extract_server_binary_posix(dst_path, tmp_path).await
 895        }
 896    }
 897
 898    async fn extract_server_binary_posix(
 899        &self,
 900        dst_path: &RelPath,
 901        tmp_path: &RelPath,
 902    ) -> Result<()> {
 903        let shell_kind = ShellKind::Posix;
 904        let server_mode = 0o755;
 905        let orig_tmp_path = tmp_path.display(self.path_style());
 906        let server_mode = format!("{:o}", server_mode);
 907        let server_mode = shell_kind
 908            .try_quote(&server_mode)
 909            .context("shell quoting")?;
 910        let dst_path = dst_path.display(self.path_style());
 911        let dst_path = shell_kind.try_quote(&dst_path).context("shell quoting")?;
 912        let script = if let Some(tmp_path) = orig_tmp_path.strip_suffix(".gz") {
 913            let orig_tmp_path = shell_kind
 914                .try_quote(&orig_tmp_path)
 915                .context("shell quoting")?;
 916            let tmp_path = shell_kind.try_quote(&tmp_path).context("shell quoting")?;
 917            format!(
 918                "gunzip -f {orig_tmp_path} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
 919            )
 920        } else {
 921            let orig_tmp_path = shell_kind
 922                .try_quote(&orig_tmp_path)
 923                .context("shell quoting")?;
 924            format!("chmod {server_mode} {orig_tmp_path} && mv {orig_tmp_path} {dst_path}",)
 925        };
 926        let args = shell_kind.args_for_shell(false, script.to_string());
 927        self.socket
 928            .run_command(self.ssh_shell_kind, "sh", &args, true)
 929            .await?;
 930        Ok(())
 931    }
 932
 933    async fn extract_server_binary_windows(
 934        &self,
 935        dst_path: &RelPath,
 936        tmp_path: &RelPath,
 937    ) -> Result<()> {
 938        let shell_kind = ShellKind::Pwsh;
 939        let orig_tmp_path = tmp_path.display(self.path_style());
 940        let dst_path = dst_path.display(self.path_style());
 941        let dst_path = shell_kind.try_quote(&dst_path).context("shell quoting")?;
 942
 943        let script = if let Some(tmp_path) = orig_tmp_path.strip_suffix(".zip") {
 944            let orig_tmp_path = shell_kind
 945                .try_quote(&orig_tmp_path)
 946                .context("shell quoting")?;
 947            let tmp_path = shell_kind.try_quote(tmp_path).context("shell quoting")?;
 948            let tmp_exe_path = format!("{tmp_path}\\remote_server.exe");
 949            let tmp_exe_path = shell_kind
 950                .try_quote(&tmp_exe_path)
 951                .context("shell quoting")?;
 952            format!(
 953                "Expand-Archive -Force -Path {orig_tmp_path} -DestinationPath {tmp_path} -ErrorAction Stop;
 954                 Move-Item -Force {tmp_exe_path} {dst_path};
 955                 Remove-Item -Force {tmp_path} -Recurse;
 956                 Remove-Item -Force {orig_tmp_path}",
 957            )
 958        } else {
 959            let orig_tmp_path = shell_kind
 960                .try_quote(&orig_tmp_path)
 961                .context("shell quoting")?;
 962            format!("Move-Item -Force {orig_tmp_path} {dst_path}")
 963        };
 964
 965        let args = shell_kind.args_for_shell(false, script);
 966        self.socket
 967            .run_command(self.ssh_shell_kind, "powershell", &args, true)
 968            .await?;
 969        Ok(())
 970    }
 971
 972    fn build_scp_command(
 973        &self,
 974        src_path: &Path,
 975        dest_path_str: &str,
 976        args: Option<&[&str]>,
 977    ) -> process::Command {
 978        let mut command = util::command::new_smol_command("scp");
 979        self.socket.ssh_options(&mut command, false).args(
 980            self.socket
 981                .connection_options
 982                .port
 983                .map(|port| vec!["-P".to_string(), port.to_string()])
 984                .unwrap_or_default(),
 985        );
 986        if let Some(args) = args {
 987            command.args(args);
 988        }
 989        command.arg(src_path).arg(format!(
 990            "{}:{}",
 991            self.socket.connection_options.scp_destination(),
 992            dest_path_str
 993        ));
 994        command
 995    }
 996
 997    fn build_sftp_command(&self) -> process::Command {
 998        let mut command = util::command::new_smol_command("sftp");
 999        self.socket.ssh_options(&mut command, false).args(
1000            self.socket
1001                .connection_options
1002                .port
1003                .map(|port| vec!["-P".to_string(), port.to_string()])
1004                .unwrap_or_default(),
1005        );
1006        command.arg("-b").arg("-");
1007        command.arg(self.socket.connection_options.scp_destination());
1008        command.stdin(Stdio::piped());
1009        command
1010    }
1011
1012    async fn upload_file(&self, src_path: &Path, dest_path: &RelPath) -> Result<()> {
1013        log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
1014
1015        let src_path_display = src_path.display().to_string();
1016        let dest_path_str = dest_path.display(self.path_style());
1017
1018        // We will try SFTP first, and if that fails, we will fall back to SCP.
1019        // If SCP fails also, we give up and return an error.
1020        // The reason we allow a fallback from SFTP to SCP is that if the user has to specify a password,
1021        // depending on the implementation of SSH stack, SFTP may disable interactive password prompts in batch mode.
1022        // This is for example the case on Windows as evidenced by this implementation snippet:
1023        // https://github.com/PowerShell/openssh-portable/blob/b8c08ef9da9450a94a9c5ef717d96a7bd83f3332/sshconnect2.c#L417
1024        if Self::is_sftp_available().await {
1025            log::debug!("using SFTP for file upload");
1026            let mut command = self.build_sftp_command();
1027            let sftp_batch = format!("put {src_path_display} {dest_path_str}\n");
1028
1029            let mut child = command.spawn()?;
1030            if let Some(mut stdin) = child.stdin.take() {
1031                use futures::AsyncWriteExt;
1032                stdin.write_all(sftp_batch.as_bytes()).await?;
1033                stdin.flush().await?;
1034            }
1035
1036            let output = child.output().await?;
1037            if output.status.success() {
1038                return Ok(());
1039            }
1040
1041            let stderr = String::from_utf8_lossy(&output.stderr);
1042            log::debug!(
1043                "failed to upload file via SFTP {src_path_display} -> {dest_path_str}: {stderr}"
1044            );
1045        }
1046
1047        log::debug!("using SCP for file upload");
1048        let mut command = self.build_scp_command(src_path, &dest_path_str, None);
1049        let output = command.output().await?;
1050
1051        if output.status.success() {
1052            return Ok(());
1053        }
1054
1055        let stderr = String::from_utf8_lossy(&output.stderr);
1056        log::debug!(
1057            "failed to upload file via SCP {src_path_display} -> {dest_path_str}: {stderr}",
1058        );
1059        anyhow::bail!(
1060            "failed to upload file via STFP/SCP {} -> {}: {}",
1061            src_path_display,
1062            dest_path_str,
1063            stderr,
1064        );
1065    }
1066
1067    async fn is_sftp_available() -> bool {
1068        which::which("sftp").is_ok()
1069    }
1070}
1071
1072impl SshSocket {
1073    #[cfg(not(target_os = "windows"))]
1074    async fn new(options: SshConnectionOptions, socket_path: PathBuf) -> Result<Self> {
1075        Ok(Self {
1076            connection_options: options,
1077            envs: HashMap::default(),
1078            socket_path,
1079        })
1080    }
1081
1082    #[cfg(target_os = "windows")]
1083    async fn new(
1084        options: SshConnectionOptions,
1085        password: askpass::EncryptedPassword,
1086        executor: gpui::BackgroundExecutor,
1087    ) -> Result<Self> {
1088        let mut envs = HashMap::default();
1089        let get_password =
1090            move |_| Task::ready(std::ops::ControlFlow::Continue(Ok(password.clone())));
1091
1092        let _proxy = askpass::PasswordProxy::new(get_password, executor).await?;
1093        envs.insert("SSH_ASKPASS_REQUIRE".into(), "force".into());
1094        envs.insert(
1095            "SSH_ASKPASS".into(),
1096            _proxy.script_path().as_ref().display().to_string(),
1097        );
1098
1099        Ok(Self {
1100            connection_options: options,
1101            envs,
1102            _proxy,
1103        })
1104    }
1105
1106    // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
1107    // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
1108    // and passes -l as an argument to sh, not to ls.
1109    // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
1110    // into a machine. You must use `cd` to get back to $HOME.
1111    // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
1112    fn ssh_command(
1113        &self,
1114        shell_kind: ShellKind,
1115        program: &str,
1116        args: &[impl AsRef<str>],
1117        allow_pseudo_tty: bool,
1118    ) -> process::Command {
1119        let mut command = util::command::new_smol_command("ssh");
1120        let program = shell_kind.prepend_command_prefix(program);
1121        let mut to_run = shell_kind
1122            .try_quote_prefix_aware(&program)
1123            .expect("shell quoting")
1124            .into_owned();
1125        for arg in args {
1126            // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
1127            debug_assert!(
1128                !arg.as_ref().contains('\n'),
1129                "multiline arguments do not work in all shells"
1130            );
1131            to_run.push(' ');
1132            to_run.push_str(&shell_kind.try_quote(arg.as_ref()).expect("shell quoting"));
1133        }
1134        let to_run = if shell_kind == ShellKind::Cmd {
1135            to_run // 'cd' prints the current directory in CMD
1136        } else {
1137            let separator = shell_kind.sequential_commands_separator();
1138            format!("cd{separator} {to_run}")
1139        };
1140        self.ssh_options(&mut command, true)
1141            .arg(self.connection_options.ssh_destination());
1142        if !allow_pseudo_tty {
1143            command.arg("-T");
1144        }
1145        command.arg(to_run);
1146        log::debug!("ssh {:?}", command);
1147        command
1148    }
1149
1150    async fn run_command(
1151        &self,
1152        shell_kind: ShellKind,
1153        program: &str,
1154        args: &[impl AsRef<str>],
1155        allow_pseudo_tty: bool,
1156    ) -> Result<String> {
1157        let mut command = self.ssh_command(shell_kind, program, args, allow_pseudo_tty);
1158        let output = command.output().await?;
1159        log::debug!("{:?}: {:?}", command, output);
1160        anyhow::ensure!(
1161            output.status.success(),
1162            "failed to run command {command:?}: {}",
1163            String::from_utf8_lossy(&output.stderr)
1164        );
1165        Ok(String::from_utf8_lossy(&output.stdout).to_string())
1166    }
1167
1168    #[cfg(not(target_os = "windows"))]
1169    fn ssh_options<'a>(
1170        &self,
1171        command: &'a mut process::Command,
1172        include_port_forwards: bool,
1173    ) -> &'a mut process::Command {
1174        let args = if include_port_forwards {
1175            self.connection_options.additional_args()
1176        } else {
1177            self.connection_options.additional_args_for_scp()
1178        };
1179
1180        command
1181            .stdin(Stdio::piped())
1182            .stdout(Stdio::piped())
1183            .stderr(Stdio::piped())
1184            .args(args)
1185            .args(["-o", "ControlMaster=no", "-o"])
1186            .arg(format!("ControlPath={}", self.socket_path.display()))
1187    }
1188
1189    #[cfg(target_os = "windows")]
1190    fn ssh_options<'a>(
1191        &self,
1192        command: &'a mut process::Command,
1193        include_port_forwards: bool,
1194    ) -> &'a mut process::Command {
1195        let args = if include_port_forwards {
1196            self.connection_options.additional_args()
1197        } else {
1198            self.connection_options.additional_args_for_scp()
1199        };
1200
1201        command
1202            .stdin(Stdio::piped())
1203            .stdout(Stdio::piped())
1204            .stderr(Stdio::piped())
1205            .args(args)
1206            .envs(self.envs.clone())
1207    }
1208
1209    // On Windows, we need to use `SSH_ASKPASS` to provide the password to ssh.
1210    // On Linux, we use the `ControlPath` option to create a socket file that ssh can use to
1211    #[cfg(not(target_os = "windows"))]
1212    fn ssh_args(&self) -> Vec<String> {
1213        let mut arguments = self.connection_options.additional_args();
1214        arguments.extend(vec![
1215            "-o".to_string(),
1216            "ControlMaster=no".to_string(),
1217            "-o".to_string(),
1218            format!("ControlPath={}", self.socket_path.display()),
1219            self.connection_options.ssh_destination(),
1220        ]);
1221        arguments
1222    }
1223
1224    #[cfg(target_os = "windows")]
1225    fn ssh_args(&self) -> Vec<String> {
1226        let mut arguments = self.connection_options.additional_args();
1227        arguments.push(self.connection_options.ssh_destination());
1228        arguments
1229    }
1230
1231    async fn platform(&self, shell: ShellKind, is_windows: bool) -> Result<RemotePlatform> {
1232        if is_windows {
1233            self.platform_windows(shell).await
1234        } else {
1235            self.platform_posix(shell).await
1236        }
1237    }
1238
1239    async fn platform_posix(&self, shell: ShellKind) -> Result<RemotePlatform> {
1240        let output = self
1241            .run_command(shell, "uname", &["-sm"], false)
1242            .await
1243            .context("Failed to run 'uname -sm' to determine platform")?;
1244        parse_platform(&output)
1245    }
1246
1247    async fn platform_windows(&self, shell: ShellKind) -> Result<RemotePlatform> {
1248        let output = self
1249            .run_command(
1250                shell,
1251                "cmd.exe",
1252                &["/c", "echo", "%PROCESSOR_ARCHITECTURE%"],
1253                false,
1254            )
1255            .await
1256            .context(
1257                "Failed to run 'echo %PROCESSOR_ARCHITECTURE%' to determine Windows architecture",
1258            )?;
1259
1260        Ok(RemotePlatform {
1261            os: RemoteOs::Windows,
1262            arch: match output.trim() {
1263                "AMD64" => RemoteArch::X86_64,
1264                "ARM64" => RemoteArch::Aarch64,
1265                arch => anyhow::bail!(
1266                    "Prebuilt remote servers are not yet available for windows-{arch}. See https://zed.dev/docs/remote-development"
1267                ),
1268            },
1269        })
1270    }
1271
1272    /// Probes whether the remote host is running Windows.
1273    ///
1274    /// This is done by attempting to run a simple Windows-specific command.
1275    /// If it succeeds and returns Windows-like output, we assume it's Windows.
1276    async fn probe_is_windows(&self) -> bool {
1277        match self
1278            .run_command(ShellKind::Cmd, "cmd.exe", &["/c", "ver"], false)
1279            .await
1280        {
1281            // Windows 'ver' command outputs something like "Microsoft Windows [Version 10.0.19045.5011]"
1282            Ok(output) => output.trim().contains("indows"),
1283            Err(_) => false,
1284        }
1285    }
1286
1287    async fn shell(&self, is_windows: bool) -> String {
1288        if is_windows {
1289            self.shell_windows().await
1290        } else {
1291            self.shell_posix().await
1292        }
1293    }
1294
1295    async fn shell_posix(&self) -> String {
1296        const DEFAULT_SHELL: &str = "sh";
1297        match self
1298            .run_command(ShellKind::Posix, "sh", &["-c", "echo $SHELL"], false)
1299            .await
1300        {
1301            Ok(output) => parse_shell(&output, DEFAULT_SHELL),
1302            Err(e) => {
1303                log::error!("Failed to detect remote shell: {e}");
1304                DEFAULT_SHELL.to_owned()
1305            }
1306        }
1307    }
1308
1309    async fn shell_windows(&self) -> String {
1310        const DEFAULT_SHELL: &str = "cmd.exe";
1311
1312        // We detect the shell used by the SSH session by running the following command in PowerShell:
1313        // (Get-CimInstance Win32_Process -Filter "ProcessId = $((Get-CimInstance Win32_Process -Filter ProcessId=$PID).ParentProcessId)").Name
1314        // This prints the name of PowerShell's parent process (which will be the shell that SSH launched).
1315        // We pass it as a Base64 encoded string since we don't yet know how to correctly quote that command.
1316        // (We'd need to know what the shell is to do that...)
1317        match self
1318            .run_command(
1319                ShellKind::Cmd,
1320                "powershell",
1321                &[
1322                    "-E",
1323                    "KABHAGUAdAAtAEMAaQBtAEkAbgBzAHQAYQBuAGMAZQAgAFcAaQBuADMAMgBfAFAAcgBvAGMAZQBzAHMAIAAtAEYAaQBsAHQAZQByACAAIgBQAHIAbwBjAGUAcwBzAEkAZAAgAD0AIAAkACgAKABHAGUAdAAtAEMAaQBtAEkAbgBzAHQAYQBuAGMAZQAgAFcAaQBuADMAMgBfAFAAcgBvAGMAZQBzAHMAIAAtAEYAaQBsAHQAZQByACAAUAByAG8AYwBlAHMAcwBJAGQAPQAkAFAASQBEACkALgBQAGEAcgBlAG4AdABQAHIAbwBjAGUAcwBzAEkAZAApACIAKQAuAE4AYQBtAGUA",
1324                ],
1325                false,
1326            )
1327            .await
1328        {
1329            Ok(output) => parse_shell(&output, DEFAULT_SHELL),
1330            Err(e) => {
1331                log::error!("Failed to detect remote shell: {e}");
1332                DEFAULT_SHELL.to_owned()
1333            }
1334        }
1335    }
1336}
1337
1338fn parse_port_number(port_str: &str) -> Result<u16> {
1339    port_str
1340        .parse()
1341        .with_context(|| format!("parsing port number: {port_str}"))
1342}
1343
1344fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
1345    let parts: Vec<&str> = spec.split(':').collect();
1346
1347    match parts.len() {
1348        4 => {
1349            let local_port = parse_port_number(parts[1])?;
1350            let remote_port = parse_port_number(parts[3])?;
1351
1352            Ok(SshPortForwardOption {
1353                local_host: Some(parts[0].to_string()),
1354                local_port,
1355                remote_host: Some(parts[2].to_string()),
1356                remote_port,
1357            })
1358        }
1359        3 => {
1360            let local_port = parse_port_number(parts[0])?;
1361            let remote_port = parse_port_number(parts[2])?;
1362
1363            Ok(SshPortForwardOption {
1364                local_host: None,
1365                local_port,
1366                remote_host: Some(parts[1].to_string()),
1367                remote_port,
1368            })
1369        }
1370        _ => anyhow::bail!("Invalid port forward format"),
1371    }
1372}
1373
1374impl SshConnectionOptions {
1375    pub fn parse_command_line(input: &str) -> Result<Self> {
1376        let input = input.trim_start_matches("ssh ");
1377        let mut hostname: Option<String> = None;
1378        let mut username: Option<String> = None;
1379        let mut port: Option<u16> = None;
1380        let mut args = Vec::new();
1381        let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
1382
1383        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
1384        const ALLOWED_OPTS: &[&str] = &[
1385            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
1386        ];
1387        const ALLOWED_ARGS: &[&str] = &[
1388            "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
1389            "-w",
1390        ];
1391
1392        let mut tokens = ShellKind::Posix
1393            .split(input)
1394            .context("invalid input")?
1395            .into_iter();
1396
1397        'outer: while let Some(arg) = tokens.next() {
1398            if ALLOWED_OPTS.contains(&(&arg as &str)) {
1399                args.push(arg.to_string());
1400                continue;
1401            }
1402            if arg == "-p" {
1403                port = tokens.next().and_then(|arg| arg.parse().ok());
1404                continue;
1405            } else if let Some(p) = arg.strip_prefix("-p") {
1406                port = p.parse().ok();
1407                continue;
1408            }
1409            if arg == "-l" {
1410                username = tokens.next();
1411                continue;
1412            } else if let Some(l) = arg.strip_prefix("-l") {
1413                username = Some(l.to_string());
1414                continue;
1415            }
1416            if arg == "-L" || arg.starts_with("-L") {
1417                let forward_spec = if arg == "-L" {
1418                    tokens.next()
1419                } else {
1420                    Some(arg.strip_prefix("-L").unwrap().to_string())
1421                };
1422
1423                if let Some(spec) = forward_spec {
1424                    port_forwards.push(parse_port_forward_spec(&spec)?);
1425                } else {
1426                    anyhow::bail!("Missing port forward format");
1427                }
1428            }
1429
1430            for a in ALLOWED_ARGS {
1431                if arg == *a {
1432                    args.push(arg);
1433                    if let Some(next) = tokens.next() {
1434                        args.push(next);
1435                    }
1436                    continue 'outer;
1437                } else if arg.starts_with(a) {
1438                    args.push(arg);
1439                    continue 'outer;
1440                }
1441            }
1442            if arg.starts_with("-") || hostname.is_some() {
1443                anyhow::bail!("unsupported argument: {:?}", arg);
1444            }
1445            let mut input = &arg as &str;
1446            // Destination might be: username1@username2@ip2@ip1
1447            if let Some((u, rest)) = input.rsplit_once('@') {
1448                input = rest;
1449                username = Some(u.to_string());
1450            }
1451
1452            // Handle port parsing, accounting for IPv6 addresses
1453            // IPv6 addresses can be: 2001:db8::1 or [2001:db8::1]:22
1454            if input.starts_with('[') {
1455                if let Some((rest, p)) = input.rsplit_once("]:") {
1456                    input = rest.strip_prefix('[').unwrap_or(rest);
1457                    port = p.parse().ok();
1458                } else if input.ends_with(']') {
1459                    input = input.strip_prefix('[').unwrap_or(input);
1460                    input = input.strip_suffix(']').unwrap_or(input);
1461                }
1462            } else if let Some((rest, p)) = input.rsplit_once(':')
1463                && !rest.contains(":")
1464            {
1465                input = rest;
1466                port = p.parse().ok();
1467            }
1468
1469            hostname = Some(input.to_string())
1470        }
1471
1472        let Some(hostname) = hostname else {
1473            anyhow::bail!("missing hostname");
1474        };
1475
1476        let port_forwards = match port_forwards.len() {
1477            0 => None,
1478            _ => Some(port_forwards),
1479        };
1480
1481        Ok(Self {
1482            host: hostname.into(),
1483            username,
1484            port,
1485            port_forwards,
1486            args: Some(args),
1487            password: None,
1488            nickname: None,
1489            upload_binary_over_ssh: false,
1490            connection_timeout: None,
1491        })
1492    }
1493
1494    pub fn ssh_destination(&self) -> String {
1495        let mut result = String::default();
1496        if let Some(username) = &self.username {
1497            // Username might be: username1@username2@ip2
1498            let username = urlencoding::encode(username);
1499            result.push_str(&username);
1500            result.push('@');
1501        }
1502
1503        result.push_str(&self.host.to_string());
1504        result
1505    }
1506
1507    pub fn additional_args_for_scp(&self) -> Vec<String> {
1508        self.args.iter().flatten().cloned().collect::<Vec<String>>()
1509    }
1510
1511    pub fn additional_args(&self) -> Vec<String> {
1512        let mut args = self.additional_args_for_scp();
1513
1514        if let Some(timeout) = self.connection_timeout {
1515            args.extend(["-o".to_string(), format!("ConnectTimeout={}", timeout)]);
1516        }
1517
1518        if let Some(port) = self.port {
1519            args.push("-p".to_string());
1520            args.push(port.to_string());
1521        }
1522
1523        if let Some(forwards) = &self.port_forwards {
1524            args.extend(forwards.iter().map(|pf| {
1525                let local_host = match &pf.local_host {
1526                    Some(host) => host,
1527                    None => "localhost",
1528                };
1529                let remote_host = match &pf.remote_host {
1530                    Some(host) => host,
1531                    None => "localhost",
1532                };
1533
1534                format!(
1535                    "-L{}:{}:{}:{}",
1536                    local_host, pf.local_port, remote_host, pf.remote_port
1537                )
1538            }));
1539        }
1540
1541        args
1542    }
1543
1544    fn scp_destination(&self) -> String {
1545        if let Some(username) = &self.username {
1546            format!("{}@{}", username, self.host.to_bracketed_string())
1547        } else {
1548            self.host.to_string()
1549        }
1550    }
1551
1552    pub fn connection_string(&self) -> String {
1553        let host = if let Some(port) = &self.port {
1554            format!("{}:{}", self.host.to_bracketed_string(), port)
1555        } else {
1556            self.host.to_string()
1557        };
1558
1559        if let Some(username) = &self.username {
1560            format!("{}@{}", username, host)
1561        } else {
1562            host
1563        }
1564    }
1565}
1566
1567fn build_command(
1568    input_program: Option<String>,
1569    input_args: &[String],
1570    input_env: &HashMap<String, String>,
1571    working_dir: Option<String>,
1572    port_forward: Option<(u16, String, u16)>,
1573    ssh_env: HashMap<String, String>,
1574    ssh_path_style: PathStyle,
1575    ssh_shell: &str,
1576    ssh_shell_kind: ShellKind,
1577    ssh_args: Vec<String>,
1578    interactive: Interactive,
1579) -> Result<CommandTemplate> {
1580    use std::fmt::Write as _;
1581
1582    let mut exec = String::new();
1583    if let Some(working_dir) = working_dir {
1584        let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1585
1586        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
1587        // replace with something that works
1588        const TILDE_PREFIX: &'static str = "~/";
1589        if working_dir.starts_with(TILDE_PREFIX) {
1590            let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
1591            write!(
1592                exec,
1593                "cd \"$HOME/{working_dir}\" {} ",
1594                ssh_shell_kind.sequential_and_commands_separator()
1595            )?;
1596        } else {
1597            write!(
1598                exec,
1599                "cd \"{working_dir}\" {} ",
1600                ssh_shell_kind.sequential_and_commands_separator()
1601            )?;
1602        }
1603    } else {
1604        write!(
1605            exec,
1606            "cd {} ",
1607            ssh_shell_kind.sequential_and_commands_separator()
1608        )?;
1609    };
1610    write!(exec, "exec env ")?;
1611
1612    for (k, v) in input_env.iter() {
1613        write!(
1614            exec,
1615            "{}={} ",
1616            k,
1617            ssh_shell_kind.try_quote(v).context("shell quoting")?
1618        )?;
1619    }
1620
1621    if let Some(input_program) = input_program {
1622        write!(
1623            exec,
1624            "{}",
1625            ssh_shell_kind
1626                .try_quote_prefix_aware(&input_program)
1627                .context("shell quoting")?
1628        )?;
1629        for arg in input_args {
1630            let arg = ssh_shell_kind.try_quote(&arg).context("shell quoting")?;
1631            write!(exec, " {}", &arg)?;
1632        }
1633    } else {
1634        write!(exec, "{ssh_shell} -l")?;
1635    };
1636
1637    let mut args = Vec::new();
1638    args.extend(ssh_args);
1639
1640    if let Some((local_port, host, remote_port)) = port_forward {
1641        args.push("-L".into());
1642        args.push(format!("{local_port}:{host}:{remote_port}"));
1643    }
1644
1645    // -q suppresses the "Connection to ... closed." message that SSH prints when
1646    // the connection terminates with -t (pseudo-terminal allocation)
1647    args.push("-q".into());
1648    match interactive {
1649        // -t forces pseudo-TTY allocation (for interactive use)
1650        Interactive::Yes => args.push("-t".into()),
1651        // -T disables pseudo-TTY allocation (for non-interactive piped stdio)
1652        Interactive::No => args.push("-T".into()),
1653    }
1654    args.push(exec);
1655
1656    Ok(CommandTemplate {
1657        program: "ssh".into(),
1658        args,
1659        env: ssh_env,
1660    })
1661}
1662
1663#[cfg(test)]
1664mod tests {
1665    use super::*;
1666
1667    #[test]
1668    fn test_build_command() -> Result<()> {
1669        let mut input_env = HashMap::default();
1670        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1671        let mut env = HashMap::default();
1672        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1673
1674        // Test non-interactive command (interactive=false should use -T)
1675        let command = build_command(
1676            Some("remote_program".to_string()),
1677            &["arg1".to_string(), "arg2".to_string()],
1678            &input_env,
1679            Some("~/work".to_string()),
1680            None,
1681            env.clone(),
1682            PathStyle::Posix,
1683            "/bin/bash",
1684            ShellKind::Posix,
1685            vec!["-o".to_string(), "ControlMaster=auto".to_string()],
1686            Interactive::No,
1687        )?;
1688        assert_eq!(command.program, "ssh");
1689        // Should contain -T for non-interactive
1690        assert!(command.args.iter().any(|arg| arg == "-T"));
1691        assert!(!command.args.iter().any(|arg| arg == "-t"));
1692
1693        // Test interactive command (interactive=true should use -t)
1694        let command = build_command(
1695            Some("remote_program".to_string()),
1696            &["arg1".to_string(), "arg2".to_string()],
1697            &input_env,
1698            Some("~/work".to_string()),
1699            None,
1700            env.clone(),
1701            PathStyle::Posix,
1702            "/bin/fish",
1703            ShellKind::Fish,
1704            vec!["-p".to_string(), "2222".to_string()],
1705            Interactive::Yes,
1706        )?;
1707
1708        assert_eq!(command.program, "ssh");
1709        assert_eq!(
1710            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1711            [
1712                "-p",
1713                "2222",
1714                "-q",
1715                "-t",
1716                "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1717            ]
1718        );
1719        assert_eq!(command.env, env);
1720
1721        let mut input_env = HashMap::default();
1722        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1723        let mut env = HashMap::default();
1724        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1725
1726        let command = build_command(
1727            None,
1728            &[],
1729            &input_env,
1730            None,
1731            Some((1, "foo".to_owned(), 2)),
1732            env.clone(),
1733            PathStyle::Posix,
1734            "/bin/fish",
1735            ShellKind::Fish,
1736            vec!["-p".to_string(), "2222".to_string()],
1737            Interactive::Yes,
1738        )?;
1739
1740        assert_eq!(command.program, "ssh");
1741        assert_eq!(
1742            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1743            [
1744                "-p",
1745                "2222",
1746                "-L",
1747                "1:foo:2",
1748                "-q",
1749                "-t",
1750                "cd && exec env INPUT_VA=val /bin/fish -l"
1751            ]
1752        );
1753        assert_eq!(command.env, env);
1754
1755        Ok(())
1756    }
1757
1758    #[test]
1759    fn scp_args_exclude_port_forward_flags() {
1760        let options = SshConnectionOptions {
1761            host: "example.com".into(),
1762            args: Some(vec![
1763                "-p".to_string(),
1764                "2222".to_string(),
1765                "-o".to_string(),
1766                "StrictHostKeyChecking=no".to_string(),
1767            ]),
1768            port_forwards: Some(vec![SshPortForwardOption {
1769                local_host: Some("127.0.0.1".to_string()),
1770                local_port: 8080,
1771                remote_host: Some("127.0.0.1".to_string()),
1772                remote_port: 80,
1773            }]),
1774            ..Default::default()
1775        };
1776
1777        let ssh_args = options.additional_args();
1778        assert!(
1779            ssh_args.iter().any(|arg| arg.starts_with("-L")),
1780            "expected ssh args to include port-forward: {ssh_args:?}"
1781        );
1782
1783        let scp_args = options.additional_args_for_scp();
1784        assert_eq!(
1785            scp_args,
1786            vec![
1787                "-p".to_string(),
1788                "2222".to_string(),
1789                "-o".to_string(),
1790                "StrictHostKeyChecking=no".to_string(),
1791            ]
1792        );
1793    }
1794
1795    #[test]
1796    fn test_host_parsing() -> Result<()> {
1797        let opts = SshConnectionOptions::parse_command_line("user@2001:db8::1")?;
1798        assert_eq!(opts.host, "2001:db8::1".into());
1799        assert_eq!(opts.username, Some("user".to_string()));
1800        assert_eq!(opts.port, None);
1801
1802        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]:2222")?;
1803        assert_eq!(opts.host, "2001:db8::1".into());
1804        assert_eq!(opts.username, Some("user".to_string()));
1805        assert_eq!(opts.port, Some(2222));
1806
1807        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]")?;
1808        assert_eq!(opts.host, "2001:db8::1".into());
1809        assert_eq!(opts.username, Some("user".to_string()));
1810        assert_eq!(opts.port, None);
1811
1812        let opts = SshConnectionOptions::parse_command_line("2001:db8::1")?;
1813        assert_eq!(opts.host, "2001:db8::1".into());
1814        assert_eq!(opts.username, None);
1815        assert_eq!(opts.port, None);
1816
1817        let opts = SshConnectionOptions::parse_command_line("[2001:db8::1]:2222")?;
1818        assert_eq!(opts.host, "2001:db8::1".into());
1819        assert_eq!(opts.username, None);
1820        assert_eq!(opts.port, Some(2222));
1821
1822        let opts = SshConnectionOptions::parse_command_line("user@example.com:2222")?;
1823        assert_eq!(opts.host, "example.com".into());
1824        assert_eq!(opts.username, Some("user".to_string()));
1825        assert_eq!(opts.port, Some(2222));
1826
1827        let opts = SshConnectionOptions::parse_command_line("user@192.168.1.1:2222")?;
1828        assert_eq!(opts.host, "192.168.1.1".into());
1829        assert_eq!(opts.username, Some("user".to_string()));
1830        assert_eq!(opts.port, Some(2222));
1831
1832        Ok(())
1833    }
1834}