ssh_session.rs

   1use crate::{
   2    json_log::LogRecord,
   3    protocol::{
   4        MESSAGE_LEN_SIZE, MessageId, message_len_from_buffer, read_message_with_len, write_message,
   5    },
   6    proxy::ProxyLaunchError,
   7};
   8use anyhow::{Context as _, Result, anyhow};
   9use async_trait::async_trait;
  10use collections::HashMap;
  11use futures::{
  12    AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
  13    channel::{
  14        mpsc::{self, Sender, UnboundedReceiver, UnboundedSender},
  15        oneshot,
  16    },
  17    future::{BoxFuture, Shared},
  18    select, select_biased,
  19};
  20use gpui::{
  21    App, AppContext as _, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter, Global,
  22    SemanticVersion, Task, WeakEntity,
  23};
  24use itertools::Itertools;
  25use parking_lot::Mutex;
  26use paths;
  27use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
  28use rpc::{
  29    AnyProtoClient, EntityMessageSubscriber, ErrorExt, ProtoClient, ProtoMessageHandlerSet,
  30    RpcError,
  31    proto::{self, Envelope, EnvelopedMessage, PeerId, RequestMessage, build_typed_envelope},
  32};
  33use schemars::JsonSchema;
  34use serde::{Deserialize, Serialize};
  35use smol::{
  36    fs,
  37    process::{self, Child, Stdio},
  38};
  39use std::{
  40    any::TypeId,
  41    collections::VecDeque,
  42    fmt, iter,
  43    ops::ControlFlow,
  44    path::{Path, PathBuf},
  45    sync::{
  46        Arc, Weak,
  47        atomic::{AtomicU32, AtomicU64, Ordering::SeqCst},
  48    },
  49    time::{Duration, Instant},
  50};
  51use tempfile::TempDir;
  52use util::ResultExt;
  53
  54#[derive(
  55    Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
  56)]
  57pub struct SshProjectId(pub u64);
  58
  59#[derive(Clone)]
  60pub struct SshSocket {
  61    connection_options: SshConnectionOptions,
  62    socket_path: PathBuf,
  63}
  64
  65#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, JsonSchema)]
  66pub struct SshPortForwardOption {
  67    #[serde(skip_serializing_if = "Option::is_none")]
  68    pub local_host: Option<String>,
  69    pub local_port: u16,
  70    #[serde(skip_serializing_if = "Option::is_none")]
  71    pub remote_host: Option<String>,
  72    pub remote_port: u16,
  73}
  74
  75#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
  76pub struct SshConnectionOptions {
  77    pub host: String,
  78    pub username: Option<String>,
  79    pub port: Option<u16>,
  80    pub password: Option<String>,
  81    pub args: Option<Vec<String>>,
  82    pub port_forwards: Option<Vec<SshPortForwardOption>>,
  83
  84    pub nickname: Option<String>,
  85    pub upload_binary_over_ssh: bool,
  86}
  87
  88#[macro_export]
  89macro_rules! shell_script {
  90    ($fmt:expr, $($name:ident = $arg:expr),+ $(,)?) => {{
  91        format!(
  92            $fmt,
  93            $(
  94                $name = shlex::try_quote($arg).unwrap()
  95            ),+
  96        )
  97    }};
  98}
  99
 100fn parse_port_number(port_str: &str) -> Result<u16> {
 101    port_str
 102        .parse()
 103        .map_err(|e| anyhow!("Invalid port number: {}: {}", port_str, e))
 104}
 105
 106fn parse_port_forward_spec(spec: &str) -> Result<SshPortForwardOption> {
 107    let parts: Vec<&str> = spec.split(':').collect();
 108
 109    match parts.len() {
 110        4 => {
 111            let local_port = parse_port_number(parts[1])?;
 112            let remote_port = parse_port_number(parts[3])?;
 113
 114            Ok(SshPortForwardOption {
 115                local_host: Some(parts[0].to_string()),
 116                local_port,
 117                remote_host: Some(parts[2].to_string()),
 118                remote_port,
 119            })
 120        }
 121        3 => {
 122            let local_port = parse_port_number(parts[0])?;
 123            let remote_port = parse_port_number(parts[2])?;
 124
 125            Ok(SshPortForwardOption {
 126                local_host: None,
 127                local_port,
 128                remote_host: Some(parts[1].to_string()),
 129                remote_port,
 130            })
 131        }
 132        _ => anyhow::bail!("Invalid port forward format"),
 133    }
 134}
 135
 136impl SshConnectionOptions {
 137    pub fn parse_command_line(input: &str) -> Result<Self> {
 138        let input = input.trim_start_matches("ssh ");
 139        let mut hostname: Option<String> = None;
 140        let mut username: Option<String> = None;
 141        let mut port: Option<u16> = None;
 142        let mut args = Vec::new();
 143        let mut port_forwards: Vec<SshPortForwardOption> = Vec::new();
 144
 145        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
 146        const ALLOWED_OPTS: &[&str] = &[
 147            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
 148        ];
 149        const ALLOWED_ARGS: &[&str] = &[
 150            "-B", "-b", "-c", "-D", "-F", "-I", "-i", "-J", "-l", "-m", "-o", "-P", "-p", "-R",
 151            "-w",
 152        ];
 153
 154        let mut tokens = shlex::split(input)
 155            .ok_or_else(|| anyhow!("invalid input"))?
 156            .into_iter();
 157
 158        'outer: while let Some(arg) = tokens.next() {
 159            if ALLOWED_OPTS.contains(&(&arg as &str)) {
 160                args.push(arg.to_string());
 161                continue;
 162            }
 163            if arg == "-p" {
 164                port = tokens.next().and_then(|arg| arg.parse().ok());
 165                continue;
 166            } else if let Some(p) = arg.strip_prefix("-p") {
 167                port = p.parse().ok();
 168                continue;
 169            }
 170            if arg == "-l" {
 171                username = tokens.next();
 172                continue;
 173            } else if let Some(l) = arg.strip_prefix("-l") {
 174                username = Some(l.to_string());
 175                continue;
 176            }
 177            if arg == "-L" || arg.starts_with("-L") {
 178                let forward_spec = if arg == "-L" {
 179                    tokens.next()
 180                } else {
 181                    Some(arg.strip_prefix("-L").unwrap().to_string())
 182                };
 183
 184                if let Some(spec) = forward_spec {
 185                    port_forwards.push(parse_port_forward_spec(&spec)?);
 186                } else {
 187                    anyhow::bail!("Missing port forward format");
 188                }
 189            }
 190
 191            for a in ALLOWED_ARGS {
 192                if arg == *a {
 193                    args.push(arg);
 194                    if let Some(next) = tokens.next() {
 195                        args.push(next);
 196                    }
 197                    continue 'outer;
 198                } else if arg.starts_with(a) {
 199                    args.push(arg);
 200                    continue 'outer;
 201                }
 202            }
 203            if arg.starts_with("-") || hostname.is_some() {
 204                anyhow::bail!("unsupported argument: {:?}", arg);
 205            }
 206            let mut input = &arg as &str;
 207            // Destination might be: username1@username2@ip2@ip1
 208            if let Some((u, rest)) = input.rsplit_once('@') {
 209                input = rest;
 210                username = Some(u.to_string());
 211            }
 212            if let Some((rest, p)) = input.split_once(':') {
 213                input = rest;
 214                port = p.parse().ok()
 215            }
 216            hostname = Some(input.to_string())
 217        }
 218
 219        let Some(hostname) = hostname else {
 220            anyhow::bail!("missing hostname");
 221        };
 222
 223        let port_forwards = match port_forwards.len() {
 224            0 => None,
 225            _ => Some(port_forwards),
 226        };
 227
 228        Ok(Self {
 229            host: hostname.to_string(),
 230            username: username.clone(),
 231            port,
 232            port_forwards,
 233            args: Some(args),
 234            password: None,
 235            nickname: None,
 236            upload_binary_over_ssh: false,
 237        })
 238    }
 239
 240    pub fn ssh_url(&self) -> String {
 241        let mut result = String::from("ssh://");
 242        if let Some(username) = &self.username {
 243            // Username might be: username1@username2@ip2
 244            let username = urlencoding::encode(username);
 245            result.push_str(&username);
 246            result.push('@');
 247        }
 248        result.push_str(&self.host);
 249        if let Some(port) = self.port {
 250            result.push(':');
 251            result.push_str(&port.to_string());
 252        }
 253        result
 254    }
 255
 256    pub fn additional_args(&self) -> Vec<String> {
 257        let mut args = self.args.iter().flatten().cloned().collect::<Vec<String>>();
 258
 259        if let Some(forwards) = &self.port_forwards {
 260            args.extend(forwards.iter().map(|pf| {
 261                let local_host = match &pf.local_host {
 262                    Some(host) => host,
 263                    None => "localhost",
 264                };
 265                let remote_host = match &pf.remote_host {
 266                    Some(host) => host,
 267                    None => "localhost",
 268                };
 269
 270                format!(
 271                    "-L{}:{}:{}:{}",
 272                    local_host, pf.local_port, remote_host, pf.remote_port
 273                )
 274            }));
 275        }
 276
 277        args
 278    }
 279
 280    fn scp_url(&self) -> String {
 281        if let Some(username) = &self.username {
 282            format!("{}@{}", username, self.host)
 283        } else {
 284            self.host.clone()
 285        }
 286    }
 287
 288    pub fn connection_string(&self) -> String {
 289        let host = if let Some(username) = &self.username {
 290            format!("{}@{}", username, self.host)
 291        } else {
 292            self.host.clone()
 293        };
 294        if let Some(port) = &self.port {
 295            format!("{}:{}", host, port)
 296        } else {
 297            host
 298        }
 299    }
 300}
 301
 302#[derive(Copy, Clone, Debug)]
 303pub struct SshPlatform {
 304    pub os: &'static str,
 305    pub arch: &'static str,
 306}
 307
 308impl SshPlatform {
 309    pub fn triple(&self) -> Option<String> {
 310        Some(format!(
 311            "{}-{}",
 312            self.arch,
 313            match self.os {
 314                "linux" => "unknown-linux-gnu",
 315                "macos" => "apple-darwin",
 316                _ => return None,
 317            }
 318        ))
 319    }
 320}
 321
 322pub trait SshClientDelegate: Send + Sync {
 323    fn ask_password(&self, prompt: String, tx: oneshot::Sender<String>, cx: &mut AsyncApp);
 324    fn get_download_params(
 325        &self,
 326        platform: SshPlatform,
 327        release_channel: ReleaseChannel,
 328        version: Option<SemanticVersion>,
 329        cx: &mut AsyncApp,
 330    ) -> Task<Result<Option<(String, String)>>>;
 331
 332    fn download_server_binary_locally(
 333        &self,
 334        platform: SshPlatform,
 335        release_channel: ReleaseChannel,
 336        version: Option<SemanticVersion>,
 337        cx: &mut AsyncApp,
 338    ) -> Task<Result<PathBuf>>;
 339    fn set_status(&self, status: Option<&str>, cx: &mut AsyncApp);
 340}
 341
 342impl SshSocket {
 343    // :WARNING: ssh unquotes arguments when executing on the remote :WARNING:
 344    // e.g. $ ssh host sh -c 'ls -l' is equivalent to $ ssh host sh -c ls -l
 345    // and passes -l as an argument to sh, not to ls.
 346    // Furthermore, some setups (e.g. Coder) will change directory when SSH'ing
 347    // into a machine. You must use `cd` to get back to $HOME.
 348    // You need to do it like this: $ ssh host "cd; sh -c 'ls -l /tmp'"
 349    fn ssh_command(&self, program: &str, args: &[&str]) -> process::Command {
 350        let mut command = util::command::new_smol_command("ssh");
 351        let to_run = iter::once(&program)
 352            .chain(args.iter())
 353            .map(|token| {
 354                // We're trying to work with: sh, bash, zsh, fish, tcsh, ...?
 355                debug_assert!(
 356                    !token.contains('\n'),
 357                    "multiline arguments do not work in all shells"
 358                );
 359                shlex::try_quote(token).unwrap()
 360            })
 361            .join(" ");
 362        let to_run = format!("cd; {to_run}");
 363        log::debug!("ssh {} {:?}", self.connection_options.ssh_url(), to_run);
 364        self.ssh_options(&mut command)
 365            .arg(self.connection_options.ssh_url())
 366            .arg(to_run);
 367        command
 368    }
 369
 370    async fn run_command(&self, program: &str, args: &[&str]) -> Result<String> {
 371        let output = self.ssh_command(program, args).output().await?;
 372        if output.status.success() {
 373            Ok(String::from_utf8_lossy(&output.stdout).to_string())
 374        } else {
 375            Err(anyhow!(
 376                "failed to run command: {}",
 377                String::from_utf8_lossy(&output.stderr)
 378            ))
 379        }
 380    }
 381
 382    fn ssh_options<'a>(&self, command: &'a mut process::Command) -> &'a mut process::Command {
 383        command
 384            .stdin(Stdio::piped())
 385            .stdout(Stdio::piped())
 386            .stderr(Stdio::piped())
 387            .args(["-o", "ControlMaster=no", "-o"])
 388            .arg(format!("ControlPath={}", self.socket_path.display()))
 389    }
 390
 391    fn ssh_args(&self) -> Vec<String> {
 392        vec![
 393            "-o".to_string(),
 394            "ControlMaster=no".to_string(),
 395            "-o".to_string(),
 396            format!("ControlPath={}", self.socket_path.display()),
 397            self.connection_options.ssh_url(),
 398        ]
 399    }
 400}
 401
 402const MAX_MISSED_HEARTBEATS: usize = 5;
 403const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
 404const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(5);
 405
 406const MAX_RECONNECT_ATTEMPTS: usize = 3;
 407
 408enum State {
 409    Connecting,
 410    Connected {
 411        ssh_connection: Arc<dyn RemoteConnection>,
 412        delegate: Arc<dyn SshClientDelegate>,
 413
 414        multiplex_task: Task<Result<()>>,
 415        heartbeat_task: Task<Result<()>>,
 416    },
 417    HeartbeatMissed {
 418        missed_heartbeats: usize,
 419
 420        ssh_connection: Arc<dyn RemoteConnection>,
 421        delegate: Arc<dyn SshClientDelegate>,
 422
 423        multiplex_task: Task<Result<()>>,
 424        heartbeat_task: Task<Result<()>>,
 425    },
 426    Reconnecting,
 427    ReconnectFailed {
 428        ssh_connection: Arc<dyn RemoteConnection>,
 429        delegate: Arc<dyn SshClientDelegate>,
 430
 431        error: anyhow::Error,
 432        attempts: usize,
 433    },
 434    ReconnectExhausted,
 435    ServerNotRunning,
 436}
 437
 438impl fmt::Display for State {
 439    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 440        match self {
 441            Self::Connecting => write!(f, "connecting"),
 442            Self::Connected { .. } => write!(f, "connected"),
 443            Self::Reconnecting => write!(f, "reconnecting"),
 444            Self::ReconnectFailed { .. } => write!(f, "reconnect failed"),
 445            Self::ReconnectExhausted => write!(f, "reconnect exhausted"),
 446            Self::HeartbeatMissed { .. } => write!(f, "heartbeat missed"),
 447            Self::ServerNotRunning { .. } => write!(f, "server not running"),
 448        }
 449    }
 450}
 451
 452impl State {
 453    fn ssh_connection(&self) -> Option<&dyn RemoteConnection> {
 454        match self {
 455            Self::Connected { ssh_connection, .. } => Some(ssh_connection.as_ref()),
 456            Self::HeartbeatMissed { ssh_connection, .. } => Some(ssh_connection.as_ref()),
 457            Self::ReconnectFailed { ssh_connection, .. } => Some(ssh_connection.as_ref()),
 458            _ => None,
 459        }
 460    }
 461
 462    fn can_reconnect(&self) -> bool {
 463        match self {
 464            Self::Connected { .. }
 465            | Self::HeartbeatMissed { .. }
 466            | Self::ReconnectFailed { .. } => true,
 467            State::Connecting
 468            | State::Reconnecting
 469            | State::ReconnectExhausted
 470            | State::ServerNotRunning => false,
 471        }
 472    }
 473
 474    fn is_reconnect_failed(&self) -> bool {
 475        matches!(self, Self::ReconnectFailed { .. })
 476    }
 477
 478    fn is_reconnect_exhausted(&self) -> bool {
 479        matches!(self, Self::ReconnectExhausted { .. })
 480    }
 481
 482    fn is_server_not_running(&self) -> bool {
 483        matches!(self, Self::ServerNotRunning)
 484    }
 485
 486    fn is_reconnecting(&self) -> bool {
 487        matches!(self, Self::Reconnecting { .. })
 488    }
 489
 490    fn heartbeat_recovered(self) -> Self {
 491        match self {
 492            Self::HeartbeatMissed {
 493                ssh_connection,
 494                delegate,
 495                multiplex_task,
 496                heartbeat_task,
 497                ..
 498            } => Self::Connected {
 499                ssh_connection,
 500                delegate,
 501                multiplex_task,
 502                heartbeat_task,
 503            },
 504            _ => self,
 505        }
 506    }
 507
 508    fn heartbeat_missed(self) -> Self {
 509        match self {
 510            Self::Connected {
 511                ssh_connection,
 512                delegate,
 513                multiplex_task,
 514                heartbeat_task,
 515            } => Self::HeartbeatMissed {
 516                missed_heartbeats: 1,
 517                ssh_connection,
 518                delegate,
 519                multiplex_task,
 520                heartbeat_task,
 521            },
 522            Self::HeartbeatMissed {
 523                missed_heartbeats,
 524                ssh_connection,
 525                delegate,
 526                multiplex_task,
 527                heartbeat_task,
 528            } => Self::HeartbeatMissed {
 529                missed_heartbeats: missed_heartbeats + 1,
 530                ssh_connection,
 531                delegate,
 532                multiplex_task,
 533                heartbeat_task,
 534            },
 535            _ => self,
 536        }
 537    }
 538}
 539
 540/// The state of the ssh connection.
 541#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 542pub enum ConnectionState {
 543    Connecting,
 544    Connected,
 545    HeartbeatMissed,
 546    Reconnecting,
 547    Disconnected,
 548}
 549
 550impl From<&State> for ConnectionState {
 551    fn from(value: &State) -> Self {
 552        match value {
 553            State::Connecting => Self::Connecting,
 554            State::Connected { .. } => Self::Connected,
 555            State::Reconnecting | State::ReconnectFailed { .. } => Self::Reconnecting,
 556            State::HeartbeatMissed { .. } => Self::HeartbeatMissed,
 557            State::ReconnectExhausted => Self::Disconnected,
 558            State::ServerNotRunning => Self::Disconnected,
 559        }
 560    }
 561}
 562
 563pub struct SshRemoteClient {
 564    client: Arc<ChannelClient>,
 565    unique_identifier: String,
 566    connection_options: SshConnectionOptions,
 567    state: Arc<Mutex<Option<State>>>,
 568}
 569
 570#[derive(Debug)]
 571pub enum SshRemoteEvent {
 572    Disconnected,
 573}
 574
 575impl EventEmitter<SshRemoteEvent> for SshRemoteClient {}
 576
 577// Identifies the socket on the remote server so that reconnects
 578// can re-join the same project.
 579pub enum ConnectionIdentifier {
 580    Setup(u64),
 581    Workspace(i64),
 582}
 583
 584static NEXT_ID: AtomicU64 = AtomicU64::new(1);
 585
 586impl ConnectionIdentifier {
 587    pub fn setup() -> Self {
 588        Self::Setup(NEXT_ID.fetch_add(1, SeqCst))
 589    }
 590    // This string gets used in a socket name, and so must be relatively short.
 591    // The total length of:
 592    //   /home/{username}/.local/share/zed/server_state/{name}/stdout.sock
 593    // Must be less than about 100 characters
 594    //   https://unix.stackexchange.com/questions/367008/why-is-socket-path-length-limited-to-a-hundred-chars
 595    // So our strings should be at most 20 characters or so.
 596    fn to_string(&self, cx: &App) -> String {
 597        let identifier_prefix = match ReleaseChannel::global(cx) {
 598            ReleaseChannel::Stable => "".to_string(),
 599            release_channel => format!("{}-", release_channel.dev_name()),
 600        };
 601        match self {
 602            Self::Setup(setup_id) => format!("{identifier_prefix}setup-{setup_id}"),
 603            Self::Workspace(workspace_id) => {
 604                format!("{identifier_prefix}workspace-{workspace_id}",)
 605            }
 606        }
 607    }
 608}
 609
 610impl SshRemoteClient {
 611    pub fn new(
 612        unique_identifier: ConnectionIdentifier,
 613        connection_options: SshConnectionOptions,
 614        cancellation: oneshot::Receiver<()>,
 615        delegate: Arc<dyn SshClientDelegate>,
 616        cx: &mut App,
 617    ) -> Task<Result<Option<Entity<Self>>>> {
 618        let unique_identifier = unique_identifier.to_string(cx);
 619        cx.spawn(async move |cx| {
 620            let success = Box::pin(async move {
 621                let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 622                let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 623                let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 624
 625                let client =
 626                    cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "client"))?;
 627                let this = cx.new(|_| Self {
 628                    client: client.clone(),
 629                    unique_identifier: unique_identifier.clone(),
 630                    connection_options: connection_options.clone(),
 631                    state: Arc::new(Mutex::new(Some(State::Connecting))),
 632                })?;
 633
 634                let ssh_connection = cx
 635                    .update(|cx| {
 636                        cx.update_default_global(|pool: &mut ConnectionPool, cx| {
 637                            pool.connect(connection_options, &delegate, cx)
 638                        })
 639                    })?
 640                    .await
 641                    .map_err(|e| e.cloned())?;
 642
 643                let io_task = ssh_connection.start_proxy(
 644                    unique_identifier,
 645                    false,
 646                    incoming_tx,
 647                    outgoing_rx,
 648                    connection_activity_tx,
 649                    delegate.clone(),
 650                    cx,
 651                );
 652
 653                let multiplex_task = Self::monitor(this.downgrade(), io_task, &cx);
 654
 655                if let Err(error) = client.ping(HEARTBEAT_TIMEOUT).await {
 656                    log::error!("failed to establish connection: {}", error);
 657                    return Err(error);
 658                }
 659
 660                let heartbeat_task = Self::heartbeat(this.downgrade(), connection_activity_rx, cx);
 661
 662                this.update(cx, |this, _| {
 663                    *this.state.lock() = Some(State::Connected {
 664                        ssh_connection,
 665                        delegate,
 666                        multiplex_task,
 667                        heartbeat_task,
 668                    });
 669                })?;
 670
 671                Ok(Some(this))
 672            });
 673
 674            select! {
 675                _ = cancellation.fuse() => {
 676                    Ok(None)
 677                }
 678                result = success.fuse() =>  result
 679            }
 680        })
 681    }
 682
 683    pub fn shutdown_processes<T: RequestMessage>(
 684        &self,
 685        shutdown_request: Option<T>,
 686    ) -> Option<impl Future<Output = ()> + use<T>> {
 687        let state = self.state.lock().take()?;
 688        log::info!("shutting down ssh processes");
 689
 690        let State::Connected {
 691            multiplex_task,
 692            heartbeat_task,
 693            ssh_connection,
 694            delegate,
 695        } = state
 696        else {
 697            return None;
 698        };
 699
 700        let client = self.client.clone();
 701
 702        Some(async move {
 703            if let Some(shutdown_request) = shutdown_request {
 704                client.send(shutdown_request).log_err();
 705                // We wait 50ms instead of waiting for a response, because
 706                // waiting for a response would require us to wait on the main thread
 707                // which we want to avoid in an `on_app_quit` callback.
 708                smol::Timer::after(Duration::from_millis(50)).await;
 709            }
 710
 711            // Drop `multiplex_task` because it owns our ssh_proxy_process, which is a
 712            // child of master_process.
 713            drop(multiplex_task);
 714            // Now drop the rest of state, which kills master process.
 715            drop(heartbeat_task);
 716            drop(ssh_connection);
 717            drop(delegate);
 718        })
 719    }
 720
 721    fn reconnect(&mut self, cx: &mut Context<Self>) -> Result<()> {
 722        let mut lock = self.state.lock();
 723
 724        let can_reconnect = lock
 725            .as_ref()
 726            .map(|state| state.can_reconnect())
 727            .unwrap_or(false);
 728        if !can_reconnect {
 729            let error = if let Some(state) = lock.as_ref() {
 730                format!("invalid state, cannot reconnect while in state {state}")
 731            } else {
 732                "no state set".to_string()
 733            };
 734            log::info!("aborting reconnect, because not in state that allows reconnecting");
 735            return Err(anyhow!(error));
 736        }
 737
 738        let state = lock.take().unwrap();
 739        let (attempts, ssh_connection, delegate) = match state {
 740            State::Connected {
 741                ssh_connection,
 742                delegate,
 743                multiplex_task,
 744                heartbeat_task,
 745            }
 746            | State::HeartbeatMissed {
 747                ssh_connection,
 748                delegate,
 749                multiplex_task,
 750                heartbeat_task,
 751                ..
 752            } => {
 753                drop(multiplex_task);
 754                drop(heartbeat_task);
 755                (0, ssh_connection, delegate)
 756            }
 757            State::ReconnectFailed {
 758                attempts,
 759                ssh_connection,
 760                delegate,
 761                ..
 762            } => (attempts, ssh_connection, delegate),
 763            State::Connecting
 764            | State::Reconnecting
 765            | State::ReconnectExhausted
 766            | State::ServerNotRunning => unreachable!(),
 767        };
 768
 769        let attempts = attempts + 1;
 770        if attempts > MAX_RECONNECT_ATTEMPTS {
 771            log::error!(
 772                "Failed to reconnect to after {} attempts, giving up",
 773                MAX_RECONNECT_ATTEMPTS
 774            );
 775            drop(lock);
 776            self.set_state(State::ReconnectExhausted, cx);
 777            return Ok(());
 778        }
 779        drop(lock);
 780
 781        self.set_state(State::Reconnecting, cx);
 782
 783        log::info!("Trying to reconnect to ssh server... Attempt {}", attempts);
 784
 785        let unique_identifier = self.unique_identifier.clone();
 786        let client = self.client.clone();
 787        let reconnect_task = cx.spawn(async move |this, cx| {
 788            macro_rules! failed {
 789                ($error:expr, $attempts:expr, $ssh_connection:expr, $delegate:expr) => {
 790                    return State::ReconnectFailed {
 791                        error: anyhow!($error),
 792                        attempts: $attempts,
 793                        ssh_connection: $ssh_connection,
 794                        delegate: $delegate,
 795                    };
 796                };
 797            }
 798
 799            if let Err(error) = ssh_connection
 800                .kill()
 801                .await
 802                .context("Failed to kill ssh process")
 803            {
 804                failed!(error, attempts, ssh_connection, delegate);
 805            };
 806
 807            let connection_options = ssh_connection.connection_options();
 808
 809            let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 810            let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 811            let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 812
 813            let (ssh_connection, io_task) = match async {
 814                let ssh_connection = cx
 815                    .update_global(|pool: &mut ConnectionPool, cx| {
 816                        pool.connect(connection_options, &delegate, cx)
 817                    })?
 818                    .await
 819                    .map_err(|error| error.cloned())?;
 820
 821                let io_task = ssh_connection.start_proxy(
 822                    unique_identifier,
 823                    true,
 824                    incoming_tx,
 825                    outgoing_rx,
 826                    connection_activity_tx,
 827                    delegate.clone(),
 828                    cx,
 829                );
 830                anyhow::Ok((ssh_connection, io_task))
 831            }
 832            .await
 833            {
 834                Ok((ssh_connection, io_task)) => (ssh_connection, io_task),
 835                Err(error) => {
 836                    failed!(error, attempts, ssh_connection, delegate);
 837                }
 838            };
 839
 840            let multiplex_task = Self::monitor(this.clone(), io_task, &cx);
 841            client.reconnect(incoming_rx, outgoing_tx, &cx);
 842
 843            if let Err(error) = client.resync(HEARTBEAT_TIMEOUT).await {
 844                failed!(error, attempts, ssh_connection, delegate);
 845            };
 846
 847            State::Connected {
 848                ssh_connection,
 849                delegate,
 850                multiplex_task,
 851                heartbeat_task: Self::heartbeat(this.clone(), connection_activity_rx, cx),
 852            }
 853        });
 854
 855        cx.spawn(async move |this, cx| {
 856            let new_state = reconnect_task.await;
 857            this.update(cx, |this, cx| {
 858                this.try_set_state(cx, |old_state| {
 859                    if old_state.is_reconnecting() {
 860                        match &new_state {
 861                            State::Connecting
 862                            | State::Reconnecting { .. }
 863                            | State::HeartbeatMissed { .. }
 864                            | State::ServerNotRunning => {}
 865                            State::Connected { .. } => {
 866                                log::info!("Successfully reconnected");
 867                            }
 868                            State::ReconnectFailed {
 869                                error, attempts, ..
 870                            } => {
 871                                log::error!(
 872                                    "Reconnect attempt {} failed: {:?}. Starting new attempt...",
 873                                    attempts,
 874                                    error
 875                                );
 876                            }
 877                            State::ReconnectExhausted => {
 878                                log::error!("Reconnect attempt failed and all attempts exhausted");
 879                            }
 880                        }
 881                        Some(new_state)
 882                    } else {
 883                        None
 884                    }
 885                });
 886
 887                if this.state_is(State::is_reconnect_failed) {
 888                    this.reconnect(cx)
 889                } else if this.state_is(State::is_reconnect_exhausted) {
 890                    Ok(())
 891                } else {
 892                    log::debug!("State has transition from Reconnecting into new state while attempting reconnect.");
 893                    Ok(())
 894                }
 895            })
 896        })
 897        .detach_and_log_err(cx);
 898
 899        Ok(())
 900    }
 901
 902    fn heartbeat(
 903        this: WeakEntity<Self>,
 904        mut connection_activity_rx: mpsc::Receiver<()>,
 905        cx: &mut AsyncApp,
 906    ) -> Task<Result<()>> {
 907        let Ok(client) = this.update(cx, |this, _| this.client.clone()) else {
 908            return Task::ready(Err(anyhow!("SshRemoteClient lost")));
 909        };
 910
 911        cx.spawn(async move |cx| {
 912                let mut missed_heartbeats = 0;
 913
 914                let keepalive_timer = cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse();
 915                futures::pin_mut!(keepalive_timer);
 916
 917                loop {
 918                    select_biased! {
 919                        result = connection_activity_rx.next().fuse() => {
 920                            if result.is_none() {
 921                                log::warn!("ssh heartbeat: connection activity channel has been dropped. stopping.");
 922                                return Ok(());
 923                            }
 924
 925                            if missed_heartbeats != 0 {
 926                                missed_heartbeats = 0;
 927                                this.update(cx, |this, mut cx| {
 928                                    this.handle_heartbeat_result(missed_heartbeats, &mut cx)
 929                                })?;
 930                            }
 931                        }
 932                        _ = keepalive_timer => {
 933                            log::debug!("Sending heartbeat to server...");
 934
 935                            let result = select_biased! {
 936                                _ = connection_activity_rx.next().fuse() => {
 937                                    Ok(())
 938                                }
 939                                ping_result = client.ping(HEARTBEAT_TIMEOUT).fuse() => {
 940                                    ping_result
 941                                }
 942                            };
 943
 944                            if result.is_err() {
 945                                missed_heartbeats += 1;
 946                                log::warn!(
 947                                    "No heartbeat from server after {:?}. Missed heartbeat {} out of {}.",
 948                                    HEARTBEAT_TIMEOUT,
 949                                    missed_heartbeats,
 950                                    MAX_MISSED_HEARTBEATS
 951                                );
 952                            } else if missed_heartbeats != 0 {
 953                                missed_heartbeats = 0;
 954                            } else {
 955                                continue;
 956                            }
 957
 958                            let result = this.update(cx, |this, mut cx| {
 959                                this.handle_heartbeat_result(missed_heartbeats, &mut cx)
 960                            })?;
 961                            if result.is_break() {
 962                                return Ok(());
 963                            }
 964                        }
 965                    }
 966
 967                    keepalive_timer.set(cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse());
 968                }
 969
 970        })
 971    }
 972
 973    fn handle_heartbeat_result(
 974        &mut self,
 975        missed_heartbeats: usize,
 976        cx: &mut Context<Self>,
 977    ) -> ControlFlow<()> {
 978        let state = self.state.lock().take().unwrap();
 979        let next_state = if missed_heartbeats > 0 {
 980            state.heartbeat_missed()
 981        } else {
 982            state.heartbeat_recovered()
 983        };
 984
 985        self.set_state(next_state, cx);
 986
 987        if missed_heartbeats >= MAX_MISSED_HEARTBEATS {
 988            log::error!(
 989                "Missed last {} heartbeats. Reconnecting...",
 990                missed_heartbeats
 991            );
 992
 993            self.reconnect(cx)
 994                .context("failed to start reconnect process after missing heartbeats")
 995                .log_err();
 996            ControlFlow::Break(())
 997        } else {
 998            ControlFlow::Continue(())
 999        }
1000    }
1001
1002    fn monitor(
1003        this: WeakEntity<Self>,
1004        io_task: Task<Result<i32>>,
1005        cx: &AsyncApp,
1006    ) -> Task<Result<()>> {
1007        cx.spawn(async move |cx| {
1008            let result = io_task.await;
1009
1010            match result {
1011                Ok(exit_code) => {
1012                    if let Some(error) = ProxyLaunchError::from_exit_code(exit_code) {
1013                        match error {
1014                            ProxyLaunchError::ServerNotRunning => {
1015                                log::error!("failed to reconnect because server is not running");
1016                                this.update(cx, |this, cx| {
1017                                    this.set_state(State::ServerNotRunning, cx);
1018                                })?;
1019                            }
1020                        }
1021                    } else if exit_code > 0 {
1022                        log::error!("proxy process terminated unexpectedly");
1023                        this.update(cx, |this, cx| {
1024                            this.reconnect(cx).ok();
1025                        })?;
1026                    }
1027                }
1028                Err(error) => {
1029                    log::warn!("ssh io task died with error: {:?}. reconnecting...", error);
1030                    this.update(cx, |this, cx| {
1031                        this.reconnect(cx).ok();
1032                    })?;
1033                }
1034            }
1035
1036            Ok(())
1037        })
1038    }
1039
1040    fn state_is(&self, check: impl FnOnce(&State) -> bool) -> bool {
1041        self.state.lock().as_ref().map_or(false, check)
1042    }
1043
1044    fn try_set_state(&self, cx: &mut Context<Self>, map: impl FnOnce(&State) -> Option<State>) {
1045        let mut lock = self.state.lock();
1046        let new_state = lock.as_ref().and_then(map);
1047
1048        if let Some(new_state) = new_state {
1049            lock.replace(new_state);
1050            cx.notify();
1051        }
1052    }
1053
1054    fn set_state(&self, state: State, cx: &mut Context<Self>) {
1055        log::info!("setting state to '{}'", &state);
1056
1057        let is_reconnect_exhausted = state.is_reconnect_exhausted();
1058        let is_server_not_running = state.is_server_not_running();
1059        self.state.lock().replace(state);
1060
1061        if is_reconnect_exhausted || is_server_not_running {
1062            cx.emit(SshRemoteEvent::Disconnected);
1063        }
1064        cx.notify();
1065    }
1066
1067    pub fn subscribe_to_entity<E: 'static>(&self, remote_id: u64, entity: &Entity<E>) {
1068        self.client.subscribe_to_entity(remote_id, entity);
1069    }
1070
1071    pub fn ssh_args(&self) -> Option<Vec<String>> {
1072        self.state
1073            .lock()
1074            .as_ref()
1075            .and_then(|state| state.ssh_connection())
1076            .map(|ssh_connection| ssh_connection.ssh_args())
1077    }
1078
1079    pub fn upload_directory(
1080        &self,
1081        src_path: PathBuf,
1082        dest_path: PathBuf,
1083        cx: &App,
1084    ) -> Task<Result<()>> {
1085        let state = self.state.lock();
1086        let Some(connection) = state.as_ref().and_then(|state| state.ssh_connection()) else {
1087            return Task::ready(Err(anyhow!("no ssh connection")));
1088        };
1089        connection.upload_directory(src_path, dest_path, cx)
1090    }
1091
1092    pub fn proto_client(&self) -> AnyProtoClient {
1093        self.client.clone().into()
1094    }
1095
1096    pub fn connection_string(&self) -> String {
1097        self.connection_options.connection_string()
1098    }
1099
1100    pub fn connection_options(&self) -> SshConnectionOptions {
1101        self.connection_options.clone()
1102    }
1103
1104    pub fn connection_state(&self) -> ConnectionState {
1105        self.state
1106            .lock()
1107            .as_ref()
1108            .map(ConnectionState::from)
1109            .unwrap_or(ConnectionState::Disconnected)
1110    }
1111
1112    pub fn is_disconnected(&self) -> bool {
1113        self.connection_state() == ConnectionState::Disconnected
1114    }
1115
1116    #[cfg(any(test, feature = "test-support"))]
1117    pub fn simulate_disconnect(&self, client_cx: &mut App) -> Task<()> {
1118        let opts = self.connection_options();
1119        client_cx.spawn(async move |cx| {
1120            let connection = cx
1121                .update_global(|c: &mut ConnectionPool, _| {
1122                    if let Some(ConnectionPoolEntry::Connecting(c)) = c.connections.get(&opts) {
1123                        c.clone()
1124                    } else {
1125                        panic!("missing test connection")
1126                    }
1127                })
1128                .unwrap()
1129                .await
1130                .unwrap();
1131
1132            connection.simulate_disconnect(&cx);
1133        })
1134    }
1135
1136    #[cfg(any(test, feature = "test-support"))]
1137    pub fn fake_server(
1138        client_cx: &mut gpui::TestAppContext,
1139        server_cx: &mut gpui::TestAppContext,
1140    ) -> (SshConnectionOptions, Arc<ChannelClient>) {
1141        let port = client_cx
1142            .update(|cx| cx.default_global::<ConnectionPool>().connections.len() as u16 + 1);
1143        let opts = SshConnectionOptions {
1144            host: "<fake>".to_string(),
1145            port: Some(port),
1146            ..Default::default()
1147        };
1148        let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
1149        let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
1150        let server_client =
1151            server_cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "fake-server"));
1152        let connection: Arc<dyn RemoteConnection> = Arc::new(fake::FakeRemoteConnection {
1153            connection_options: opts.clone(),
1154            server_cx: fake::SendableCx::new(server_cx),
1155            server_channel: server_client.clone(),
1156        });
1157
1158        client_cx.update(|cx| {
1159            cx.update_default_global(|c: &mut ConnectionPool, cx| {
1160                c.connections.insert(
1161                    opts.clone(),
1162                    ConnectionPoolEntry::Connecting(
1163                        cx.background_spawn({
1164                            let connection = connection.clone();
1165                            async move { Ok(connection.clone()) }
1166                        })
1167                        .shared(),
1168                    ),
1169                );
1170            })
1171        });
1172
1173        (opts, server_client)
1174    }
1175
1176    #[cfg(any(test, feature = "test-support"))]
1177    pub async fn fake_client(
1178        opts: SshConnectionOptions,
1179        client_cx: &mut gpui::TestAppContext,
1180    ) -> Entity<Self> {
1181        let (_tx, rx) = oneshot::channel();
1182        client_cx
1183            .update(|cx| {
1184                Self::new(
1185                    ConnectionIdentifier::setup(),
1186                    opts,
1187                    rx,
1188                    Arc::new(fake::Delegate),
1189                    cx,
1190                )
1191            })
1192            .await
1193            .unwrap()
1194            .unwrap()
1195    }
1196}
1197
1198enum ConnectionPoolEntry {
1199    Connecting(Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>>),
1200    Connected(Weak<dyn RemoteConnection>),
1201}
1202
1203#[derive(Default)]
1204struct ConnectionPool {
1205    connections: HashMap<SshConnectionOptions, ConnectionPoolEntry>,
1206}
1207
1208impl Global for ConnectionPool {}
1209
1210impl ConnectionPool {
1211    pub fn connect(
1212        &mut self,
1213        opts: SshConnectionOptions,
1214        delegate: &Arc<dyn SshClientDelegate>,
1215        cx: &mut App,
1216    ) -> Shared<Task<Result<Arc<dyn RemoteConnection>, Arc<anyhow::Error>>>> {
1217        let connection = self.connections.get(&opts);
1218        match connection {
1219            Some(ConnectionPoolEntry::Connecting(task)) => {
1220                let delegate = delegate.clone();
1221                cx.spawn(async move |cx| {
1222                    delegate.set_status(Some("Waiting for existing connection attempt"), cx);
1223                })
1224                .detach();
1225                return task.clone();
1226            }
1227            Some(ConnectionPoolEntry::Connected(ssh)) => {
1228                if let Some(ssh) = ssh.upgrade() {
1229                    if !ssh.has_been_killed() {
1230                        return Task::ready(Ok(ssh)).shared();
1231                    }
1232                }
1233                self.connections.remove(&opts);
1234            }
1235            None => {}
1236        }
1237
1238        let task = cx
1239            .spawn({
1240                let opts = opts.clone();
1241                let delegate = delegate.clone();
1242                async move |cx| {
1243                    let connection = SshRemoteConnection::new(opts.clone(), delegate, cx)
1244                        .await
1245                        .map(|connection| Arc::new(connection) as Arc<dyn RemoteConnection>);
1246
1247                    cx.update_global(|pool: &mut Self, _| {
1248                        debug_assert!(matches!(
1249                            pool.connections.get(&opts),
1250                            Some(ConnectionPoolEntry::Connecting(_))
1251                        ));
1252                        match connection {
1253                            Ok(connection) => {
1254                                pool.connections.insert(
1255                                    opts.clone(),
1256                                    ConnectionPoolEntry::Connected(Arc::downgrade(&connection)),
1257                                );
1258                                Ok(connection)
1259                            }
1260                            Err(error) => {
1261                                pool.connections.remove(&opts);
1262                                Err(Arc::new(error))
1263                            }
1264                        }
1265                    })?
1266                }
1267            })
1268            .shared();
1269
1270        self.connections
1271            .insert(opts.clone(), ConnectionPoolEntry::Connecting(task.clone()));
1272        task
1273    }
1274}
1275
1276impl From<SshRemoteClient> for AnyProtoClient {
1277    fn from(client: SshRemoteClient) -> Self {
1278        AnyProtoClient::new(client.client.clone())
1279    }
1280}
1281
1282#[async_trait(?Send)]
1283trait RemoteConnection: Send + Sync {
1284    fn start_proxy(
1285        &self,
1286        unique_identifier: String,
1287        reconnect: bool,
1288        incoming_tx: UnboundedSender<Envelope>,
1289        outgoing_rx: UnboundedReceiver<Envelope>,
1290        connection_activity_tx: Sender<()>,
1291        delegate: Arc<dyn SshClientDelegate>,
1292        cx: &mut AsyncApp,
1293    ) -> Task<Result<i32>>;
1294    fn upload_directory(&self, src_path: PathBuf, dest_path: PathBuf, cx: &App)
1295    -> Task<Result<()>>;
1296    async fn kill(&self) -> Result<()>;
1297    fn has_been_killed(&self) -> bool;
1298    fn ssh_args(&self) -> Vec<String>;
1299    fn connection_options(&self) -> SshConnectionOptions;
1300
1301    #[cfg(any(test, feature = "test-support"))]
1302    fn simulate_disconnect(&self, _: &AsyncApp) {}
1303}
1304
1305struct SshRemoteConnection {
1306    socket: SshSocket,
1307    master_process: Mutex<Option<Child>>,
1308    remote_binary_path: Option<PathBuf>,
1309    _temp_dir: TempDir,
1310}
1311
1312#[async_trait(?Send)]
1313impl RemoteConnection for SshRemoteConnection {
1314    async fn kill(&self) -> Result<()> {
1315        let Some(mut process) = self.master_process.lock().take() else {
1316            return Ok(());
1317        };
1318        process.kill().ok();
1319        process.status().await?;
1320        Ok(())
1321    }
1322
1323    fn has_been_killed(&self) -> bool {
1324        self.master_process.lock().is_none()
1325    }
1326
1327    fn ssh_args(&self) -> Vec<String> {
1328        self.socket.ssh_args()
1329    }
1330
1331    fn connection_options(&self) -> SshConnectionOptions {
1332        self.socket.connection_options.clone()
1333    }
1334
1335    fn upload_directory(
1336        &self,
1337        src_path: PathBuf,
1338        dest_path: PathBuf,
1339        cx: &App,
1340    ) -> Task<Result<()>> {
1341        let mut command = util::command::new_smol_command("scp");
1342        let output = self
1343            .socket
1344            .ssh_options(&mut command)
1345            .args(
1346                self.socket
1347                    .connection_options
1348                    .port
1349                    .map(|port| vec!["-P".to_string(), port.to_string()])
1350                    .unwrap_or_default(),
1351            )
1352            .arg("-C")
1353            .arg("-r")
1354            .arg(&src_path)
1355            .arg(format!(
1356                "{}:{}",
1357                self.socket.connection_options.scp_url(),
1358                dest_path.display()
1359            ))
1360            .output();
1361
1362        cx.background_spawn(async move {
1363            let output = output.await?;
1364
1365            if !output.status.success() {
1366                return Err(anyhow!(
1367                    "failed to upload directory {} -> {}: {}",
1368                    src_path.display(),
1369                    dest_path.display(),
1370                    String::from_utf8_lossy(&output.stderr)
1371                ));
1372            }
1373
1374            Ok(())
1375        })
1376    }
1377
1378    fn start_proxy(
1379        &self,
1380        unique_identifier: String,
1381        reconnect: bool,
1382        incoming_tx: UnboundedSender<Envelope>,
1383        outgoing_rx: UnboundedReceiver<Envelope>,
1384        connection_activity_tx: Sender<()>,
1385        delegate: Arc<dyn SshClientDelegate>,
1386        cx: &mut AsyncApp,
1387    ) -> Task<Result<i32>> {
1388        delegate.set_status(Some("Starting proxy"), cx);
1389
1390        let Some(remote_binary_path) = self.remote_binary_path.clone() else {
1391            return Task::ready(Err(anyhow!("Remote binary path not set")));
1392        };
1393
1394        let mut start_proxy_command = shell_script!(
1395            "exec {binary_path} proxy --identifier {identifier}",
1396            binary_path = &remote_binary_path.to_string_lossy(),
1397            identifier = &unique_identifier,
1398        );
1399
1400        if let Some(rust_log) = std::env::var("RUST_LOG").ok() {
1401            start_proxy_command = format!(
1402                "RUST_LOG={} {}",
1403                shlex::try_quote(&rust_log).unwrap(),
1404                start_proxy_command
1405            )
1406        }
1407        if let Some(rust_backtrace) = std::env::var("RUST_BACKTRACE").ok() {
1408            start_proxy_command = format!(
1409                "RUST_BACKTRACE={} {}",
1410                shlex::try_quote(&rust_backtrace).unwrap(),
1411                start_proxy_command
1412            )
1413        }
1414        if reconnect {
1415            start_proxy_command.push_str(" --reconnect");
1416        }
1417
1418        let ssh_proxy_process = match self
1419            .socket
1420            .ssh_command("sh", &["-c", &start_proxy_command])
1421            // IMPORTANT: we kill this process when we drop the task that uses it.
1422            .kill_on_drop(true)
1423            .spawn()
1424        {
1425            Ok(process) => process,
1426            Err(error) => {
1427                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
1428            }
1429        };
1430
1431        Self::multiplex(
1432            ssh_proxy_process,
1433            incoming_tx,
1434            outgoing_rx,
1435            connection_activity_tx,
1436            &cx,
1437        )
1438    }
1439}
1440
1441impl SshRemoteConnection {
1442    #[cfg(not(unix))]
1443    async fn new(
1444        _connection_options: SshConnectionOptions,
1445        _delegate: Arc<dyn SshClientDelegate>,
1446        _cx: &mut AsyncApp,
1447    ) -> Result<Self> {
1448        Err(anyhow!("ssh is not supported on this platform"))
1449    }
1450
1451    #[cfg(unix)]
1452    async fn new(
1453        connection_options: SshConnectionOptions,
1454        delegate: Arc<dyn SshClientDelegate>,
1455        cx: &mut AsyncApp,
1456    ) -> Result<Self> {
1457        use askpass::AskPassResult;
1458
1459        delegate.set_status(Some("Connecting"), cx);
1460
1461        let url = connection_options.ssh_url();
1462
1463        let temp_dir = tempfile::Builder::new()
1464            .prefix("zed-ssh-session")
1465            .tempdir()?;
1466        let askpass_delegate = askpass::AskPassDelegate::new(cx, {
1467            let delegate = delegate.clone();
1468            move |prompt, tx, cx| delegate.ask_password(prompt, tx, cx)
1469        });
1470
1471        let mut askpass =
1472            askpass::AskPassSession::new(cx.background_executor(), askpass_delegate).await?;
1473
1474        // Start the master SSH process, which does not do anything except for establish
1475        // the connection and keep it open, allowing other ssh commands to reuse it
1476        // via a control socket.
1477        let socket_path = temp_dir.path().join("ssh.sock");
1478
1479        let mut master_process = process::Command::new("ssh")
1480            .stdin(Stdio::null())
1481            .stdout(Stdio::piped())
1482            .stderr(Stdio::piped())
1483            .env("SSH_ASKPASS_REQUIRE", "force")
1484            .env("SSH_ASKPASS", &askpass.script_path())
1485            .args(connection_options.additional_args())
1486            .args([
1487                "-N",
1488                "-o",
1489                "ControlPersist=no",
1490                "-o",
1491                "ControlMaster=yes",
1492                "-o",
1493            ])
1494            .arg(format!("ControlPath={}", socket_path.display()))
1495            .arg(&url)
1496            .kill_on_drop(true)
1497            .spawn()?;
1498        // Wait for this ssh process to close its stdout, indicating that authentication
1499        // has completed.
1500        let mut stdout = master_process.stdout.take().unwrap();
1501        let mut output = Vec::new();
1502
1503        let result = select_biased! {
1504            result = askpass.run().fuse() => {
1505                match result {
1506                    AskPassResult::CancelledByUser => {
1507                        master_process.kill().ok();
1508                        Err(anyhow!("SSH connection canceled"))?
1509                    }
1510                    AskPassResult::Timedout => {
1511                        Err(anyhow!("connecting to host timed out"))?
1512                    }
1513                }
1514            }
1515            _ = stdout.read_to_end(&mut output).fuse() => {
1516                anyhow::Ok(())
1517            }
1518        };
1519
1520        if let Err(e) = result {
1521            return Err(e.context("Failed to connect to host"));
1522        }
1523
1524        if master_process.try_status()?.is_some() {
1525            output.clear();
1526            let mut stderr = master_process.stderr.take().unwrap();
1527            stderr.read_to_end(&mut output).await?;
1528
1529            let error_message = format!(
1530                "failed to connect: {}",
1531                String::from_utf8_lossy(&output).trim()
1532            );
1533            Err(anyhow!(error_message))?;
1534        }
1535
1536        drop(askpass);
1537
1538        let socket = SshSocket {
1539            connection_options,
1540            socket_path,
1541        };
1542
1543        let mut this = Self {
1544            socket,
1545            master_process: Mutex::new(Some(master_process)),
1546            _temp_dir: temp_dir,
1547            remote_binary_path: None,
1548        };
1549
1550        let (release_channel, version, commit) = cx.update(|cx| {
1551            (
1552                ReleaseChannel::global(cx),
1553                AppVersion::global(cx),
1554                AppCommitSha::try_global(cx),
1555            )
1556        })?;
1557        this.remote_binary_path = Some(
1558            this.ensure_server_binary(&delegate, release_channel, version, commit, cx)
1559                .await?,
1560        );
1561
1562        Ok(this)
1563    }
1564
1565    async fn platform(&self) -> Result<SshPlatform> {
1566        let uname = self.socket.run_command("sh", &["-c", "uname -sm"]).await?;
1567        let Some((os, arch)) = uname.split_once(" ") else {
1568            Err(anyhow!("unknown uname: {uname:?}"))?
1569        };
1570
1571        let os = match os.trim() {
1572            "Darwin" => "macos",
1573            "Linux" => "linux",
1574            _ => Err(anyhow!(
1575                "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
1576            ))?,
1577        };
1578        // exclude armv5,6,7 as they are 32-bit.
1579        let arch = if arch.starts_with("armv8")
1580            || arch.starts_with("armv9")
1581            || arch.starts_with("arm64")
1582            || arch.starts_with("aarch64")
1583        {
1584            "aarch64"
1585        } else if arch.starts_with("x86") {
1586            "x86_64"
1587        } else {
1588            Err(anyhow!(
1589                "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
1590            ))?
1591        };
1592
1593        Ok(SshPlatform { os, arch })
1594    }
1595
1596    fn multiplex(
1597        mut ssh_proxy_process: Child,
1598        incoming_tx: UnboundedSender<Envelope>,
1599        mut outgoing_rx: UnboundedReceiver<Envelope>,
1600        mut connection_activity_tx: Sender<()>,
1601        cx: &AsyncApp,
1602    ) -> Task<Result<i32>> {
1603        let mut child_stderr = ssh_proxy_process.stderr.take().unwrap();
1604        let mut child_stdout = ssh_proxy_process.stdout.take().unwrap();
1605        let mut child_stdin = ssh_proxy_process.stdin.take().unwrap();
1606
1607        let mut stdin_buffer = Vec::new();
1608        let mut stdout_buffer = Vec::new();
1609        let mut stderr_buffer = Vec::new();
1610        let mut stderr_offset = 0;
1611
1612        let stdin_task = cx.background_spawn(async move {
1613            while let Some(outgoing) = outgoing_rx.next().await {
1614                write_message(&mut child_stdin, &mut stdin_buffer, outgoing).await?;
1615            }
1616            anyhow::Ok(())
1617        });
1618
1619        let stdout_task = cx.background_spawn({
1620            let mut connection_activity_tx = connection_activity_tx.clone();
1621            async move {
1622                loop {
1623                    stdout_buffer.resize(MESSAGE_LEN_SIZE, 0);
1624                    let len = child_stdout.read(&mut stdout_buffer).await?;
1625
1626                    if len == 0 {
1627                        return anyhow::Ok(());
1628                    }
1629
1630                    if len < MESSAGE_LEN_SIZE {
1631                        child_stdout.read_exact(&mut stdout_buffer[len..]).await?;
1632                    }
1633
1634                    let message_len = message_len_from_buffer(&stdout_buffer);
1635                    let envelope =
1636                        read_message_with_len(&mut child_stdout, &mut stdout_buffer, message_len)
1637                            .await?;
1638                    connection_activity_tx.try_send(()).ok();
1639                    incoming_tx.unbounded_send(envelope).ok();
1640                }
1641            }
1642        });
1643
1644        let stderr_task: Task<anyhow::Result<()>> = cx.background_spawn(async move {
1645            loop {
1646                stderr_buffer.resize(stderr_offset + 1024, 0);
1647
1648                let len = child_stderr
1649                    .read(&mut stderr_buffer[stderr_offset..])
1650                    .await?;
1651                if len == 0 {
1652                    return anyhow::Ok(());
1653                }
1654
1655                stderr_offset += len;
1656                let mut start_ix = 0;
1657                while let Some(ix) = stderr_buffer[start_ix..stderr_offset]
1658                    .iter()
1659                    .position(|b| b == &b'\n')
1660                {
1661                    let line_ix = start_ix + ix;
1662                    let content = &stderr_buffer[start_ix..line_ix];
1663                    start_ix = line_ix + 1;
1664                    if let Ok(record) = serde_json::from_slice::<LogRecord>(content) {
1665                        record.log(log::logger())
1666                    } else {
1667                        eprintln!("(remote) {}", String::from_utf8_lossy(content));
1668                    }
1669                }
1670                stderr_buffer.drain(0..start_ix);
1671                stderr_offset -= start_ix;
1672
1673                connection_activity_tx.try_send(()).ok();
1674            }
1675        });
1676
1677        cx.spawn(async move |_| {
1678            let result = futures::select! {
1679                result = stdin_task.fuse() => {
1680                    result.context("stdin")
1681                }
1682                result = stdout_task.fuse() => {
1683                    result.context("stdout")
1684                }
1685                result = stderr_task.fuse() => {
1686                    result.context("stderr")
1687                }
1688            };
1689
1690            let status = ssh_proxy_process.status().await?.code().unwrap_or(1);
1691            match result {
1692                Ok(_) => Ok(status),
1693                Err(error) => Err(error),
1694            }
1695        })
1696    }
1697
1698    #[allow(unused)]
1699    async fn ensure_server_binary(
1700        &self,
1701        delegate: &Arc<dyn SshClientDelegate>,
1702        release_channel: ReleaseChannel,
1703        version: SemanticVersion,
1704        commit: Option<AppCommitSha>,
1705        cx: &mut AsyncApp,
1706    ) -> Result<PathBuf> {
1707        let version_str = match release_channel {
1708            ReleaseChannel::Nightly => {
1709                let commit = commit.map(|s| s.0.to_string()).unwrap_or_default();
1710
1711                format!("{}-{}", version, commit)
1712            }
1713            ReleaseChannel::Dev => "build".to_string(),
1714            _ => version.to_string(),
1715        };
1716        let binary_name = format!(
1717            "zed-remote-server-{}-{}",
1718            release_channel.dev_name(),
1719            version_str
1720        );
1721        let dst_path = paths::remote_server_dir_relative().join(binary_name);
1722        let tmp_path_gz = PathBuf::from(format!(
1723            "{}-download-{}.gz",
1724            dst_path.to_string_lossy(),
1725            std::process::id()
1726        ));
1727
1728        #[cfg(debug_assertions)]
1729        if std::env::var("ZED_BUILD_REMOTE_SERVER").is_ok() {
1730            let src_path = self
1731                .build_local(self.platform().await?, delegate, cx)
1732                .await?;
1733            self.upload_local_server_binary(&src_path, &tmp_path_gz, delegate, cx)
1734                .await?;
1735            self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
1736                .await?;
1737            return Ok(dst_path);
1738        }
1739
1740        if self
1741            .socket
1742            .run_command(&dst_path.to_string_lossy(), &["version"])
1743            .await
1744            .is_ok()
1745        {
1746            return Ok(dst_path);
1747        }
1748
1749        let wanted_version = cx.update(|cx| match release_channel {
1750            ReleaseChannel::Nightly => Ok(None),
1751            ReleaseChannel::Dev => {
1752                anyhow::bail!(
1753                    "ZED_BUILD_REMOTE_SERVER is not set and no remote server exists at ({:?})",
1754                    dst_path
1755                )
1756            }
1757            _ => Ok(Some(AppVersion::global(cx))),
1758        })??;
1759
1760        let platform = self.platform().await?;
1761
1762        if !self.socket.connection_options.upload_binary_over_ssh {
1763            if let Some((url, body)) = delegate
1764                .get_download_params(platform, release_channel, wanted_version, cx)
1765                .await?
1766            {
1767                match self
1768                    .download_binary_on_server(&url, &body, &tmp_path_gz, delegate, cx)
1769                    .await
1770                {
1771                    Ok(_) => {
1772                        self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
1773                            .await?;
1774                        return Ok(dst_path);
1775                    }
1776                    Err(e) => {
1777                        log::error!(
1778                            "Failed to download binary on server, attempting to upload server: {}",
1779                            e
1780                        )
1781                    }
1782                }
1783            }
1784        }
1785
1786        let src_path = delegate
1787            .download_server_binary_locally(platform, release_channel, wanted_version, cx)
1788            .await?;
1789        self.upload_local_server_binary(&src_path, &tmp_path_gz, delegate, cx)
1790            .await?;
1791        self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
1792            .await?;
1793        return Ok(dst_path);
1794    }
1795
1796    async fn download_binary_on_server(
1797        &self,
1798        url: &str,
1799        body: &str,
1800        tmp_path_gz: &Path,
1801        delegate: &Arc<dyn SshClientDelegate>,
1802        cx: &mut AsyncApp,
1803    ) -> Result<()> {
1804        if let Some(parent) = tmp_path_gz.parent() {
1805            self.socket
1806                .run_command("mkdir", &["-p", &parent.to_string_lossy()])
1807                .await?;
1808        }
1809
1810        delegate.set_status(Some("Downloading remote development server on host"), cx);
1811
1812        match self
1813            .socket
1814            .run_command(
1815                "curl",
1816                &[
1817                    "-f",
1818                    "-L",
1819                    "-X",
1820                    "GET",
1821                    "-H",
1822                    "Content-Type: application/json",
1823                    "-d",
1824                    &body,
1825                    &url,
1826                    "-o",
1827                    &tmp_path_gz.to_string_lossy(),
1828                ],
1829            )
1830            .await
1831        {
1832            Ok(_) => {}
1833            Err(e) => {
1834                if self.socket.run_command("which", &["curl"]).await.is_ok() {
1835                    return Err(e);
1836                }
1837
1838                match self
1839                    .socket
1840                    .run_command(
1841                        "wget",
1842                        &[
1843                            "--method=GET",
1844                            "--header=Content-Type: application/json",
1845                            "--body-data",
1846                            &body,
1847                            &url,
1848                            "-O",
1849                            &tmp_path_gz.to_string_lossy(),
1850                        ],
1851                    )
1852                    .await
1853                {
1854                    Ok(_) => {}
1855                    Err(e) => {
1856                        if self.socket.run_command("which", &["wget"]).await.is_ok() {
1857                            return Err(e);
1858                        } else {
1859                            anyhow::bail!("Neither curl nor wget is available");
1860                        }
1861                    }
1862                }
1863            }
1864        }
1865
1866        Ok(())
1867    }
1868
1869    async fn upload_local_server_binary(
1870        &self,
1871        src_path: &Path,
1872        tmp_path_gz: &Path,
1873        delegate: &Arc<dyn SshClientDelegate>,
1874        cx: &mut AsyncApp,
1875    ) -> Result<()> {
1876        if let Some(parent) = tmp_path_gz.parent() {
1877            self.socket
1878                .run_command("mkdir", &["-p", &parent.to_string_lossy()])
1879                .await?;
1880        }
1881
1882        let src_stat = fs::metadata(&src_path).await?;
1883        let size = src_stat.len();
1884
1885        let t0 = Instant::now();
1886        delegate.set_status(Some("Uploading remote development server"), cx);
1887        log::info!(
1888            "uploading remote development server to {:?} ({}kb)",
1889            tmp_path_gz,
1890            size / 1024
1891        );
1892        self.upload_file(&src_path, &tmp_path_gz)
1893            .await
1894            .context("failed to upload server binary")?;
1895        log::info!("uploaded remote development server in {:?}", t0.elapsed());
1896        Ok(())
1897    }
1898
1899    async fn extract_server_binary(
1900        &self,
1901        dst_path: &Path,
1902        tmp_path_gz: &Path,
1903        delegate: &Arc<dyn SshClientDelegate>,
1904        cx: &mut AsyncApp,
1905    ) -> Result<()> {
1906        delegate.set_status(Some("Extracting remote development server"), cx);
1907        let server_mode = 0o755;
1908
1909        let script = shell_script!(
1910            "gunzip -f {tmp_path_gz} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
1911            tmp_path_gz = &tmp_path_gz.to_string_lossy(),
1912            tmp_path = &tmp_path_gz.to_string_lossy().strip_suffix(".gz").unwrap(),
1913            server_mode = &format!("{:o}", server_mode),
1914            dst_path = &dst_path.to_string_lossy()
1915        );
1916        self.socket.run_command("sh", &["-c", &script]).await?;
1917        Ok(())
1918    }
1919
1920    async fn upload_file(&self, src_path: &Path, dest_path: &Path) -> Result<()> {
1921        log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
1922        let mut command = util::command::new_smol_command("scp");
1923        let output = self
1924            .socket
1925            .ssh_options(&mut command)
1926            .args(
1927                self.socket
1928                    .connection_options
1929                    .port
1930                    .map(|port| vec!["-P".to_string(), port.to_string()])
1931                    .unwrap_or_default(),
1932            )
1933            .arg(src_path)
1934            .arg(format!(
1935                "{}:{}",
1936                self.socket.connection_options.scp_url(),
1937                dest_path.display()
1938            ))
1939            .output()
1940            .await?;
1941
1942        if output.status.success() {
1943            Ok(())
1944        } else {
1945            Err(anyhow!(
1946                "failed to upload file {} -> {}: {}",
1947                src_path.display(),
1948                dest_path.display(),
1949                String::from_utf8_lossy(&output.stderr)
1950            ))
1951        }
1952    }
1953
1954    #[cfg(debug_assertions)]
1955    async fn build_local(
1956        &self,
1957        platform: SshPlatform,
1958        delegate: &Arc<dyn SshClientDelegate>,
1959        cx: &mut AsyncApp,
1960    ) -> Result<PathBuf> {
1961        use smol::process::{Command, Stdio};
1962
1963        async fn run_cmd(command: &mut Command) -> Result<()> {
1964            let output = command
1965                .kill_on_drop(true)
1966                .stderr(Stdio::inherit())
1967                .output()
1968                .await?;
1969            if !output.status.success() {
1970                Err(anyhow!("Failed to run command: {:?}", command))?;
1971            }
1972            Ok(())
1973        }
1974
1975        if platform.arch == std::env::consts::ARCH && platform.os == std::env::consts::OS {
1976            delegate.set_status(Some("Building remote server binary from source"), cx);
1977            log::info!("building remote server binary from source");
1978            run_cmd(Command::new("cargo").args([
1979                "build",
1980                "--package",
1981                "remote_server",
1982                "--features",
1983                "debug-embed",
1984                "--target-dir",
1985                "target/remote_server",
1986            ]))
1987            .await?;
1988
1989            delegate.set_status(Some("Compressing binary"), cx);
1990
1991            run_cmd(Command::new("gzip").args([
1992                "-9",
1993                "-f",
1994                "target/remote_server/debug/remote_server",
1995            ]))
1996            .await?;
1997
1998            let path = std::env::current_dir()?.join("target/remote_server/debug/remote_server.gz");
1999            return Ok(path);
2000        }
2001        let Some(triple) = platform.triple() else {
2002            anyhow::bail!("can't cross compile for: {:?}", platform);
2003        };
2004        smol::fs::create_dir_all("target/remote_server").await?;
2005
2006        delegate.set_status(Some("Installing cross.rs for cross-compilation"), cx);
2007        log::info!("installing cross");
2008        run_cmd(Command::new("cargo").args([
2009            "install",
2010            "cross",
2011            "--git",
2012            "https://github.com/cross-rs/cross",
2013        ]))
2014        .await?;
2015
2016        delegate.set_status(
2017            Some(&format!(
2018                "Building remote server binary from source for {} with Docker",
2019                &triple
2020            )),
2021            cx,
2022        );
2023        log::info!("building remote server binary from source for {}", &triple);
2024        run_cmd(
2025            Command::new("cross")
2026                .args([
2027                    "build",
2028                    "--package",
2029                    "remote_server",
2030                    "--features",
2031                    "debug-embed",
2032                    "--target-dir",
2033                    "target/remote_server",
2034                    "--target",
2035                    &triple,
2036                ])
2037                .env(
2038                    "CROSS_CONTAINER_OPTS",
2039                    "--mount type=bind,src=./target,dst=/app/target",
2040                ),
2041        )
2042        .await?;
2043
2044        delegate.set_status(Some("Compressing binary"), cx);
2045
2046        run_cmd(Command::new("gzip").args([
2047            "-9",
2048            "-f",
2049            &format!("target/remote_server/{}/debug/remote_server", triple),
2050        ]))
2051        .await?;
2052
2053        let path = std::env::current_dir()?.join(format!(
2054            "target/remote_server/{}/debug/remote_server.gz",
2055            triple
2056        ));
2057
2058        return Ok(path);
2059    }
2060}
2061
2062type ResponseChannels = Mutex<HashMap<MessageId, oneshot::Sender<(Envelope, oneshot::Sender<()>)>>>;
2063
2064pub struct ChannelClient {
2065    next_message_id: AtomicU32,
2066    outgoing_tx: Mutex<mpsc::UnboundedSender<Envelope>>,
2067    buffer: Mutex<VecDeque<Envelope>>,
2068    response_channels: ResponseChannels,
2069    message_handlers: Mutex<ProtoMessageHandlerSet>,
2070    max_received: AtomicU32,
2071    name: &'static str,
2072    task: Mutex<Task<Result<()>>>,
2073}
2074
2075impl ChannelClient {
2076    pub fn new(
2077        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
2078        outgoing_tx: mpsc::UnboundedSender<Envelope>,
2079        cx: &App,
2080        name: &'static str,
2081    ) -> Arc<Self> {
2082        Arc::new_cyclic(|this| Self {
2083            outgoing_tx: Mutex::new(outgoing_tx),
2084            next_message_id: AtomicU32::new(0),
2085            max_received: AtomicU32::new(0),
2086            response_channels: ResponseChannels::default(),
2087            message_handlers: Default::default(),
2088            buffer: Mutex::new(VecDeque::new()),
2089            name,
2090            task: Mutex::new(Self::start_handling_messages(
2091                this.clone(),
2092                incoming_rx,
2093                &cx.to_async(),
2094            )),
2095        })
2096    }
2097
2098    fn start_handling_messages(
2099        this: Weak<Self>,
2100        mut incoming_rx: mpsc::UnboundedReceiver<Envelope>,
2101        cx: &AsyncApp,
2102    ) -> Task<Result<()>> {
2103        cx.spawn(async move |cx| {
2104            let peer_id = PeerId { owner_id: 0, id: 0 };
2105            while let Some(incoming) = incoming_rx.next().await {
2106                let Some(this) = this.upgrade() else {
2107                    return anyhow::Ok(());
2108                };
2109                if let Some(ack_id) = incoming.ack_id {
2110                    let mut buffer = this.buffer.lock();
2111                    while buffer.front().is_some_and(|msg| msg.id <= ack_id) {
2112                        buffer.pop_front();
2113                    }
2114                }
2115                if let Some(proto::envelope::Payload::FlushBufferedMessages(_)) = &incoming.payload
2116                {
2117                    log::debug!(
2118                        "{}:ssh message received. name:FlushBufferedMessages",
2119                        this.name
2120                    );
2121                    {
2122                        let buffer = this.buffer.lock();
2123                        for envelope in buffer.iter() {
2124                            this.outgoing_tx
2125                                .lock()
2126                                .unbounded_send(envelope.clone())
2127                                .ok();
2128                        }
2129                    }
2130                    let mut envelope = proto::Ack {}.into_envelope(0, Some(incoming.id), None);
2131                    envelope.id = this.next_message_id.fetch_add(1, SeqCst);
2132                    this.outgoing_tx.lock().unbounded_send(envelope).ok();
2133                    continue;
2134                }
2135
2136                this.max_received.store(incoming.id, SeqCst);
2137
2138                if let Some(request_id) = incoming.responding_to {
2139                    let request_id = MessageId(request_id);
2140                    let sender = this.response_channels.lock().remove(&request_id);
2141                    if let Some(sender) = sender {
2142                        let (tx, rx) = oneshot::channel();
2143                        if incoming.payload.is_some() {
2144                            sender.send((incoming, tx)).ok();
2145                        }
2146                        rx.await.ok();
2147                    }
2148                } else if let Some(envelope) =
2149                    build_typed_envelope(peer_id, Instant::now(), incoming)
2150                {
2151                    let type_name = envelope.payload_type_name();
2152                    if let Some(future) = ProtoMessageHandlerSet::handle_message(
2153                        &this.message_handlers,
2154                        envelope,
2155                        this.clone().into(),
2156                        cx.clone(),
2157                    ) {
2158                        log::debug!("{}:ssh message received. name:{type_name}", this.name);
2159                        cx.foreground_executor()
2160                            .spawn(async move {
2161                                match future.await {
2162                                    Ok(_) => {
2163                                        log::debug!(
2164                                            "{}:ssh message handled. name:{type_name}",
2165                                            this.name
2166                                        );
2167                                    }
2168                                    Err(error) => {
2169                                        log::error!(
2170                                            "{}:error handling message. type:{}, error:{}",
2171                                            this.name,
2172                                            type_name,
2173                                            format!("{error:#}").lines().fold(
2174                                                String::new(),
2175                                                |mut message, line| {
2176                                                    if !message.is_empty() {
2177                                                        message.push(' ');
2178                                                    }
2179                                                    message.push_str(line);
2180                                                    message
2181                                                }
2182                                            )
2183                                        );
2184                                    }
2185                                }
2186                            })
2187                            .detach()
2188                    } else {
2189                        log::error!("{}:unhandled ssh message name:{type_name}", this.name);
2190                    }
2191                }
2192            }
2193            anyhow::Ok(())
2194        })
2195    }
2196
2197    pub fn reconnect(
2198        self: &Arc<Self>,
2199        incoming_rx: UnboundedReceiver<Envelope>,
2200        outgoing_tx: UnboundedSender<Envelope>,
2201        cx: &AsyncApp,
2202    ) {
2203        *self.outgoing_tx.lock() = outgoing_tx;
2204        *self.task.lock() = Self::start_handling_messages(Arc::downgrade(self), incoming_rx, cx);
2205    }
2206
2207    pub fn subscribe_to_entity<E: 'static>(&self, remote_id: u64, entity: &Entity<E>) {
2208        let id = (TypeId::of::<E>(), remote_id);
2209
2210        let mut message_handlers = self.message_handlers.lock();
2211        if message_handlers
2212            .entities_by_type_and_remote_id
2213            .contains_key(&id)
2214        {
2215            panic!("already subscribed to entity");
2216        }
2217
2218        message_handlers.entities_by_type_and_remote_id.insert(
2219            id,
2220            EntityMessageSubscriber::Entity {
2221                handle: entity.downgrade().into(),
2222            },
2223        );
2224    }
2225
2226    pub fn request<T: RequestMessage>(
2227        &self,
2228        payload: T,
2229    ) -> impl 'static + Future<Output = Result<T::Response>> {
2230        self.request_internal(payload, true)
2231    }
2232
2233    fn request_internal<T: RequestMessage>(
2234        &self,
2235        payload: T,
2236        use_buffer: bool,
2237    ) -> impl 'static + Future<Output = Result<T::Response>> {
2238        log::debug!("ssh request start. name:{}", T::NAME);
2239        let response =
2240            self.request_dynamic(payload.into_envelope(0, None, None), T::NAME, use_buffer);
2241        async move {
2242            let response = response.await?;
2243            log::debug!("ssh request finish. name:{}", T::NAME);
2244            T::Response::from_envelope(response)
2245                .ok_or_else(|| anyhow!("received a response of the wrong type"))
2246        }
2247    }
2248
2249    pub async fn resync(&self, timeout: Duration) -> Result<()> {
2250        smol::future::or(
2251            async {
2252                self.request_internal(proto::FlushBufferedMessages {}, false)
2253                    .await?;
2254
2255                for envelope in self.buffer.lock().iter() {
2256                    self.outgoing_tx
2257                        .lock()
2258                        .unbounded_send(envelope.clone())
2259                        .ok();
2260                }
2261                Ok(())
2262            },
2263            async {
2264                smol::Timer::after(timeout).await;
2265                Err(anyhow!("Timeout detected"))
2266            },
2267        )
2268        .await
2269    }
2270
2271    pub async fn ping(&self, timeout: Duration) -> Result<()> {
2272        smol::future::or(
2273            async {
2274                self.request(proto::Ping {}).await?;
2275                Ok(())
2276            },
2277            async {
2278                smol::Timer::after(timeout).await;
2279                Err(anyhow!("Timeout detected"))
2280            },
2281        )
2282        .await
2283    }
2284
2285    pub fn send<T: EnvelopedMessage>(&self, payload: T) -> Result<()> {
2286        log::debug!("ssh send name:{}", T::NAME);
2287        self.send_dynamic(payload.into_envelope(0, None, None))
2288    }
2289
2290    fn request_dynamic(
2291        &self,
2292        mut envelope: proto::Envelope,
2293        type_name: &'static str,
2294        use_buffer: bool,
2295    ) -> impl 'static + Future<Output = Result<proto::Envelope>> {
2296        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
2297        let (tx, rx) = oneshot::channel();
2298        let mut response_channels_lock = self.response_channels.lock();
2299        response_channels_lock.insert(MessageId(envelope.id), tx);
2300        drop(response_channels_lock);
2301
2302        let result = if use_buffer {
2303            self.send_buffered(envelope)
2304        } else {
2305            self.send_unbuffered(envelope)
2306        };
2307        async move {
2308            if let Err(error) = &result {
2309                log::error!("failed to send message: {}", error);
2310                return Err(anyhow!("failed to send message: {}", error));
2311            }
2312
2313            let response = rx.await.context("connection lost")?.0;
2314            if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
2315                return Err(RpcError::from_proto(error, type_name));
2316            }
2317            Ok(response)
2318        }
2319    }
2320
2321    pub fn send_dynamic(&self, mut envelope: proto::Envelope) -> Result<()> {
2322        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
2323        self.send_buffered(envelope)
2324    }
2325
2326    fn send_buffered(&self, mut envelope: proto::Envelope) -> Result<()> {
2327        envelope.ack_id = Some(self.max_received.load(SeqCst));
2328        self.buffer.lock().push_back(envelope.clone());
2329        // ignore errors on send (happen while we're reconnecting)
2330        // assume that the global "disconnected" overlay is sufficient.
2331        self.outgoing_tx.lock().unbounded_send(envelope).ok();
2332        Ok(())
2333    }
2334
2335    fn send_unbuffered(&self, mut envelope: proto::Envelope) -> Result<()> {
2336        envelope.ack_id = Some(self.max_received.load(SeqCst));
2337        self.outgoing_tx.lock().unbounded_send(envelope).ok();
2338        Ok(())
2339    }
2340}
2341
2342impl ProtoClient for ChannelClient {
2343    fn request(
2344        &self,
2345        envelope: proto::Envelope,
2346        request_type: &'static str,
2347    ) -> BoxFuture<'static, Result<proto::Envelope>> {
2348        self.request_dynamic(envelope, request_type, true).boxed()
2349    }
2350
2351    fn send(&self, envelope: proto::Envelope, _message_type: &'static str) -> Result<()> {
2352        self.send_dynamic(envelope)
2353    }
2354
2355    fn send_response(&self, envelope: Envelope, _message_type: &'static str) -> anyhow::Result<()> {
2356        self.send_dynamic(envelope)
2357    }
2358
2359    fn message_handler_set(&self) -> &Mutex<ProtoMessageHandlerSet> {
2360        &self.message_handlers
2361    }
2362
2363    fn is_via_collab(&self) -> bool {
2364        false
2365    }
2366}
2367
2368#[cfg(any(test, feature = "test-support"))]
2369mod fake {
2370    use std::{path::PathBuf, sync::Arc};
2371
2372    use anyhow::Result;
2373    use async_trait::async_trait;
2374    use futures::{
2375        FutureExt, SinkExt, StreamExt,
2376        channel::{
2377            mpsc::{self, Sender},
2378            oneshot,
2379        },
2380        select_biased,
2381    };
2382    use gpui::{App, AppContext as _, AsyncApp, SemanticVersion, Task, TestAppContext};
2383    use release_channel::ReleaseChannel;
2384    use rpc::proto::Envelope;
2385
2386    use super::{
2387        ChannelClient, RemoteConnection, SshClientDelegate, SshConnectionOptions, SshPlatform,
2388    };
2389
2390    pub(super) struct FakeRemoteConnection {
2391        pub(super) connection_options: SshConnectionOptions,
2392        pub(super) server_channel: Arc<ChannelClient>,
2393        pub(super) server_cx: SendableCx,
2394    }
2395
2396    pub(super) struct SendableCx(AsyncApp);
2397    impl SendableCx {
2398        // SAFETY: When run in test mode, GPUI is always single threaded.
2399        pub(super) fn new(cx: &TestAppContext) -> Self {
2400            Self(cx.to_async())
2401        }
2402
2403        // SAFETY: Enforce that we're on the main thread by requiring a valid AsyncApp
2404        fn get(&self, _: &AsyncApp) -> AsyncApp {
2405            self.0.clone()
2406        }
2407    }
2408
2409    // SAFETY: There is no way to access a SendableCx from a different thread, see [`SendableCx::new`] and [`SendableCx::get`]
2410    unsafe impl Send for SendableCx {}
2411    unsafe impl Sync for SendableCx {}
2412
2413    #[async_trait(?Send)]
2414    impl RemoteConnection for FakeRemoteConnection {
2415        async fn kill(&self) -> Result<()> {
2416            Ok(())
2417        }
2418
2419        fn has_been_killed(&self) -> bool {
2420            false
2421        }
2422
2423        fn ssh_args(&self) -> Vec<String> {
2424            Vec::new()
2425        }
2426        fn upload_directory(
2427            &self,
2428            _src_path: PathBuf,
2429            _dest_path: PathBuf,
2430            _cx: &App,
2431        ) -> Task<Result<()>> {
2432            unreachable!()
2433        }
2434
2435        fn connection_options(&self) -> SshConnectionOptions {
2436            self.connection_options.clone()
2437        }
2438
2439        fn simulate_disconnect(&self, cx: &AsyncApp) {
2440            let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
2441            let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
2442            self.server_channel
2443                .reconnect(incoming_rx, outgoing_tx, &self.server_cx.get(&cx));
2444        }
2445
2446        fn start_proxy(
2447            &self,
2448
2449            _unique_identifier: String,
2450            _reconnect: bool,
2451            mut client_incoming_tx: mpsc::UnboundedSender<Envelope>,
2452            mut client_outgoing_rx: mpsc::UnboundedReceiver<Envelope>,
2453            mut connection_activity_tx: Sender<()>,
2454            _delegate: Arc<dyn SshClientDelegate>,
2455            cx: &mut AsyncApp,
2456        ) -> Task<Result<i32>> {
2457            let (mut server_incoming_tx, server_incoming_rx) = mpsc::unbounded::<Envelope>();
2458            let (server_outgoing_tx, mut server_outgoing_rx) = mpsc::unbounded::<Envelope>();
2459
2460            self.server_channel.reconnect(
2461                server_incoming_rx,
2462                server_outgoing_tx,
2463                &self.server_cx.get(cx),
2464            );
2465
2466            cx.background_spawn(async move {
2467                loop {
2468                    select_biased! {
2469                        server_to_client = server_outgoing_rx.next().fuse() => {
2470                            let Some(server_to_client) = server_to_client else {
2471                                return Ok(1)
2472                            };
2473                            connection_activity_tx.try_send(()).ok();
2474                            client_incoming_tx.send(server_to_client).await.ok();
2475                        }
2476                        client_to_server = client_outgoing_rx.next().fuse() => {
2477                            let Some(client_to_server) = client_to_server else {
2478                                return Ok(1)
2479                            };
2480                            server_incoming_tx.send(client_to_server).await.ok();
2481                        }
2482                    }
2483                }
2484            })
2485        }
2486    }
2487
2488    pub(super) struct Delegate;
2489
2490    impl SshClientDelegate for Delegate {
2491        fn ask_password(&self, _: String, _: oneshot::Sender<String>, _: &mut AsyncApp) {
2492            unreachable!()
2493        }
2494
2495        fn download_server_binary_locally(
2496            &self,
2497            _: SshPlatform,
2498            _: ReleaseChannel,
2499            _: Option<SemanticVersion>,
2500            _: &mut AsyncApp,
2501        ) -> Task<Result<PathBuf>> {
2502            unreachable!()
2503        }
2504
2505        fn get_download_params(
2506            &self,
2507            _platform: SshPlatform,
2508            _release_channel: ReleaseChannel,
2509            _version: Option<SemanticVersion>,
2510            _cx: &mut AsyncApp,
2511        ) -> Task<Result<Option<(String, String)>>> {
2512            unreachable!()
2513        }
2514
2515        fn set_status(&self, _: Option<&str>, _: &mut AsyncApp) {}
2516    }
2517}