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