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