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(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(&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 = ShellKind::Posix;
 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            // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
1142            debug_assert!(
1143                !arg.as_ref().contains('\n'),
1144                "multiline arguments do not work in all shells"
1145            );
1146            to_run.push(' ');
1147            to_run.push_str(&shell_kind.try_quote(arg.as_ref()).expect("shell quoting"));
1148        }
1149        let to_run = if shell_kind == ShellKind::Cmd {
1150            to_run // 'cd' prints the current directory in CMD
1151        } else {
1152            let separator = shell_kind.sequential_commands_separator();
1153            format!("cd{separator} {to_run}")
1154        };
1155        self.ssh_options(&mut command, true)
1156            .arg(self.connection_options.ssh_destination());
1157        if !allow_pseudo_tty {
1158            command.arg("-T");
1159        }
1160        command.arg(to_run);
1161        log::debug!("ssh {:?}", command);
1162        command
1163    }
1164
1165    async fn run_command(
1166        &self,
1167        shell_kind: ShellKind,
1168        program: &str,
1169        args: &[impl AsRef<str>],
1170        allow_pseudo_tty: bool,
1171    ) -> Result<String> {
1172        let mut command = self.ssh_command(shell_kind, program, args, allow_pseudo_tty);
1173        let output = command.output().await?;
1174        log::debug!("{:?}: {:?}", command, output);
1175        anyhow::ensure!(
1176            output.status.success(),
1177            "failed to run command {command:?}: {}",
1178            String::from_utf8_lossy(&output.stderr)
1179        );
1180        Ok(String::from_utf8_lossy(&output.stdout).to_string())
1181    }
1182
1183    fn ssh_options<'a>(
1184        &self,
1185        command: &'a mut process::Command,
1186        include_port_forwards: bool,
1187    ) -> &'a mut process::Command {
1188        let args = if include_port_forwards {
1189            self.connection_options.additional_args()
1190        } else {
1191            self.connection_options.additional_args_for_scp()
1192        };
1193
1194        let cmd = command
1195            .stdin(Stdio::piped())
1196            .stdout(Stdio::piped())
1197            .stderr(Stdio::piped())
1198            .args(args);
1199
1200        if cfg!(windows) {
1201            cmd.envs(self.envs.clone());
1202        }
1203        #[cfg(not(windows))]
1204        {
1205            cmd.args(["-o", "ControlMaster=no", "-o"])
1206                .arg(format!("ControlPath={}", self.socket_path.display()));
1207        }
1208        cmd
1209    }
1210
1211    // On Windows, we need to use `SSH_ASKPASS` to provide the password to ssh.
1212    // On Linux, we use the `ControlPath` option to create a socket file that ssh can use to
1213    fn ssh_args(&self) -> Vec<String> {
1214        let mut arguments = self.connection_options.additional_args();
1215        #[cfg(not(windows))]
1216        arguments.extend(vec![
1217            "-o".to_string(),
1218            "ControlMaster=no".to_string(),
1219            "-o".to_string(),
1220            format!("ControlPath={}", self.socket_path.display()),
1221            self.connection_options.ssh_destination(),
1222        ]);
1223        #[cfg(windows)]
1224        arguments.push(self.connection_options.ssh_destination());
1225        arguments
1226    }
1227
1228    async fn platform(&self, shell: ShellKind, is_windows: bool) -> Result<RemotePlatform> {
1229        if is_windows {
1230            self.platform_windows(shell).await
1231        } else {
1232            self.platform_posix(shell).await
1233        }
1234    }
1235
1236    async fn platform_posix(&self, shell: ShellKind) -> Result<RemotePlatform> {
1237        let output = self
1238            .run_command(shell, "uname", &["-sm"], false)
1239            .await
1240            .context("Failed to run 'uname -sm' to determine platform")?;
1241        parse_platform(&output)
1242    }
1243
1244    async fn platform_windows(&self, shell: ShellKind) -> Result<RemotePlatform> {
1245        let output = self
1246            .run_command(
1247                shell,
1248                "cmd.exe",
1249                &["/c", "echo", "%PROCESSOR_ARCHITECTURE%"],
1250                false,
1251            )
1252            .await
1253            .context(
1254                "Failed to run 'echo %PROCESSOR_ARCHITECTURE%' to determine Windows architecture",
1255            )?;
1256
1257        Ok(RemotePlatform {
1258            os: RemoteOs::Windows,
1259            arch: match output.trim() {
1260                "AMD64" => RemoteArch::X86_64,
1261                "ARM64" => RemoteArch::Aarch64,
1262                arch => anyhow::bail!(
1263                    "Prebuilt remote servers are not yet available for windows-{arch}. See https://zed.dev/docs/remote-development"
1264                ),
1265            },
1266        })
1267    }
1268
1269    /// Probes whether the remote host is running Windows.
1270    ///
1271    /// This is done by attempting to run a simple Windows-specific command.
1272    /// If it succeeds and returns Windows-like output, we assume it's Windows.
1273    async fn probe_is_windows(&self) -> bool {
1274        match self
1275            .run_command(ShellKind::Cmd, "cmd.exe", &["/c", "ver"], false)
1276            .await
1277        {
1278            // Windows 'ver' command outputs something like "Microsoft Windows [Version 10.0.19045.5011]"
1279            Ok(output) => output.trim().contains("indows"),
1280            Err(_) => false,
1281        }
1282    }
1283
1284    async fn shell(&self, is_windows: bool) -> String {
1285        if is_windows {
1286            self.shell_windows().await
1287        } else {
1288            self.shell_posix().await
1289        }
1290    }
1291
1292    async fn shell_posix(&self) -> String {
1293        const DEFAULT_SHELL: &str = "sh";
1294        match self
1295            .run_command(ShellKind::Posix, "sh", &["-c", "echo $SHELL"], false)
1296            .await
1297        {
1298            Ok(output) => parse_shell(&output, DEFAULT_SHELL),
1299            Err(e) => {
1300                log::error!("Failed to detect remote shell: {e}");
1301                DEFAULT_SHELL.to_owned()
1302            }
1303        }
1304    }
1305
1306    async fn shell_windows(&self) -> String {
1307        const DEFAULT_SHELL: &str = "cmd.exe";
1308
1309        // We detect the shell used by the SSH session by running the following command in PowerShell:
1310        // (Get-CimInstance Win32_Process -Filter "ProcessId = $((Get-CimInstance Win32_Process -Filter ProcessId=$PID).ParentProcessId)").Name
1311        // This prints the name of PowerShell's parent process (which will be the shell that SSH launched).
1312        // We pass it as a Base64 encoded string since we don't yet know how to correctly quote that command.
1313        // (We'd need to know what the shell is to do that...)
1314        match self
1315            .run_command(
1316                ShellKind::Cmd,
1317                "powershell",
1318                &[
1319                    "-E",
1320                    "KABHAGUAdAAtAEMAaQBtAEkAbgBzAHQAYQBuAGMAZQAgAFcAaQBuADMAMgBfAFAAcgBvAGMAZQBzAHMAIAAtAEYAaQBsAHQAZQByACAAIgBQAHIAbwBjAGUAcwBzAEkAZAAgAD0AIAAkACgAKABHAGUAdAAtAEMAaQBtAEkAbgBzAHQAYQBuAGMAZQAgAFcAaQBuADMAMgBfAFAAcgBvAGMAZQBzAHMAIAAtAEYAaQBsAHQAZQByACAAUAByAG8AYwBlAHMAcwBJAGQAPQAkAFAASQBEACkALgBQAGEAcgBlAG4AdABQAHIAbwBjAGUAcwBzAEkAZAApACIAKQAuAE4AYQBtAGUA",
1321                ],
1322                false,
1323            )
1324            .await
1325        {
1326            Ok(output) => parse_shell(&output, DEFAULT_SHELL),
1327            Err(e) => {
1328                log::error!("Failed to detect remote shell: {e}");
1329                DEFAULT_SHELL.to_owned()
1330            }
1331        }
1332    }
1333}
1334
1335fn parse_port_number(port_str: &str) -> Result<u16> {
1336    port_str
1337        .parse()
1338        .with_context(|| format!("parsing port number: {port_str}"))
1339}
1340
1341fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
1342    let parts: Vec<&str> = spec.split(':').collect();
1343
1344    match *parts {
1345        [a, b, c, d] => {
1346            let local_port = parse_port_number(b)?;
1347            let remote_port = parse_port_number(d)?;
1348
1349            Ok(SshPortForwardOption {
1350                local_host: Some(a.to_string()),
1351                local_port,
1352                remote_host: Some(c.to_string()),
1353                remote_port,
1354            })
1355        }
1356        [a, b, c] => {
1357            let local_port = parse_port_number(a)?;
1358            let remote_port = parse_port_number(c)?;
1359
1360            Ok(SshPortForwardOption {
1361                local_host: None,
1362                local_port,
1363                remote_host: Some(b.to_string()),
1364                remote_port,
1365            })
1366        }
1367        _ => anyhow::bail!("Invalid port forward format"),
1368    }
1369}
1370
1371impl SshConnectionOptions {
1372    pub fn parse_command_line(input: &str) -> Result<Self> {
1373        let input = input.trim_start_matches("ssh ");
1374        let mut hostname: Option<String> = None;
1375        let mut username: Option<String> = None;
1376        let mut port: Option<u16> = None;
1377        let mut args = Vec::new();
1378        let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
1379
1380        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
1381        const ALLOWED_OPTS: &[&str] = &[
1382            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
1383        ];
1384        const ALLOWED_ARGS: &[&str] = &[
1385            "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
1386            "-w",
1387        ];
1388
1389        let mut tokens = ShellKind::Posix
1390            .split(input)
1391            .context("invalid input")?
1392            .into_iter();
1393
1394        'outer: while let Some(arg) = tokens.next() {
1395            if ALLOWED_OPTS.contains(&(&arg as &str)) {
1396                args.push(arg.to_string());
1397                continue;
1398            }
1399            if arg == "-p" {
1400                port = tokens.next().and_then(|arg| arg.parse().ok());
1401                continue;
1402            } else if let Some(p) = arg.strip_prefix("-p") {
1403                port = p.parse().ok();
1404                continue;
1405            }
1406            if arg == "-l" {
1407                username = tokens.next();
1408                continue;
1409            } else if let Some(l) = arg.strip_prefix("-l") {
1410                username = Some(l.to_string());
1411                continue;
1412            }
1413            if arg == "-L" || arg.starts_with("-L") {
1414                let forward_spec = if arg == "-L" {
1415                    tokens.next()
1416                } else {
1417                    Some(arg.strip_prefix("-L").unwrap().to_string())
1418                };
1419
1420                if let Some(spec) = forward_spec {
1421                    port_forwards.push(parse_port_forward_spec(&spec)?);
1422                } else {
1423                    anyhow::bail!("Missing port forward format");
1424                }
1425            }
1426
1427            for a in ALLOWED_ARGS {
1428                if arg == *a {
1429                    args.push(arg);
1430                    if let Some(next) = tokens.next() {
1431                        args.push(next);
1432                    }
1433                    continue 'outer;
1434                } else if arg.starts_with(a) {
1435                    args.push(arg);
1436                    continue 'outer;
1437                }
1438            }
1439            if arg.starts_with("-") || hostname.is_some() {
1440                anyhow::bail!("unsupported argument: {:?}", arg);
1441            }
1442            let mut input = &arg as &str;
1443            // Destination might be: username1@username2@ip2@ip1
1444            if let Some((u, rest)) = input.rsplit_once('@') {
1445                input = rest;
1446                username = Some(u.to_string());
1447            }
1448
1449            // Handle port parsing, accounting for IPv6 addresses
1450            // IPv6 addresses can be: 2001:db8::1 or [2001:db8::1]:22
1451            if input.starts_with('[') {
1452                if let Some((rest, p)) = input.rsplit_once("]:") {
1453                    input = rest.strip_prefix('[').unwrap_or(rest);
1454                    port = p.parse().ok();
1455                } else if input.ends_with(']') {
1456                    input = input.strip_prefix('[').unwrap_or(input);
1457                    input = input.strip_suffix(']').unwrap_or(input);
1458                }
1459            } else if let Some((rest, p)) = input.rsplit_once(':')
1460                && !rest.contains(":")
1461            {
1462                input = rest;
1463                port = p.parse().ok();
1464            }
1465
1466            hostname = Some(input.to_string())
1467        }
1468
1469        let Some(hostname) = hostname else {
1470            anyhow::bail!("missing hostname");
1471        };
1472
1473        let port_forwards = match port_forwards.len() {
1474            0 => None,
1475            _ => Some(port_forwards),
1476        };
1477
1478        Ok(Self {
1479            host: hostname.into(),
1480            username,
1481            port,
1482            port_forwards,
1483            args: Some(args),
1484            password: None,
1485            nickname: None,
1486            upload_binary_over_ssh: false,
1487            connection_timeout: None,
1488        })
1489    }
1490
1491    pub fn ssh_destination(&self) -> String {
1492        let mut result = String::default();
1493        if let Some(username) = &self.username {
1494            // Username might be: username1@username2@ip2
1495            let username = urlencoding::encode(username);
1496            result.push_str(&username);
1497            result.push('@');
1498        }
1499
1500        result.push_str(&self.host.to_string());
1501        result
1502    }
1503
1504    pub fn additional_args_for_scp(&self) -> Vec<String> {
1505        self.args.iter().flatten().cloned().collect::<Vec<String>>()
1506    }
1507
1508    pub fn additional_args(&self) -> Vec<String> {
1509        let mut args = self.additional_args_for_scp();
1510
1511        if let Some(timeout) = self.connection_timeout {
1512            args.extend(["-o".to_string(), format!("ConnectTimeout={}", timeout)]);
1513        }
1514
1515        if let Some(port) = self.port {
1516            args.push("-p".to_string());
1517            args.push(port.to_string());
1518        }
1519
1520        if let Some(forwards) = &self.port_forwards {
1521            args.extend(forwards.iter().map(|pf| {
1522                let local_host = match &pf.local_host {
1523                    Some(host) => host,
1524                    None => "localhost",
1525                };
1526                let remote_host = match &pf.remote_host {
1527                    Some(host) => host,
1528                    None => "localhost",
1529                };
1530
1531                format!(
1532                    "-L{}:{}:{}:{}",
1533                    local_host, pf.local_port, remote_host, pf.remote_port
1534                )
1535            }));
1536        }
1537
1538        args
1539    }
1540
1541    fn scp_destination(&self) -> String {
1542        if let Some(username) = &self.username {
1543            format!("{}@{}", username, self.host.to_bracketed_string())
1544        } else {
1545            self.host.to_string()
1546        }
1547    }
1548
1549    pub fn connection_string(&self) -> String {
1550        let host = if let Some(port) = &self.port {
1551            format!("{}:{}", self.host.to_bracketed_string(), port)
1552        } else {
1553            self.host.to_string()
1554        };
1555
1556        if let Some(username) = &self.username {
1557            format!("{}@{}", username, host)
1558        } else {
1559            host
1560        }
1561    }
1562}
1563
1564fn build_command_posix(
1565    input_program: Option<String>,
1566    input_args: &[String],
1567    input_env: &HashMap<String, String>,
1568    working_dir: Option<String>,
1569    port_forward: Option<(u16, String, u16)>,
1570    ssh_env: HashMap<String, String>,
1571    ssh_path_style: PathStyle,
1572    ssh_shell: &str,
1573    ssh_shell_kind: ShellKind,
1574    ssh_args: Vec<String>,
1575    interactive: Interactive,
1576) -> Result<CommandTemplate> {
1577    use std::fmt::Write as _;
1578
1579    let mut exec = String::new();
1580    if let Some(working_dir) = working_dir {
1581        let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1582
1583        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
1584        // replace with something that works
1585        const TILDE_PREFIX: &'static str = "~/";
1586        if working_dir.starts_with(TILDE_PREFIX) {
1587            let working_dir = working_dir.trim_start_matches("~").trim_start_matches("/");
1588            write!(
1589                exec,
1590                "cd \"$HOME/{working_dir}\" {} ",
1591                ssh_shell_kind.sequential_and_commands_separator()
1592            )?;
1593        } else {
1594            write!(
1595                exec,
1596                "cd \"{working_dir}\" {} ",
1597                ssh_shell_kind.sequential_and_commands_separator()
1598            )?;
1599        }
1600    } else {
1601        write!(
1602            exec,
1603            "cd {} ",
1604            ssh_shell_kind.sequential_and_commands_separator()
1605        )?;
1606    };
1607    write!(exec, "exec env ")?;
1608
1609    for (k, v) in input_env.iter() {
1610        write!(
1611            exec,
1612            "{}={} ",
1613            k,
1614            ssh_shell_kind.try_quote(v).context("shell quoting")?
1615        )?;
1616    }
1617
1618    if let Some(input_program) = input_program {
1619        write!(
1620            exec,
1621            "{}",
1622            ssh_shell_kind
1623                .try_quote_prefix_aware(&input_program)
1624                .context("shell quoting")?
1625        )?;
1626        for arg in input_args {
1627            let arg = ssh_shell_kind.try_quote(&arg).context("shell quoting")?;
1628            write!(exec, " {}", &arg)?;
1629        }
1630    } else {
1631        write!(exec, "{ssh_shell} -l")?;
1632    };
1633
1634    let mut args = Vec::new();
1635    args.extend(ssh_args);
1636
1637    if let Some((local_port, host, remote_port)) = port_forward {
1638        args.push("-L".into());
1639        args.push(format!("{local_port}:{host}:{remote_port}"));
1640    }
1641
1642    // -q suppresses the "Connection to ... closed." message that SSH prints when
1643    // the connection terminates with -t (pseudo-terminal allocation)
1644    args.push("-q".into());
1645    match interactive {
1646        // -t forces pseudo-TTY allocation (for interactive use)
1647        Interactive::Yes => args.push("-t".into()),
1648        // -T disables pseudo-TTY allocation (for non-interactive piped stdio)
1649        Interactive::No => args.push("-T".into()),
1650    }
1651    args.push(exec);
1652
1653    Ok(CommandTemplate {
1654        program: "ssh".into(),
1655        args,
1656        env: ssh_env,
1657    })
1658}
1659
1660fn build_command_windows(
1661    input_program: Option<String>,
1662    input_args: &[String],
1663    _input_env: &HashMap<String, String>,
1664    working_dir: Option<String>,
1665    port_forward: Option<(u16, String, u16)>,
1666    ssh_env: HashMap<String, String>,
1667    ssh_path_style: PathStyle,
1668    ssh_shell: &str,
1669    _ssh_shell_kind: ShellKind,
1670    ssh_args: Vec<String>,
1671    interactive: Interactive,
1672) -> Result<CommandTemplate> {
1673    use base64::Engine as _;
1674    use std::fmt::Write as _;
1675
1676    let mut exec = String::new();
1677    let shell_kind = ShellKind::PowerShell;
1678
1679    if let Some(working_dir) = working_dir {
1680        let working_dir = RemotePathBuf::new(working_dir, ssh_path_style).to_string();
1681
1682        write!(
1683            exec,
1684            "Set-Location -Path {} {} ",
1685            shell_kind
1686                .try_quote(&working_dir)
1687                .context("shell quoting")?,
1688            shell_kind.sequential_and_commands_separator()
1689        )?;
1690    }
1691
1692    // Windows OpenSSH has an 8K character limit for command lines. Sending a lot of environment variables easily puts us over the limit.
1693    // Until we have a better solution for this, we just won't set environment variables for now.
1694    // for (k, v) in input_env.iter() {
1695    //     write!(
1696    //         exec,
1697    //         "$env:{}={} {} ",
1698    //         k,
1699    //         shell_kind.try_quote(v).context("shell quoting")?,
1700    //         shell_kind.sequential_and_commands_separator()
1701    //     )?;
1702    // }
1703
1704    if let Some(input_program) = input_program {
1705        write!(
1706            exec,
1707            "{}",
1708            shell_kind
1709                .try_quote_prefix_aware(&shell_kind.prepend_command_prefix(&input_program))
1710                .context("shell quoting")?
1711        )?;
1712        for arg in input_args {
1713            let arg = shell_kind.try_quote(arg).context("shell quoting")?;
1714            write!(exec, " {}", &arg)?;
1715        }
1716    } else {
1717        // Launch an interactive shell session
1718        write!(exec, "{ssh_shell}")?;
1719    };
1720
1721    let mut args = Vec::new();
1722    args.extend(ssh_args);
1723
1724    if let Some((local_port, host, remote_port)) = port_forward {
1725        args.push("-L".into());
1726        args.push(format!("{local_port}:{host}:{remote_port}"));
1727    }
1728
1729    // -q suppresses the "Connection to ... closed." message that SSH prints when
1730    // the connection terminates with -t (pseudo-terminal allocation)
1731    args.push("-q".into());
1732    match interactive {
1733        // -t forces pseudo-TTY allocation (for interactive use)
1734        Interactive::Yes => args.push("-t".into()),
1735        // -T disables pseudo-TTY allocation (for non-interactive piped stdio)
1736        Interactive::No => args.push("-T".into()),
1737    }
1738
1739    // Windows OpenSSH server incorrectly escapes the command string when the PTY is used.
1740    // The simplest way to work around this is to use a base64 encoded command, which doesn't require escaping.
1741    let utf16_bytes: Vec<u16> = exec.encode_utf16().collect();
1742    let byte_slice: Vec<u8> = utf16_bytes.iter().flat_map(|&u| u.to_le_bytes()).collect();
1743    let base64_encoded = base64::engine::general_purpose::STANDARD.encode(&byte_slice);
1744
1745    args.push(format!("powershell.exe -E {}", base64_encoded));
1746
1747    Ok(CommandTemplate {
1748        program: "ssh".into(),
1749        args,
1750        env: ssh_env,
1751    })
1752}
1753
1754#[cfg(test)]
1755mod tests {
1756    use super::*;
1757
1758    #[test]
1759    fn test_build_command() -> Result<()> {
1760        let mut input_env = HashMap::default();
1761        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1762        let mut env = HashMap::default();
1763        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1764
1765        // Test non-interactive command (interactive=false should use -T)
1766        let command = build_command_posix(
1767            Some("remote_program".to_string()),
1768            &["arg1".to_string(), "arg2".to_string()],
1769            &input_env,
1770            Some("~/work".to_string()),
1771            None,
1772            env.clone(),
1773            PathStyle::Posix,
1774            "/bin/bash",
1775            ShellKind::Posix,
1776            vec!["-o".to_string(), "ControlMaster=auto".to_string()],
1777            Interactive::No,
1778        )?;
1779        assert_eq!(command.program, "ssh");
1780        // Should contain -T for non-interactive
1781        assert!(command.args.iter().any(|arg| arg == "-T"));
1782        assert!(!command.args.iter().any(|arg| arg == "-t"));
1783
1784        // Test interactive command (interactive=true should use -t)
1785        let command = build_command_posix(
1786            Some("remote_program".to_string()),
1787            &["arg1".to_string(), "arg2".to_string()],
1788            &input_env,
1789            Some("~/work".to_string()),
1790            None,
1791            env.clone(),
1792            PathStyle::Posix,
1793            "/bin/fish",
1794            ShellKind::Fish,
1795            vec!["-p".to_string(), "2222".to_string()],
1796            Interactive::Yes,
1797        )?;
1798
1799        assert_eq!(command.program, "ssh");
1800        assert_eq!(
1801            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1802            [
1803                "-p",
1804                "2222",
1805                "-q",
1806                "-t",
1807                "cd \"$HOME/work\" && exec env INPUT_VA=val remote_program arg1 arg2"
1808            ]
1809        );
1810        assert_eq!(command.env, env);
1811
1812        let mut input_env = HashMap::default();
1813        input_env.insert("INPUT_VA".to_string(), "val".to_string());
1814        let mut env = HashMap::default();
1815        env.insert("SSH_VAR".to_string(), "ssh-val".to_string());
1816
1817        let command = build_command_posix(
1818            None,
1819            &[],
1820            &input_env,
1821            None,
1822            Some((1, "foo".to_owned(), 2)),
1823            env.clone(),
1824            PathStyle::Posix,
1825            "/bin/fish",
1826            ShellKind::Fish,
1827            vec!["-p".to_string(), "2222".to_string()],
1828            Interactive::Yes,
1829        )?;
1830
1831        assert_eq!(command.program, "ssh");
1832        assert_eq!(
1833            command.args.iter().map(String::as_str).collect::<Vec<_>>(),
1834            [
1835                "-p",
1836                "2222",
1837                "-L",
1838                "1:foo:2",
1839                "-q",
1840                "-t",
1841                "cd && exec env INPUT_VA=val /bin/fish -l"
1842            ]
1843        );
1844        assert_eq!(command.env, env);
1845
1846        Ok(())
1847    }
1848
1849    #[test]
1850    fn scp_args_exclude_port_forward_flags() {
1851        let options = SshConnectionOptions {
1852            host: "example.com".into(),
1853            args: Some(vec![
1854                "-p".to_string(),
1855                "2222".to_string(),
1856                "-o".to_string(),
1857                "StrictHostKeyChecking=no".to_string(),
1858            ]),
1859            port_forwards: Some(vec![SshPortForwardOption {
1860                local_host: Some("127.0.0.1".to_string()),
1861                local_port: 8080,
1862                remote_host: Some("127.0.0.1".to_string()),
1863                remote_port: 80,
1864            }]),
1865            ..Default::default()
1866        };
1867
1868        let ssh_args = options.additional_args();
1869        assert!(
1870            ssh_args.iter().any(|arg| arg.starts_with("-L")),
1871            "expected ssh args to include port-forward: {ssh_args:?}"
1872        );
1873
1874        let scp_args = options.additional_args_for_scp();
1875        assert_eq!(
1876            scp_args,
1877            vec![
1878                "-p".to_string(),
1879                "2222".to_string(),
1880                "-o".to_string(),
1881                "StrictHostKeyChecking=no".to_string(),
1882            ]
1883        );
1884    }
1885
1886    #[test]
1887    fn test_host_parsing() -> Result<()> {
1888        let opts = SshConnectionOptions::parse_command_line("user@2001:db8::1")?;
1889        assert_eq!(opts.host, "2001:db8::1".into());
1890        assert_eq!(opts.username, Some("user".to_string()));
1891        assert_eq!(opts.port, None);
1892
1893        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]:2222")?;
1894        assert_eq!(opts.host, "2001:db8::1".into());
1895        assert_eq!(opts.username, Some("user".to_string()));
1896        assert_eq!(opts.port, Some(2222));
1897
1898        let opts = SshConnectionOptions::parse_command_line("user@[2001:db8::1]")?;
1899        assert_eq!(opts.host, "2001:db8::1".into());
1900        assert_eq!(opts.username, Some("user".to_string()));
1901        assert_eq!(opts.port, None);
1902
1903        let opts = SshConnectionOptions::parse_command_line("2001:db8::1")?;
1904        assert_eq!(opts.host, "2001:db8::1".into());
1905        assert_eq!(opts.username, None);
1906        assert_eq!(opts.port, None);
1907
1908        let opts = SshConnectionOptions::parse_command_line("[2001:db8::1]:2222")?;
1909        assert_eq!(opts.host, "2001:db8::1".into());
1910        assert_eq!(opts.username, None);
1911        assert_eq!(opts.port, Some(2222));
1912
1913        let opts = SshConnectionOptions::parse_command_line("user@example.com:2222")?;
1914        assert_eq!(opts.host, "example.com".into());
1915        assert_eq!(opts.username, Some("user".to_string()));
1916        assert_eq!(opts.port, Some(2222));
1917
1918        let opts = SshConnectionOptions::parse_command_line("user@192.168.1.1:2222")?;
1919        assert_eq!(opts.host, "192.168.1.1".into());
1920        assert_eq!(opts.username, Some("user".to_string()));
1921        assert_eq!(opts.port, Some(2222));
1922
1923        Ok(())
1924    }
1925}