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