ssh_session.rs

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