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