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,
  17    select_biased, AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
  18};
  19use gpui::{
  20    AppContext, AsyncAppContext, Context, EventEmitter, Model, ModelContext, SemanticVersion, Task,
  21    WeakModel,
  22};
  23use parking_lot::Mutex;
  24use rpc::{
  25    proto::{self, build_typed_envelope, Envelope, EnvelopedMessage, PeerId, RequestMessage},
  26    AnyProtoClient, EntityMessageSubscriber, ProtoClient, ProtoMessageHandlerSet, RpcError,
  27};
  28use smol::{
  29    fs,
  30    process::{self, Child, Stdio},
  31};
  32use std::{
  33    any::TypeId,
  34    collections::VecDeque,
  35    ffi::OsStr,
  36    fmt,
  37    ops::ControlFlow,
  38    path::{Path, PathBuf},
  39    sync::{
  40        atomic::{AtomicU32, Ordering::SeqCst},
  41        Arc, Weak,
  42    },
  43    time::{Duration, Instant},
  44};
  45use tempfile::TempDir;
  46use util::ResultExt;
  47
  48#[derive(
  49    Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
  50)]
  51pub struct SshProjectId(pub u64);
  52
  53#[derive(Clone)]
  54pub struct SshSocket {
  55    connection_options: SshConnectionOptions,
  56    socket_path: PathBuf,
  57}
  58
  59#[derive(Debug, Default, Clone, PartialEq, Eq)]
  60pub struct SshConnectionOptions {
  61    pub host: String,
  62    pub username: Option<String>,
  63    pub port: Option<u16>,
  64    pub password: Option<String>,
  65    pub args: Option<Vec<String>>,
  66}
  67
  68impl SshConnectionOptions {
  69    pub fn parse_command_line(input: &str) -> Result<Self> {
  70        let input = input.trim_start_matches("ssh ");
  71        let mut hostname: Option<String> = None;
  72        let mut username: Option<String> = None;
  73        let mut port: Option<u16> = None;
  74        let mut args = Vec::new();
  75
  76        // disallowed: -E, -e, -F, -f, -G, -g, -M, -N, -n, -O, -q, -S, -s, -T, -t, -V, -v, -W
  77        const ALLOWED_OPTS: &[&str] = &[
  78            "-4", "-6", "-A", "-a", "-C", "-K", "-k", "-X", "-x", "-Y", "-y",
  79        ];
  80        const ALLOWED_ARGS: &[&str] = &[
  81            "-B", "-b", "-c", "-D", "-I", "-i", "-J", "-L", "-l", "-m", "-o", "-P", "-p", "-R",
  82            "-w",
  83        ];
  84
  85        let mut tokens = shlex::split(input)
  86            .ok_or_else(|| anyhow!("invalid input"))?
  87            .into_iter();
  88
  89        'outer: while let Some(arg) = tokens.next() {
  90            if ALLOWED_OPTS.contains(&(&arg as &str)) {
  91                args.push(arg.to_string());
  92                continue;
  93            }
  94            if arg == "-p" {
  95                port = tokens.next().and_then(|arg| arg.parse().ok());
  96                continue;
  97            } else if let Some(p) = arg.strip_prefix("-p") {
  98                port = p.parse().ok();
  99                continue;
 100            }
 101            if arg == "-l" {
 102                username = tokens.next();
 103                continue;
 104            } else if let Some(l) = arg.strip_prefix("-l") {
 105                username = Some(l.to_string());
 106                continue;
 107            }
 108            for a in ALLOWED_ARGS {
 109                if arg == *a {
 110                    args.push(arg);
 111                    if let Some(next) = tokens.next() {
 112                        args.push(next);
 113                    }
 114                    continue 'outer;
 115                } else if arg.starts_with(a) {
 116                    args.push(arg);
 117                    continue 'outer;
 118                }
 119            }
 120            if arg.starts_with("-") || hostname.is_some() {
 121                anyhow::bail!("unsupported argument: {:?}", arg);
 122            }
 123            let mut input = &arg as &str;
 124            if let Some((u, rest)) = input.split_once('@') {
 125                input = rest;
 126                username = Some(u.to_string());
 127            }
 128            if let Some((rest, p)) = input.split_once(':') {
 129                input = rest;
 130                port = p.parse().ok()
 131            }
 132            hostname = Some(input.to_string())
 133        }
 134
 135        let Some(hostname) = hostname else {
 136            anyhow::bail!("missing hostname");
 137        };
 138
 139        Ok(Self {
 140            host: hostname.to_string(),
 141            username: username.clone(),
 142            port,
 143            password: None,
 144            args: Some(args),
 145        })
 146    }
 147
 148    pub fn ssh_url(&self) -> String {
 149        let mut result = String::from("ssh://");
 150        if let Some(username) = &self.username {
 151            result.push_str(username);
 152            result.push('@');
 153        }
 154        result.push_str(&self.host);
 155        if let Some(port) = self.port {
 156            result.push(':');
 157            result.push_str(&port.to_string());
 158        }
 159        result
 160    }
 161
 162    pub fn additional_args(&self) -> Option<&Vec<String>> {
 163        self.args.as_ref()
 164    }
 165
 166    fn scp_url(&self) -> String {
 167        if let Some(username) = &self.username {
 168            format!("{}@{}", username, self.host)
 169        } else {
 170            self.host.clone()
 171        }
 172    }
 173
 174    pub fn connection_string(&self) -> String {
 175        let host = if let Some(username) = &self.username {
 176            format!("{}@{}", username, self.host)
 177        } else {
 178            self.host.clone()
 179        };
 180        if let Some(port) = &self.port {
 181            format!("{}:{}", host, port)
 182        } else {
 183            host
 184        }
 185    }
 186
 187    // Uniquely identifies dev server projects on a remote host. Needs to be
 188    // stable for the same dev server project.
 189    pub fn remote_server_identifier(&self) -> String {
 190        let mut identifier = format!("dev-server-{:?}", self.host);
 191        if let Some(username) = self.username.as_ref() {
 192            identifier.push('-');
 193            identifier.push_str(&username);
 194        }
 195        identifier
 196    }
 197}
 198
 199#[derive(Copy, Clone, Debug)]
 200pub struct SshPlatform {
 201    pub os: &'static str,
 202    pub arch: &'static str,
 203}
 204
 205impl SshPlatform {
 206    pub fn triple(&self) -> Option<String> {
 207        Some(format!(
 208            "{}-{}",
 209            self.arch,
 210            match self.os {
 211                "linux" => "unknown-linux-gnu",
 212                "macos" => "apple-darwin",
 213                _ => return None,
 214            }
 215        ))
 216    }
 217}
 218
 219pub trait SshClientDelegate: Send + Sync {
 220    fn ask_password(
 221        &self,
 222        prompt: String,
 223        cx: &mut AsyncAppContext,
 224    ) -> oneshot::Receiver<Result<String>>;
 225    fn remote_server_binary_path(
 226        &self,
 227        platform: SshPlatform,
 228        cx: &mut AsyncAppContext,
 229    ) -> Result<PathBuf>;
 230    fn get_server_binary(
 231        &self,
 232        platform: SshPlatform,
 233        cx: &mut AsyncAppContext,
 234    ) -> oneshot::Receiver<Result<(PathBuf, SemanticVersion)>>;
 235    fn set_status(&self, status: Option<&str>, cx: &mut AsyncAppContext);
 236}
 237
 238impl SshSocket {
 239    fn ssh_command<S: AsRef<OsStr>>(&self, program: S) -> process::Command {
 240        let mut command = process::Command::new("ssh");
 241        self.ssh_options(&mut command)
 242            .arg(self.connection_options.ssh_url())
 243            .arg(program);
 244        command
 245    }
 246
 247    fn ssh_options<'a>(&self, command: &'a mut process::Command) -> &'a mut process::Command {
 248        command
 249            .stdin(Stdio::piped())
 250            .stdout(Stdio::piped())
 251            .stderr(Stdio::piped())
 252            .args(["-o", "ControlMaster=no", "-o"])
 253            .arg(format!("ControlPath={}", self.socket_path.display()))
 254    }
 255
 256    fn ssh_args(&self) -> Vec<String> {
 257        vec![
 258            "-o".to_string(),
 259            "ControlMaster=no".to_string(),
 260            "-o".to_string(),
 261            format!("ControlPath={}", self.socket_path.display()),
 262            self.connection_options.ssh_url(),
 263        ]
 264    }
 265}
 266
 267async fn run_cmd(command: &mut process::Command) -> Result<String> {
 268    let output = command.output().await?;
 269    if output.status.success() {
 270        Ok(String::from_utf8_lossy(&output.stdout).to_string())
 271    } else {
 272        Err(anyhow!(
 273            "failed to run command: {}",
 274            String::from_utf8_lossy(&output.stderr)
 275        ))
 276    }
 277}
 278
 279const MAX_MISSED_HEARTBEATS: usize = 5;
 280const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
 281const HEARTBEAT_TIMEOUT: Duration = Duration::from_secs(5);
 282
 283const MAX_RECONNECT_ATTEMPTS: usize = 3;
 284
 285enum State {
 286    Connecting,
 287    Connected {
 288        ssh_connection: Box<dyn SshRemoteProcess>,
 289        delegate: Arc<dyn SshClientDelegate>,
 290
 291        multiplex_task: Task<Result<()>>,
 292        heartbeat_task: Task<Result<()>>,
 293    },
 294    HeartbeatMissed {
 295        missed_heartbeats: usize,
 296
 297        ssh_connection: Box<dyn SshRemoteProcess>,
 298        delegate: Arc<dyn SshClientDelegate>,
 299
 300        multiplex_task: Task<Result<()>>,
 301        heartbeat_task: Task<Result<()>>,
 302    },
 303    Reconnecting,
 304    ReconnectFailed {
 305        ssh_connection: Box<dyn SshRemoteProcess>,
 306        delegate: Arc<dyn SshClientDelegate>,
 307
 308        error: anyhow::Error,
 309        attempts: usize,
 310    },
 311    ReconnectExhausted,
 312    ServerNotRunning,
 313}
 314
 315impl fmt::Display for State {
 316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 317        match self {
 318            Self::Connecting => write!(f, "connecting"),
 319            Self::Connected { .. } => write!(f, "connected"),
 320            Self::Reconnecting => write!(f, "reconnecting"),
 321            Self::ReconnectFailed { .. } => write!(f, "reconnect failed"),
 322            Self::ReconnectExhausted => write!(f, "reconnect exhausted"),
 323            Self::HeartbeatMissed { .. } => write!(f, "heartbeat missed"),
 324            Self::ServerNotRunning { .. } => write!(f, "server not running"),
 325        }
 326    }
 327}
 328
 329impl State {
 330    fn ssh_connection(&self) -> Option<&dyn SshRemoteProcess> {
 331        match self {
 332            Self::Connected { ssh_connection, .. } => Some(ssh_connection.as_ref()),
 333            Self::HeartbeatMissed { ssh_connection, .. } => Some(ssh_connection.as_ref()),
 334            Self::ReconnectFailed { ssh_connection, .. } => Some(ssh_connection.as_ref()),
 335            _ => None,
 336        }
 337    }
 338
 339    fn can_reconnect(&self) -> bool {
 340        match self {
 341            Self::Connected { .. }
 342            | Self::HeartbeatMissed { .. }
 343            | Self::ReconnectFailed { .. } => true,
 344            State::Connecting
 345            | State::Reconnecting
 346            | State::ReconnectExhausted
 347            | State::ServerNotRunning => false,
 348        }
 349    }
 350
 351    fn is_reconnect_failed(&self) -> bool {
 352        matches!(self, Self::ReconnectFailed { .. })
 353    }
 354
 355    fn is_reconnect_exhausted(&self) -> bool {
 356        matches!(self, Self::ReconnectExhausted { .. })
 357    }
 358
 359    fn is_server_not_running(&self) -> bool {
 360        matches!(self, Self::ServerNotRunning)
 361    }
 362
 363    fn is_reconnecting(&self) -> bool {
 364        matches!(self, Self::Reconnecting { .. })
 365    }
 366
 367    fn heartbeat_recovered(self) -> Self {
 368        match self {
 369            Self::HeartbeatMissed {
 370                ssh_connection,
 371                delegate,
 372                multiplex_task,
 373                heartbeat_task,
 374                ..
 375            } => Self::Connected {
 376                ssh_connection,
 377                delegate,
 378                multiplex_task,
 379                heartbeat_task,
 380            },
 381            _ => self,
 382        }
 383    }
 384
 385    fn heartbeat_missed(self) -> Self {
 386        match self {
 387            Self::Connected {
 388                ssh_connection,
 389                delegate,
 390                multiplex_task,
 391                heartbeat_task,
 392            } => Self::HeartbeatMissed {
 393                missed_heartbeats: 1,
 394                ssh_connection,
 395                delegate,
 396                multiplex_task,
 397                heartbeat_task,
 398            },
 399            Self::HeartbeatMissed {
 400                missed_heartbeats,
 401                ssh_connection,
 402                delegate,
 403                multiplex_task,
 404                heartbeat_task,
 405            } => Self::HeartbeatMissed {
 406                missed_heartbeats: missed_heartbeats + 1,
 407                ssh_connection,
 408                delegate,
 409                multiplex_task,
 410                heartbeat_task,
 411            },
 412            _ => self,
 413        }
 414    }
 415}
 416
 417/// The state of the ssh connection.
 418#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 419pub enum ConnectionState {
 420    Connecting,
 421    Connected,
 422    HeartbeatMissed,
 423    Reconnecting,
 424    Disconnected,
 425}
 426
 427impl From<&State> for ConnectionState {
 428    fn from(value: &State) -> Self {
 429        match value {
 430            State::Connecting => Self::Connecting,
 431            State::Connected { .. } => Self::Connected,
 432            State::Reconnecting | State::ReconnectFailed { .. } => Self::Reconnecting,
 433            State::HeartbeatMissed { .. } => Self::HeartbeatMissed,
 434            State::ReconnectExhausted => Self::Disconnected,
 435            State::ServerNotRunning => Self::Disconnected,
 436        }
 437    }
 438}
 439
 440pub struct SshRemoteClient {
 441    client: Arc<ChannelClient>,
 442    unique_identifier: String,
 443    connection_options: SshConnectionOptions,
 444    state: Arc<Mutex<Option<State>>>,
 445}
 446
 447#[derive(Debug)]
 448pub enum SshRemoteEvent {
 449    Disconnected,
 450}
 451
 452impl EventEmitter<SshRemoteEvent> for SshRemoteClient {}
 453
 454impl SshRemoteClient {
 455    pub fn new(
 456        unique_identifier: String,
 457        connection_options: SshConnectionOptions,
 458        delegate: Arc<dyn SshClientDelegate>,
 459        cx: &AppContext,
 460    ) -> Task<Result<Model<Self>>> {
 461        cx.spawn(|mut cx| async move {
 462            let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 463            let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 464            let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 465
 466            let client =
 467                cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "client"))?;
 468            let this = cx.new_model(|_| Self {
 469                client: client.clone(),
 470                unique_identifier: unique_identifier.clone(),
 471                connection_options: connection_options.clone(),
 472                state: Arc::new(Mutex::new(Some(State::Connecting))),
 473            })?;
 474
 475            let (ssh_connection, io_task) = Self::establish_connection(
 476                unique_identifier,
 477                false,
 478                connection_options,
 479                incoming_tx,
 480                outgoing_rx,
 481                connection_activity_tx,
 482                delegate.clone(),
 483                &mut cx,
 484            )
 485            .await?;
 486
 487            let multiplex_task = Self::monitor(this.downgrade(), io_task, &cx);
 488
 489            if let Err(error) = client.ping(HEARTBEAT_TIMEOUT).await {
 490                log::error!("failed to establish connection: {}", error);
 491                return Err(error);
 492            }
 493
 494            let heartbeat_task = Self::heartbeat(this.downgrade(), connection_activity_rx, &mut cx);
 495
 496            this.update(&mut cx, |this, _| {
 497                *this.state.lock() = Some(State::Connected {
 498                    ssh_connection,
 499                    delegate,
 500                    multiplex_task,
 501                    heartbeat_task,
 502                });
 503            })?;
 504
 505            Ok(this)
 506        })
 507    }
 508
 509    pub fn shutdown_processes<T: RequestMessage>(
 510        &self,
 511        shutdown_request: Option<T>,
 512    ) -> Option<impl Future<Output = ()>> {
 513        let state = self.state.lock().take()?;
 514        log::info!("shutting down ssh processes");
 515
 516        let State::Connected {
 517            multiplex_task,
 518            heartbeat_task,
 519            ssh_connection,
 520            delegate,
 521        } = state
 522        else {
 523            return None;
 524        };
 525
 526        let client = self.client.clone();
 527
 528        Some(async move {
 529            if let Some(shutdown_request) = shutdown_request {
 530                client.send(shutdown_request).log_err();
 531                // We wait 50ms instead of waiting for a response, because
 532                // waiting for a response would require us to wait on the main thread
 533                // which we want to avoid in an `on_app_quit` callback.
 534                smol::Timer::after(Duration::from_millis(50)).await;
 535            }
 536
 537            // Drop `multiplex_task` because it owns our ssh_proxy_process, which is a
 538            // child of master_process.
 539            drop(multiplex_task);
 540            // Now drop the rest of state, which kills master process.
 541            drop(heartbeat_task);
 542            drop(ssh_connection);
 543            drop(delegate);
 544        })
 545    }
 546
 547    fn reconnect(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
 548        let mut lock = self.state.lock();
 549
 550        let can_reconnect = lock
 551            .as_ref()
 552            .map(|state| state.can_reconnect())
 553            .unwrap_or(false);
 554        if !can_reconnect {
 555            let error = if let Some(state) = lock.as_ref() {
 556                format!("invalid state, cannot reconnect while in state {state}")
 557            } else {
 558                "no state set".to_string()
 559            };
 560            log::info!("aborting reconnect, because not in state that allows reconnecting");
 561            return Err(anyhow!(error));
 562        }
 563
 564        let state = lock.take().unwrap();
 565        let (attempts, mut ssh_connection, delegate) = match state {
 566            State::Connected {
 567                ssh_connection,
 568                delegate,
 569                multiplex_task,
 570                heartbeat_task,
 571            }
 572            | State::HeartbeatMissed {
 573                ssh_connection,
 574                delegate,
 575                multiplex_task,
 576                heartbeat_task,
 577                ..
 578            } => {
 579                drop(multiplex_task);
 580                drop(heartbeat_task);
 581                (0, ssh_connection, delegate)
 582            }
 583            State::ReconnectFailed {
 584                attempts,
 585                ssh_connection,
 586                delegate,
 587                ..
 588            } => (attempts, ssh_connection, delegate),
 589            State::Connecting
 590            | State::Reconnecting
 591            | State::ReconnectExhausted
 592            | State::ServerNotRunning => unreachable!(),
 593        };
 594
 595        let attempts = attempts + 1;
 596        if attempts > MAX_RECONNECT_ATTEMPTS {
 597            log::error!(
 598                "Failed to reconnect to after {} attempts, giving up",
 599                MAX_RECONNECT_ATTEMPTS
 600            );
 601            drop(lock);
 602            self.set_state(State::ReconnectExhausted, cx);
 603            return Ok(());
 604        }
 605        drop(lock);
 606
 607        self.set_state(State::Reconnecting, cx);
 608
 609        log::info!("Trying to reconnect to ssh server... Attempt {}", attempts);
 610
 611        let identifier = self.unique_identifier.clone();
 612        let client = self.client.clone();
 613        let reconnect_task = cx.spawn(|this, mut cx| async move {
 614            macro_rules! failed {
 615                ($error:expr, $attempts:expr, $ssh_connection:expr, $delegate:expr) => {
 616                    return State::ReconnectFailed {
 617                        error: anyhow!($error),
 618                        attempts: $attempts,
 619                        ssh_connection: $ssh_connection,
 620                        delegate: $delegate,
 621                    };
 622                };
 623            }
 624
 625            if let Err(error) = ssh_connection
 626                .kill()
 627                .await
 628                .context("Failed to kill ssh process")
 629            {
 630                failed!(error, attempts, ssh_connection, delegate);
 631            };
 632
 633            let connection_options = ssh_connection.connection_options();
 634
 635            let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
 636            let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
 637            let (connection_activity_tx, connection_activity_rx) = mpsc::channel::<()>(1);
 638
 639            let (ssh_connection, io_task) = match Self::establish_connection(
 640                identifier,
 641                true,
 642                connection_options,
 643                incoming_tx,
 644                outgoing_rx,
 645                connection_activity_tx,
 646                delegate.clone(),
 647                &mut cx,
 648            )
 649            .await
 650            {
 651                Ok((ssh_connection, ssh_process)) => (ssh_connection, ssh_process),
 652                Err(error) => {
 653                    failed!(error, attempts, ssh_connection, delegate);
 654                }
 655            };
 656
 657            let multiplex_task = Self::monitor(this.clone(), io_task, &cx);
 658            client.reconnect(incoming_rx, outgoing_tx, &cx);
 659
 660            if let Err(error) = client.resync(HEARTBEAT_TIMEOUT).await {
 661                failed!(error, attempts, ssh_connection, delegate);
 662            };
 663
 664            State::Connected {
 665                ssh_connection,
 666                delegate,
 667                multiplex_task,
 668                heartbeat_task: Self::heartbeat(this.clone(), connection_activity_rx, &mut cx),
 669            }
 670        });
 671
 672        cx.spawn(|this, mut cx| async move {
 673            let new_state = reconnect_task.await;
 674            this.update(&mut cx, |this, cx| {
 675                this.try_set_state(cx, |old_state| {
 676                    if old_state.is_reconnecting() {
 677                        match &new_state {
 678                            State::Connecting
 679                            | State::Reconnecting { .. }
 680                            | State::HeartbeatMissed { .. }
 681                            | State::ServerNotRunning => {}
 682                            State::Connected { .. } => {
 683                                log::info!("Successfully reconnected");
 684                            }
 685                            State::ReconnectFailed {
 686                                error, attempts, ..
 687                            } => {
 688                                log::error!(
 689                                    "Reconnect attempt {} failed: {:?}. Starting new attempt...",
 690                                    attempts,
 691                                    error
 692                                );
 693                            }
 694                            State::ReconnectExhausted => {
 695                                log::error!("Reconnect attempt failed and all attempts exhausted");
 696                            }
 697                        }
 698                        Some(new_state)
 699                    } else {
 700                        None
 701                    }
 702                });
 703
 704                if this.state_is(State::is_reconnect_failed) {
 705                    this.reconnect(cx)
 706                } else if this.state_is(State::is_reconnect_exhausted) {
 707                    Ok(())
 708                } else {
 709                    log::debug!("State has transition from Reconnecting into new state while attempting reconnect.");
 710                    Ok(())
 711                }
 712            })
 713        })
 714        .detach_and_log_err(cx);
 715
 716        Ok(())
 717    }
 718
 719    fn heartbeat(
 720        this: WeakModel<Self>,
 721        mut connection_activity_rx: mpsc::Receiver<()>,
 722        cx: &mut AsyncAppContext,
 723    ) -> Task<Result<()>> {
 724        let Ok(client) = this.update(cx, |this, _| this.client.clone()) else {
 725            return Task::ready(Err(anyhow!("SshRemoteClient lost")));
 726        };
 727
 728        cx.spawn(|mut cx| {
 729            let this = this.clone();
 730            async move {
 731                let mut missed_heartbeats = 0;
 732
 733                let keepalive_timer = cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse();
 734                futures::pin_mut!(keepalive_timer);
 735
 736                loop {
 737                    select_biased! {
 738                        result = connection_activity_rx.next().fuse() => {
 739                            if result.is_none() {
 740                                log::warn!("ssh heartbeat: connection activity channel has been dropped. stopping.");
 741                                return Ok(());
 742                            }
 743
 744                            keepalive_timer.set(cx.background_executor().timer(HEARTBEAT_INTERVAL).fuse());
 745
 746                            if missed_heartbeats != 0 {
 747                                missed_heartbeats = 0;
 748                                this.update(&mut cx, |this, mut cx| {
 749                                    this.handle_heartbeat_result(missed_heartbeats, &mut cx)
 750                                })?;
 751                            }
 752                        }
 753                        _ = keepalive_timer => {
 754                            log::debug!("Sending heartbeat to server...");
 755
 756                            let result = select_biased! {
 757                                _ = connection_activity_rx.next().fuse() => {
 758                                    Ok(())
 759                                }
 760                                ping_result = client.ping(HEARTBEAT_TIMEOUT).fuse() => {
 761                                    ping_result
 762                                }
 763                            };
 764
 765                            if result.is_err() {
 766                                missed_heartbeats += 1;
 767                                log::warn!(
 768                                    "No heartbeat from server after {:?}. Missed heartbeat {} out of {}.",
 769                                    HEARTBEAT_TIMEOUT,
 770                                    missed_heartbeats,
 771                                    MAX_MISSED_HEARTBEATS
 772                                );
 773                            } else if missed_heartbeats != 0 {
 774                                missed_heartbeats = 0;
 775                            } else {
 776                                continue;
 777                            }
 778
 779                            let result = this.update(&mut cx, |this, mut cx| {
 780                                this.handle_heartbeat_result(missed_heartbeats, &mut cx)
 781                            })?;
 782                            if result.is_break() {
 783                                return Ok(());
 784                            }
 785                        }
 786                    }
 787                }
 788            }
 789        })
 790    }
 791
 792    fn handle_heartbeat_result(
 793        &mut self,
 794        missed_heartbeats: usize,
 795        cx: &mut ModelContext<Self>,
 796    ) -> ControlFlow<()> {
 797        let state = self.state.lock().take().unwrap();
 798        let next_state = if missed_heartbeats > 0 {
 799            state.heartbeat_missed()
 800        } else {
 801            state.heartbeat_recovered()
 802        };
 803
 804        self.set_state(next_state, cx);
 805
 806        if missed_heartbeats >= MAX_MISSED_HEARTBEATS {
 807            log::error!(
 808                "Missed last {} heartbeats. Reconnecting...",
 809                missed_heartbeats
 810            );
 811
 812            self.reconnect(cx)
 813                .context("failed to start reconnect process after missing heartbeats")
 814                .log_err();
 815            ControlFlow::Break(())
 816        } else {
 817            ControlFlow::Continue(())
 818        }
 819    }
 820
 821    fn multiplex(
 822        mut ssh_proxy_process: Child,
 823        incoming_tx: UnboundedSender<Envelope>,
 824        mut outgoing_rx: UnboundedReceiver<Envelope>,
 825        mut connection_activity_tx: Sender<()>,
 826        cx: &AsyncAppContext,
 827    ) -> Task<Result<i32>> {
 828        let mut child_stderr = ssh_proxy_process.stderr.take().unwrap();
 829        let mut child_stdout = ssh_proxy_process.stdout.take().unwrap();
 830        let mut child_stdin = ssh_proxy_process.stdin.take().unwrap();
 831
 832        let mut stdin_buffer = Vec::new();
 833        let mut stdout_buffer = Vec::new();
 834        let mut stderr_buffer = Vec::new();
 835        let mut stderr_offset = 0;
 836
 837        let stdin_task = cx.background_executor().spawn(async move {
 838            while let Some(outgoing) = outgoing_rx.next().await {
 839                write_message(&mut child_stdin, &mut stdin_buffer, outgoing).await?;
 840            }
 841            anyhow::Ok(())
 842        });
 843
 844        let stdout_task = cx.background_executor().spawn({
 845            let mut connection_activity_tx = connection_activity_tx.clone();
 846            async move {
 847                loop {
 848                    stdout_buffer.resize(MESSAGE_LEN_SIZE, 0);
 849                    let len = child_stdout.read(&mut stdout_buffer).await?;
 850
 851                    if len == 0 {
 852                        return anyhow::Ok(());
 853                    }
 854
 855                    if len < MESSAGE_LEN_SIZE {
 856                        child_stdout.read_exact(&mut stdout_buffer[len..]).await?;
 857                    }
 858
 859                    let message_len = message_len_from_buffer(&stdout_buffer);
 860                    let envelope =
 861                        read_message_with_len(&mut child_stdout, &mut stdout_buffer, message_len)
 862                            .await?;
 863                    connection_activity_tx.try_send(()).ok();
 864                    incoming_tx.unbounded_send(envelope).ok();
 865                }
 866            }
 867        });
 868
 869        let stderr_task: Task<anyhow::Result<()>> = cx.background_executor().spawn(async move {
 870            loop {
 871                stderr_buffer.resize(stderr_offset + 1024, 0);
 872
 873                let len = child_stderr
 874                    .read(&mut stderr_buffer[stderr_offset..])
 875                    .await?;
 876                if len == 0 {
 877                    return Err(anyhow!("stderr is closed"));
 878                }
 879
 880                stderr_offset += len;
 881                let mut start_ix = 0;
 882                while let Some(ix) = stderr_buffer[start_ix..stderr_offset]
 883                    .iter()
 884                    .position(|b| b == &b'\n')
 885                {
 886                    let line_ix = start_ix + ix;
 887                    let content = &stderr_buffer[start_ix..line_ix];
 888                    start_ix = line_ix + 1;
 889                    if let Ok(record) = serde_json::from_slice::<LogRecord>(content) {
 890                        record.log(log::logger())
 891                    } else {
 892                        eprintln!("(remote) {}", String::from_utf8_lossy(content));
 893                    }
 894                }
 895                stderr_buffer.drain(0..start_ix);
 896                stderr_offset -= start_ix;
 897
 898                connection_activity_tx.try_send(()).ok();
 899            }
 900        });
 901
 902        cx.spawn(|_| async move {
 903            let result = futures::select! {
 904                result = stdin_task.fuse() => {
 905                    result.context("stdin")
 906                }
 907                result = stdout_task.fuse() => {
 908                    result.context("stdout")
 909                }
 910                result = stderr_task.fuse() => {
 911                    result.context("stderr")
 912                }
 913            };
 914
 915            match result {
 916                Ok(_) => Ok(ssh_proxy_process.status().await?.code().unwrap_or(1)),
 917                Err(error) => Err(error),
 918            }
 919        })
 920    }
 921
 922    fn monitor(
 923        this: WeakModel<Self>,
 924        io_task: Task<Result<i32>>,
 925        cx: &AsyncAppContext,
 926    ) -> Task<Result<()>> {
 927        cx.spawn(|mut cx| async move {
 928            let result = io_task.await;
 929
 930            match result {
 931                Ok(exit_code) => {
 932                    if let Some(error) = ProxyLaunchError::from_exit_code(exit_code) {
 933                        match error {
 934                            ProxyLaunchError::ServerNotRunning => {
 935                                log::error!("failed to reconnect because server is not running");
 936                                this.update(&mut cx, |this, cx| {
 937                                    this.set_state(State::ServerNotRunning, cx);
 938                                })?;
 939                            }
 940                        }
 941                    } else if exit_code > 0 {
 942                        log::error!("proxy process terminated unexpectedly");
 943                        this.update(&mut cx, |this, cx| {
 944                            this.reconnect(cx).ok();
 945                        })?;
 946                    }
 947                }
 948                Err(error) => {
 949                    log::warn!("ssh io task died with error: {:?}. reconnecting...", error);
 950                    this.update(&mut cx, |this, cx| {
 951                        this.reconnect(cx).ok();
 952                    })?;
 953                }
 954            }
 955
 956            Ok(())
 957        })
 958    }
 959
 960    fn state_is(&self, check: impl FnOnce(&State) -> bool) -> bool {
 961        self.state.lock().as_ref().map_or(false, check)
 962    }
 963
 964    fn try_set_state(
 965        &self,
 966        cx: &mut ModelContext<Self>,
 967        map: impl FnOnce(&State) -> Option<State>,
 968    ) {
 969        let mut lock = self.state.lock();
 970        let new_state = lock.as_ref().and_then(map);
 971
 972        if let Some(new_state) = new_state {
 973            lock.replace(new_state);
 974            cx.notify();
 975        }
 976    }
 977
 978    fn set_state(&self, state: State, cx: &mut ModelContext<Self>) {
 979        log::info!("setting state to '{}'", &state);
 980
 981        let is_reconnect_exhausted = state.is_reconnect_exhausted();
 982        let is_server_not_running = state.is_server_not_running();
 983        self.state.lock().replace(state);
 984
 985        if is_reconnect_exhausted || is_server_not_running {
 986            cx.emit(SshRemoteEvent::Disconnected);
 987        }
 988        cx.notify();
 989    }
 990
 991    #[allow(clippy::too_many_arguments)]
 992    async fn establish_connection(
 993        unique_identifier: String,
 994        reconnect: bool,
 995        connection_options: SshConnectionOptions,
 996        incoming_tx: UnboundedSender<Envelope>,
 997        outgoing_rx: UnboundedReceiver<Envelope>,
 998        connection_activity_tx: Sender<()>,
 999        delegate: Arc<dyn SshClientDelegate>,
1000        cx: &mut AsyncAppContext,
1001    ) -> Result<(Box<dyn SshRemoteProcess>, Task<Result<i32>>)> {
1002        #[cfg(any(test, feature = "test-support"))]
1003        if let Some(fake) = fake::SshRemoteConnection::new(&connection_options) {
1004            let io_task = fake::SshRemoteConnection::multiplex(
1005                fake.connection_options(),
1006                incoming_tx,
1007                outgoing_rx,
1008                connection_activity_tx,
1009                cx,
1010            )
1011            .await;
1012            return Ok((fake, io_task));
1013        }
1014
1015        let ssh_connection =
1016            SshRemoteConnection::new(connection_options, delegate.clone(), cx).await?;
1017
1018        let platform = ssh_connection.query_platform().await?;
1019        let remote_binary_path = delegate.remote_server_binary_path(platform, cx)?;
1020        if !reconnect {
1021            ssh_connection
1022                .ensure_server_binary(&delegate, &remote_binary_path, platform, cx)
1023                .await?;
1024        }
1025
1026        let socket = ssh_connection.socket.clone();
1027        run_cmd(socket.ssh_command(&remote_binary_path).arg("version")).await?;
1028
1029        delegate.set_status(Some("Starting proxy"), cx);
1030
1031        let mut start_proxy_command = format!(
1032            "RUST_LOG={} RUST_BACKTRACE={} {:?} proxy --identifier {}",
1033            std::env::var("RUST_LOG").unwrap_or_default(),
1034            std::env::var("RUST_BACKTRACE").unwrap_or_default(),
1035            remote_binary_path,
1036            unique_identifier,
1037        );
1038        if reconnect {
1039            start_proxy_command.push_str(" --reconnect");
1040        }
1041
1042        let ssh_proxy_process = socket
1043            .ssh_command(start_proxy_command)
1044            // IMPORTANT: we kill this process when we drop the task that uses it.
1045            .kill_on_drop(true)
1046            .spawn()
1047            .context("failed to spawn remote server")?;
1048
1049        let io_task = Self::multiplex(
1050            ssh_proxy_process,
1051            incoming_tx,
1052            outgoing_rx,
1053            connection_activity_tx,
1054            &cx,
1055        );
1056
1057        Ok((Box::new(ssh_connection), io_task))
1058    }
1059
1060    pub fn subscribe_to_entity<E: 'static>(&self, remote_id: u64, entity: &Model<E>) {
1061        self.client.subscribe_to_entity(remote_id, entity);
1062    }
1063
1064    pub fn ssh_args(&self) -> Option<Vec<String>> {
1065        self.state
1066            .lock()
1067            .as_ref()
1068            .and_then(|state| state.ssh_connection())
1069            .map(|ssh_connection| ssh_connection.ssh_args())
1070    }
1071
1072    pub fn proto_client(&self) -> AnyProtoClient {
1073        self.client.clone().into()
1074    }
1075
1076    pub fn connection_string(&self) -> String {
1077        self.connection_options.connection_string()
1078    }
1079
1080    pub fn connection_options(&self) -> SshConnectionOptions {
1081        self.connection_options.clone()
1082    }
1083
1084    pub fn connection_state(&self) -> ConnectionState {
1085        self.state
1086            .lock()
1087            .as_ref()
1088            .map(ConnectionState::from)
1089            .unwrap_or(ConnectionState::Disconnected)
1090    }
1091
1092    pub fn is_disconnected(&self) -> bool {
1093        self.connection_state() == ConnectionState::Disconnected
1094    }
1095
1096    #[cfg(any(test, feature = "test-support"))]
1097    pub fn simulate_disconnect(&self, client_cx: &mut AppContext) -> Task<()> {
1098        let port = self.connection_options().port.unwrap();
1099        client_cx.spawn(|cx| async move {
1100            let (channel, server_cx) = cx
1101                .update_global(|c: &mut fake::ServerConnections, _| c.get(port))
1102                .unwrap();
1103
1104            let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
1105            let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
1106            channel.reconnect(incoming_rx, outgoing_tx, &server_cx);
1107        })
1108    }
1109
1110    #[cfg(any(test, feature = "test-support"))]
1111    pub fn fake_server(
1112        client_cx: &mut gpui::TestAppContext,
1113        server_cx: &mut gpui::TestAppContext,
1114    ) -> (u16, Arc<ChannelClient>) {
1115        use gpui::BorrowAppContext;
1116        let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
1117        let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
1118        let server_client =
1119            server_cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx, "fake-server"));
1120        let port = client_cx.update(|cx| {
1121            cx.update_default_global(|c: &mut fake::ServerConnections, _| {
1122                c.push(server_client.clone(), server_cx.to_async())
1123            })
1124        });
1125        (port, server_client)
1126    }
1127
1128    #[cfg(any(test, feature = "test-support"))]
1129    pub async fn fake_client(port: u16, client_cx: &mut gpui::TestAppContext) -> Model<Self> {
1130        client_cx
1131            .update(|cx| {
1132                Self::new(
1133                    "fake".to_string(),
1134                    SshConnectionOptions {
1135                        host: "<fake>".to_string(),
1136                        port: Some(port),
1137                        ..Default::default()
1138                    },
1139                    Arc::new(fake::Delegate),
1140                    cx,
1141                )
1142            })
1143            .await
1144            .unwrap()
1145    }
1146}
1147
1148impl From<SshRemoteClient> for AnyProtoClient {
1149    fn from(client: SshRemoteClient) -> Self {
1150        AnyProtoClient::new(client.client.clone())
1151    }
1152}
1153
1154#[async_trait]
1155trait SshRemoteProcess: Send + Sync {
1156    async fn kill(&mut self) -> Result<()>;
1157    fn ssh_args(&self) -> Vec<String>;
1158    fn connection_options(&self) -> SshConnectionOptions;
1159}
1160
1161struct SshRemoteConnection {
1162    socket: SshSocket,
1163    master_process: process::Child,
1164    _temp_dir: TempDir,
1165}
1166
1167impl Drop for SshRemoteConnection {
1168    fn drop(&mut self) {
1169        if let Err(error) = self.master_process.kill() {
1170            log::error!("failed to kill SSH master process: {}", error);
1171        }
1172    }
1173}
1174
1175#[async_trait]
1176impl SshRemoteProcess for SshRemoteConnection {
1177    async fn kill(&mut self) -> Result<()> {
1178        self.master_process.kill()?;
1179
1180        self.master_process.status().await?;
1181
1182        Ok(())
1183    }
1184
1185    fn ssh_args(&self) -> Vec<String> {
1186        self.socket.ssh_args()
1187    }
1188
1189    fn connection_options(&self) -> SshConnectionOptions {
1190        self.socket.connection_options.clone()
1191    }
1192}
1193
1194impl SshRemoteConnection {
1195    #[cfg(not(unix))]
1196    async fn new(
1197        _connection_options: SshConnectionOptions,
1198        _delegate: Arc<dyn SshClientDelegate>,
1199        _cx: &mut AsyncAppContext,
1200    ) -> Result<Self> {
1201        Err(anyhow!("ssh is not supported on this platform"))
1202    }
1203
1204    #[cfg(unix)]
1205    async fn new(
1206        connection_options: SshConnectionOptions,
1207        delegate: Arc<dyn SshClientDelegate>,
1208        cx: &mut AsyncAppContext,
1209    ) -> Result<Self> {
1210        use futures::AsyncWriteExt as _;
1211        use futures::{io::BufReader, AsyncBufReadExt as _};
1212        use smol::{fs::unix::PermissionsExt as _, net::unix::UnixListener};
1213        use util::ResultExt as _;
1214
1215        delegate.set_status(Some("Connecting"), cx);
1216
1217        let url = connection_options.ssh_url();
1218        let temp_dir = tempfile::Builder::new()
1219            .prefix("zed-ssh-session")
1220            .tempdir()?;
1221
1222        // Create a domain socket listener to handle requests from the askpass program.
1223        let askpass_socket = temp_dir.path().join("askpass.sock");
1224        let (askpass_opened_tx, askpass_opened_rx) = oneshot::channel::<()>();
1225        let listener =
1226            UnixListener::bind(&askpass_socket).context("failed to create askpass socket")?;
1227
1228        let askpass_task = cx.spawn({
1229            let delegate = delegate.clone();
1230            |mut cx| async move {
1231                let mut askpass_opened_tx = Some(askpass_opened_tx);
1232
1233                while let Ok((mut stream, _)) = listener.accept().await {
1234                    if let Some(askpass_opened_tx) = askpass_opened_tx.take() {
1235                        askpass_opened_tx.send(()).ok();
1236                    }
1237                    let mut buffer = Vec::new();
1238                    let mut reader = BufReader::new(&mut stream);
1239                    if reader.read_until(b'\0', &mut buffer).await.is_err() {
1240                        buffer.clear();
1241                    }
1242                    let password_prompt = String::from_utf8_lossy(&buffer);
1243                    if let Some(password) = delegate
1244                        .ask_password(password_prompt.to_string(), &mut cx)
1245                        .await
1246                        .context("failed to get ssh password")
1247                        .and_then(|p| p)
1248                        .log_err()
1249                    {
1250                        stream.write_all(password.as_bytes()).await.log_err();
1251                    }
1252                }
1253            }
1254        });
1255
1256        // Create an askpass script that communicates back to this process.
1257        let askpass_script = format!(
1258            "{shebang}\n{print_args} | nc -U {askpass_socket} 2> /dev/null \n",
1259            askpass_socket = askpass_socket.display(),
1260            print_args = "printf '%s\\0' \"$@\"",
1261            shebang = "#!/bin/sh",
1262        );
1263        let askpass_script_path = temp_dir.path().join("askpass.sh");
1264        fs::write(&askpass_script_path, askpass_script).await?;
1265        fs::set_permissions(&askpass_script_path, std::fs::Permissions::from_mode(0o755)).await?;
1266
1267        // Start the master SSH process, which does not do anything except for establish
1268        // the connection and keep it open, allowing other ssh commands to reuse it
1269        // via a control socket.
1270        let socket_path = temp_dir.path().join("ssh.sock");
1271        let mut master_process = process::Command::new("ssh")
1272            .stdin(Stdio::null())
1273            .stdout(Stdio::piped())
1274            .stderr(Stdio::piped())
1275            .env("SSH_ASKPASS_REQUIRE", "force")
1276            .env("SSH_ASKPASS", &askpass_script_path)
1277            .args(connection_options.additional_args().unwrap_or(&Vec::new()))
1278            .args([
1279                "-N",
1280                "-o",
1281                "ControlPersist=no",
1282                "-o",
1283                "ControlMaster=yes",
1284                "-o",
1285            ])
1286            .arg(format!("ControlPath={}", socket_path.display()))
1287            .arg(&url)
1288            .spawn()?;
1289
1290        // Wait for this ssh process to close its stdout, indicating that authentication
1291        // has completed.
1292        let stdout = master_process.stdout.as_mut().unwrap();
1293        let mut output = Vec::new();
1294        let connection_timeout = Duration::from_secs(10);
1295
1296        let result = select_biased! {
1297            _ = askpass_opened_rx.fuse() => {
1298                // If the askpass script has opened, that means the user is typing
1299                // their password, in which case we don't want to timeout anymore,
1300                // since we know a connection has been established.
1301                stdout.read_to_end(&mut output).await?;
1302                Ok(())
1303            }
1304            result = stdout.read_to_end(&mut output).fuse() => {
1305                result?;
1306                Ok(())
1307            }
1308            _ = futures::FutureExt::fuse(smol::Timer::after(connection_timeout)) => {
1309                Err(anyhow!("Exceeded {:?} timeout trying to connect to host", connection_timeout))
1310            }
1311        };
1312
1313        if let Err(e) = result {
1314            return Err(e.context("Failed to connect to host"));
1315        }
1316
1317        drop(askpass_task);
1318
1319        if master_process.try_status()?.is_some() {
1320            output.clear();
1321            let mut stderr = master_process.stderr.take().unwrap();
1322            stderr.read_to_end(&mut output).await?;
1323
1324            let error_message = format!(
1325                "failed to connect: {}",
1326                String::from_utf8_lossy(&output).trim()
1327            );
1328            Err(anyhow!(error_message))?;
1329        }
1330
1331        Ok(Self {
1332            socket: SshSocket {
1333                connection_options,
1334                socket_path,
1335            },
1336            master_process,
1337            _temp_dir: temp_dir,
1338        })
1339    }
1340
1341    async fn ensure_server_binary(
1342        &self,
1343        delegate: &Arc<dyn SshClientDelegate>,
1344        dst_path: &Path,
1345        platform: SshPlatform,
1346        cx: &mut AsyncAppContext,
1347    ) -> Result<()> {
1348        if std::env::var("ZED_USE_CACHED_REMOTE_SERVER").is_ok() {
1349            if let Ok(installed_version) =
1350                run_cmd(self.socket.ssh_command(dst_path).arg("version")).await
1351            {
1352                log::info!("using cached server binary version {}", installed_version);
1353                return Ok(());
1354            }
1355        }
1356
1357        let mut dst_path_gz = dst_path.to_path_buf();
1358        dst_path_gz.set_extension("gz");
1359
1360        if let Some(parent) = dst_path.parent() {
1361            run_cmd(self.socket.ssh_command("mkdir").arg("-p").arg(parent)).await?;
1362        }
1363
1364        let (src_path, version) = delegate.get_server_binary(platform, cx).await??;
1365
1366        let mut server_binary_exists = false;
1367        if !server_binary_exists && cfg!(not(debug_assertions)) {
1368            if let Ok(installed_version) =
1369                run_cmd(self.socket.ssh_command(dst_path).arg("version")).await
1370            {
1371                if installed_version.trim() == version.to_string() {
1372                    server_binary_exists = true;
1373                }
1374            }
1375        }
1376
1377        if server_binary_exists {
1378            log::info!("remote development server already present",);
1379            return Ok(());
1380        }
1381
1382        let src_stat = fs::metadata(&src_path).await?;
1383        let size = src_stat.len();
1384        let server_mode = 0o755;
1385
1386        let t0 = Instant::now();
1387        delegate.set_status(Some("Uploading remote development server"), cx);
1388        log::info!("uploading remote development server ({}kb)", size / 1024);
1389        self.upload_file(&src_path, &dst_path_gz)
1390            .await
1391            .context("failed to upload server binary")?;
1392        log::info!("uploaded remote development server in {:?}", t0.elapsed());
1393
1394        delegate.set_status(Some("Extracting remote development server"), cx);
1395        run_cmd(
1396            self.socket
1397                .ssh_command("gunzip")
1398                .arg("--force")
1399                .arg(&dst_path_gz),
1400        )
1401        .await?;
1402
1403        delegate.set_status(Some("Marking remote development server executable"), cx);
1404        run_cmd(
1405            self.socket
1406                .ssh_command("chmod")
1407                .arg(format!("{:o}", server_mode))
1408                .arg(dst_path),
1409        )
1410        .await?;
1411
1412        Ok(())
1413    }
1414
1415    async fn query_platform(&self) -> Result<SshPlatform> {
1416        let os = run_cmd(self.socket.ssh_command("uname").arg("-s")).await?;
1417        let arch = run_cmd(self.socket.ssh_command("uname").arg("-m")).await?;
1418
1419        let os = match os.trim() {
1420            "Darwin" => "macos",
1421            "Linux" => "linux",
1422            _ => Err(anyhow!("unknown uname os {os:?}"))?,
1423        };
1424        let arch = if arch.starts_with("arm") || arch.starts_with("aarch64") {
1425            "aarch64"
1426        } else if arch.starts_with("x86") || arch.starts_with("i686") {
1427            "x86_64"
1428        } else {
1429            Err(anyhow!("unknown uname architecture {arch:?}"))?
1430        };
1431
1432        Ok(SshPlatform { os, arch })
1433    }
1434
1435    async fn upload_file(&self, src_path: &Path, dest_path: &Path) -> Result<()> {
1436        let mut command = process::Command::new("scp");
1437        let output = self
1438            .socket
1439            .ssh_options(&mut command)
1440            .args(
1441                self.socket
1442                    .connection_options
1443                    .port
1444                    .map(|port| vec!["-P".to_string(), port.to_string()])
1445                    .unwrap_or_default(),
1446            )
1447            .arg(src_path)
1448            .arg(format!(
1449                "{}:{}",
1450                self.socket.connection_options.scp_url(),
1451                dest_path.display()
1452            ))
1453            .output()
1454            .await?;
1455
1456        if output.status.success() {
1457            Ok(())
1458        } else {
1459            Err(anyhow!(
1460                "failed to upload file {} -> {}: {}",
1461                src_path.display(),
1462                dest_path.display(),
1463                String::from_utf8_lossy(&output.stderr)
1464            ))
1465        }
1466    }
1467}
1468
1469type ResponseChannels = Mutex<HashMap<MessageId, oneshot::Sender<(Envelope, oneshot::Sender<()>)>>>;
1470
1471pub struct ChannelClient {
1472    next_message_id: AtomicU32,
1473    outgoing_tx: Mutex<mpsc::UnboundedSender<Envelope>>,
1474    buffer: Mutex<VecDeque<Envelope>>,
1475    response_channels: ResponseChannels,
1476    message_handlers: Mutex<ProtoMessageHandlerSet>,
1477    max_received: AtomicU32,
1478    name: &'static str,
1479    task: Mutex<Task<Result<()>>>,
1480}
1481
1482impl ChannelClient {
1483    pub fn new(
1484        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1485        outgoing_tx: mpsc::UnboundedSender<Envelope>,
1486        cx: &AppContext,
1487        name: &'static str,
1488    ) -> Arc<Self> {
1489        Arc::new_cyclic(|this| Self {
1490            outgoing_tx: Mutex::new(outgoing_tx),
1491            next_message_id: AtomicU32::new(0),
1492            max_received: AtomicU32::new(0),
1493            response_channels: ResponseChannels::default(),
1494            message_handlers: Default::default(),
1495            buffer: Mutex::new(VecDeque::new()),
1496            name,
1497            task: Mutex::new(Self::start_handling_messages(
1498                this.clone(),
1499                incoming_rx,
1500                &cx.to_async(),
1501            )),
1502        })
1503    }
1504
1505    fn start_handling_messages(
1506        this: Weak<Self>,
1507        mut incoming_rx: mpsc::UnboundedReceiver<Envelope>,
1508        cx: &AsyncAppContext,
1509    ) -> Task<Result<()>> {
1510        cx.spawn(|cx| {
1511            async move {
1512                let peer_id = PeerId { owner_id: 0, id: 0 };
1513                while let Some(incoming) = incoming_rx.next().await {
1514                    let Some(this) = this.upgrade() else {
1515                        return anyhow::Ok(());
1516                    };
1517                    if let Some(ack_id) = incoming.ack_id {
1518                        let mut buffer = this.buffer.lock();
1519                        while buffer.front().is_some_and(|msg| msg.id <= ack_id) {
1520                            buffer.pop_front();
1521                        }
1522                    }
1523                    if let Some(proto::envelope::Payload::FlushBufferedMessages(_)) =
1524                        &incoming.payload
1525                    {
1526                        log::debug!("{}:ssh message received. name:FlushBufferedMessages", this.name);
1527                        {
1528                            let buffer = this.buffer.lock();
1529                            for envelope in buffer.iter() {
1530                                this.outgoing_tx.lock().unbounded_send(envelope.clone()).ok();
1531                            }
1532                        }
1533                        let mut envelope = proto::Ack{}.into_envelope(0, Some(incoming.id), None);
1534                        envelope.id = this.next_message_id.fetch_add(1, SeqCst);
1535                        this.outgoing_tx.lock().unbounded_send(envelope).ok();
1536                        continue;
1537                    }
1538
1539                    this.max_received.store(incoming.id, SeqCst);
1540
1541                    if let Some(request_id) = incoming.responding_to {
1542                        let request_id = MessageId(request_id);
1543                        let sender = this.response_channels.lock().remove(&request_id);
1544                        if let Some(sender) = sender {
1545                            let (tx, rx) = oneshot::channel();
1546                            if incoming.payload.is_some() {
1547                                sender.send((incoming, tx)).ok();
1548                            }
1549                            rx.await.ok();
1550                        }
1551                    } else if let Some(envelope) =
1552                        build_typed_envelope(peer_id, Instant::now(), incoming)
1553                    {
1554                        let type_name = envelope.payload_type_name();
1555                        if let Some(future) = ProtoMessageHandlerSet::handle_message(
1556                            &this.message_handlers,
1557                            envelope,
1558                            this.clone().into(),
1559                            cx.clone(),
1560                        ) {
1561                            log::debug!("{}:ssh message received. name:{type_name}", this.name);
1562                            cx.foreground_executor().spawn(async move {
1563                                match future.await {
1564                                    Ok(_) => {
1565                                        log::debug!("{}:ssh message handled. name:{type_name}", this.name);
1566                                    }
1567                                    Err(error) => {
1568                                        log::error!(
1569                                            "{}:error handling message. type:{type_name}, error:{error}", this.name,
1570                                        );
1571                                    }
1572                                }
1573                            }).detach()
1574                        } else {
1575                            log::error!("{}:unhandled ssh message name:{type_name}", this.name);
1576                        }
1577                    }
1578                }
1579                anyhow::Ok(())
1580            }
1581        })
1582    }
1583
1584    pub fn reconnect(
1585        self: &Arc<Self>,
1586        incoming_rx: UnboundedReceiver<Envelope>,
1587        outgoing_tx: UnboundedSender<Envelope>,
1588        cx: &AsyncAppContext,
1589    ) {
1590        *self.outgoing_tx.lock() = outgoing_tx;
1591        *self.task.lock() = Self::start_handling_messages(Arc::downgrade(self), incoming_rx, cx);
1592    }
1593
1594    pub fn subscribe_to_entity<E: 'static>(&self, remote_id: u64, entity: &Model<E>) {
1595        let id = (TypeId::of::<E>(), remote_id);
1596
1597        let mut message_handlers = self.message_handlers.lock();
1598        if message_handlers
1599            .entities_by_type_and_remote_id
1600            .contains_key(&id)
1601        {
1602            panic!("already subscribed to entity");
1603        }
1604
1605        message_handlers.entities_by_type_and_remote_id.insert(
1606            id,
1607            EntityMessageSubscriber::Entity {
1608                handle: entity.downgrade().into(),
1609            },
1610        );
1611    }
1612
1613    pub fn request<T: RequestMessage>(
1614        &self,
1615        payload: T,
1616    ) -> impl 'static + Future<Output = Result<T::Response>> {
1617        self.request_internal(payload, true)
1618    }
1619
1620    fn request_internal<T: RequestMessage>(
1621        &self,
1622        payload: T,
1623        use_buffer: bool,
1624    ) -> impl 'static + Future<Output = Result<T::Response>> {
1625        log::debug!("ssh request start. name:{}", T::NAME);
1626        let response =
1627            self.request_dynamic(payload.into_envelope(0, None, None), T::NAME, use_buffer);
1628        async move {
1629            let response = response.await?;
1630            log::debug!("ssh request finish. name:{}", T::NAME);
1631            T::Response::from_envelope(response)
1632                .ok_or_else(|| anyhow!("received a response of the wrong type"))
1633        }
1634    }
1635
1636    pub async fn resync(&self, timeout: Duration) -> Result<()> {
1637        smol::future::or(
1638            async {
1639                self.request_internal(proto::FlushBufferedMessages {}, false)
1640                    .await?;
1641
1642                for envelope in self.buffer.lock().iter() {
1643                    self.outgoing_tx
1644                        .lock()
1645                        .unbounded_send(envelope.clone())
1646                        .ok();
1647                }
1648                Ok(())
1649            },
1650            async {
1651                smol::Timer::after(timeout).await;
1652                Err(anyhow!("Timeout detected"))
1653            },
1654        )
1655        .await
1656    }
1657
1658    pub async fn ping(&self, timeout: Duration) -> Result<()> {
1659        smol::future::or(
1660            async {
1661                self.request(proto::Ping {}).await?;
1662                Ok(())
1663            },
1664            async {
1665                smol::Timer::after(timeout).await;
1666                Err(anyhow!("Timeout detected"))
1667            },
1668        )
1669        .await
1670    }
1671
1672    pub fn send<T: EnvelopedMessage>(&self, payload: T) -> Result<()> {
1673        log::debug!("ssh send name:{}", T::NAME);
1674        self.send_dynamic(payload.into_envelope(0, None, None))
1675    }
1676
1677    fn request_dynamic(
1678        &self,
1679        mut envelope: proto::Envelope,
1680        type_name: &'static str,
1681        use_buffer: bool,
1682    ) -> impl 'static + Future<Output = Result<proto::Envelope>> {
1683        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1684        let (tx, rx) = oneshot::channel();
1685        let mut response_channels_lock = self.response_channels.lock();
1686        response_channels_lock.insert(MessageId(envelope.id), tx);
1687        drop(response_channels_lock);
1688
1689        let result = if use_buffer {
1690            self.send_buffered(envelope)
1691        } else {
1692            self.send_unbuffered(envelope)
1693        };
1694        async move {
1695            if let Err(error) = &result {
1696                log::error!("failed to send message: {}", error);
1697                return Err(anyhow!("failed to send message: {}", error));
1698            }
1699
1700            let response = rx.await.context("connection lost")?.0;
1701            if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
1702                return Err(RpcError::from_proto(error, type_name));
1703            }
1704            Ok(response)
1705        }
1706    }
1707
1708    pub fn send_dynamic(&self, mut envelope: proto::Envelope) -> Result<()> {
1709        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
1710        self.send_buffered(envelope)
1711    }
1712
1713    fn send_buffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1714        envelope.ack_id = Some(self.max_received.load(SeqCst));
1715        self.buffer.lock().push_back(envelope.clone());
1716        // ignore errors on send (happen while we're reconnecting)
1717        // assume that the global "disconnected" overlay is sufficient.
1718        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1719        Ok(())
1720    }
1721
1722    fn send_unbuffered(&self, mut envelope: proto::Envelope) -> Result<()> {
1723        envelope.ack_id = Some(self.max_received.load(SeqCst));
1724        self.outgoing_tx.lock().unbounded_send(envelope).ok();
1725        Ok(())
1726    }
1727}
1728
1729impl ProtoClient for ChannelClient {
1730    fn request(
1731        &self,
1732        envelope: proto::Envelope,
1733        request_type: &'static str,
1734    ) -> BoxFuture<'static, Result<proto::Envelope>> {
1735        self.request_dynamic(envelope, request_type, true).boxed()
1736    }
1737
1738    fn send(&self, envelope: proto::Envelope, _message_type: &'static str) -> Result<()> {
1739        self.send_dynamic(envelope)
1740    }
1741
1742    fn send_response(&self, envelope: Envelope, _message_type: &'static str) -> anyhow::Result<()> {
1743        self.send_dynamic(envelope)
1744    }
1745
1746    fn message_handler_set(&self) -> &Mutex<ProtoMessageHandlerSet> {
1747        &self.message_handlers
1748    }
1749
1750    fn is_via_collab(&self) -> bool {
1751        false
1752    }
1753}
1754
1755#[cfg(any(test, feature = "test-support"))]
1756mod fake {
1757    use std::{path::PathBuf, sync::Arc};
1758
1759    use anyhow::Result;
1760    use async_trait::async_trait;
1761    use futures::{
1762        channel::{
1763            mpsc::{self, Sender},
1764            oneshot,
1765        },
1766        select_biased, FutureExt, SinkExt, StreamExt,
1767    };
1768    use gpui::{AsyncAppContext, BorrowAppContext, Global, SemanticVersion, Task};
1769    use rpc::proto::Envelope;
1770
1771    use super::{
1772        ChannelClient, SshClientDelegate, SshConnectionOptions, SshPlatform, SshRemoteProcess,
1773    };
1774
1775    pub(super) struct SshRemoteConnection {
1776        connection_options: SshConnectionOptions,
1777    }
1778
1779    impl SshRemoteConnection {
1780        pub(super) fn new(
1781            connection_options: &SshConnectionOptions,
1782        ) -> Option<Box<dyn SshRemoteProcess>> {
1783            if connection_options.host == "<fake>" {
1784                return Some(Box::new(Self {
1785                    connection_options: connection_options.clone(),
1786                }));
1787            }
1788            return None;
1789        }
1790        pub(super) async fn multiplex(
1791            connection_options: SshConnectionOptions,
1792            mut client_incoming_tx: mpsc::UnboundedSender<Envelope>,
1793            mut client_outgoing_rx: mpsc::UnboundedReceiver<Envelope>,
1794            mut connection_activity_tx: Sender<()>,
1795            cx: &mut AsyncAppContext,
1796        ) -> Task<Result<i32>> {
1797            let (mut server_incoming_tx, server_incoming_rx) = mpsc::unbounded::<Envelope>();
1798            let (server_outgoing_tx, mut server_outgoing_rx) = mpsc::unbounded::<Envelope>();
1799
1800            let (channel, server_cx) = cx
1801                .update(|cx| {
1802                    cx.update_global(|conns: &mut ServerConnections, _| {
1803                        conns.get(connection_options.port.unwrap())
1804                    })
1805                })
1806                .unwrap();
1807            channel.reconnect(server_incoming_rx, server_outgoing_tx, &server_cx);
1808
1809            // send to proxy_tx to get to the server.
1810            // receive from
1811
1812            cx.background_executor().spawn(async move {
1813                loop {
1814                    select_biased! {
1815                        server_to_client = server_outgoing_rx.next().fuse() => {
1816                            let Some(server_to_client) = server_to_client else {
1817                                return Ok(1)
1818                            };
1819                            connection_activity_tx.try_send(()).ok();
1820                            client_incoming_tx.send(server_to_client).await.ok();
1821                        }
1822                        client_to_server = client_outgoing_rx.next().fuse() => {
1823                            let Some(client_to_server) = client_to_server else {
1824                                return Ok(1)
1825                            };
1826                            server_incoming_tx.send(client_to_server).await.ok();
1827                        }
1828                    }
1829                }
1830            })
1831        }
1832    }
1833
1834    #[async_trait]
1835    impl SshRemoteProcess for SshRemoteConnection {
1836        async fn kill(&mut self) -> Result<()> {
1837            Ok(())
1838        }
1839
1840        fn ssh_args(&self) -> Vec<String> {
1841            Vec::new()
1842        }
1843
1844        fn connection_options(&self) -> SshConnectionOptions {
1845            self.connection_options.clone()
1846        }
1847    }
1848
1849    #[derive(Default)]
1850    pub(super) struct ServerConnections(Vec<(Arc<ChannelClient>, AsyncAppContext)>);
1851    impl Global for ServerConnections {}
1852
1853    impl ServerConnections {
1854        pub(super) fn push(&mut self, server: Arc<ChannelClient>, cx: AsyncAppContext) -> u16 {
1855            self.0.push((server.clone(), cx));
1856            self.0.len() as u16 - 1
1857        }
1858
1859        pub(super) fn get(&mut self, port: u16) -> (Arc<ChannelClient>, AsyncAppContext) {
1860            self.0
1861                .get(port as usize)
1862                .expect("no fake server for port")
1863                .clone()
1864        }
1865    }
1866
1867    pub(super) struct Delegate;
1868
1869    impl SshClientDelegate for Delegate {
1870        fn ask_password(
1871            &self,
1872            _: String,
1873            _: &mut AsyncAppContext,
1874        ) -> oneshot::Receiver<Result<String>> {
1875            unreachable!()
1876        }
1877        fn remote_server_binary_path(
1878            &self,
1879            _: SshPlatform,
1880            _: &mut AsyncAppContext,
1881        ) -> Result<PathBuf> {
1882            unreachable!()
1883        }
1884        fn get_server_binary(
1885            &self,
1886            _: SshPlatform,
1887            _: &mut AsyncAppContext,
1888        ) -> oneshot::Receiver<Result<(PathBuf, SemanticVersion)>> {
1889            unreachable!()
1890        }
1891        fn set_status(&self, _: Option<&str>, _: &mut AsyncAppContext) {
1892            unreachable!()
1893        }
1894    }
1895}