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!(
1553 "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
1554 ))?,
1555 };
1556 // exclude armv5,6,7 as they are 32-bit.
1557 let arch = if arch.starts_with("armv8")
1558 || arch.starts_with("armv9")
1559 || arch.starts_with("aarch64")
1560 {
1561 "aarch64"
1562 } else if arch.starts_with("x86") {
1563 "x86_64"
1564 } else {
1565 Err(anyhow!(
1566 "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
1567 ))?
1568 };
1569
1570 Ok(SshPlatform { os, arch })
1571 }
1572
1573 fn multiplex(
1574 mut ssh_proxy_process: Child,
1575 incoming_tx: UnboundedSender<Envelope>,
1576 mut outgoing_rx: UnboundedReceiver<Envelope>,
1577 mut connection_activity_tx: Sender<()>,
1578 cx: &AsyncAppContext,
1579 ) -> Task<Result<i32>> {
1580 let mut child_stderr = ssh_proxy_process.stderr.take().unwrap();
1581 let mut child_stdout = ssh_proxy_process.stdout.take().unwrap();
1582 let mut child_stdin = ssh_proxy_process.stdin.take().unwrap();
1583
1584 let mut stdin_buffer = Vec::new();
1585 let mut stdout_buffer = Vec::new();
1586 let mut stderr_buffer = Vec::new();
1587 let mut stderr_offset = 0;
1588
1589 let stdin_task = cx.background_executor().spawn(async move {
1590 while let Some(outgoing) = outgoing_rx.next().await {
1591 write_message(&mut child_stdin, &mut stdin_buffer, outgoing).await?;
1592 }
1593 anyhow::Ok(())
1594 });
1595
1596 let stdout_task = cx.background_executor().spawn({
1597 let mut connection_activity_tx = connection_activity_tx.clone();
1598 async move {
1599 loop {
1600 stdout_buffer.resize(MESSAGE_LEN_SIZE, 0);
1601 let len = child_stdout.read(&mut stdout_buffer).await?;
1602
1603 if len == 0 {
1604 return anyhow::Ok(());
1605 }
1606
1607 if len < MESSAGE_LEN_SIZE {
1608 child_stdout.read_exact(&mut stdout_buffer[len..]).await?;
1609 }
1610
1611 let message_len = message_len_from_buffer(&stdout_buffer);
1612 let envelope =
1613 read_message_with_len(&mut child_stdout, &mut stdout_buffer, message_len)
1614 .await?;
1615 connection_activity_tx.try_send(()).ok();
1616 incoming_tx.unbounded_send(envelope).ok();
1617 }
1618 }
1619 });
1620
1621 let stderr_task: Task<anyhow::Result<()>> = cx.background_executor().spawn(async move {
1622 loop {
1623 stderr_buffer.resize(stderr_offset + 1024, 0);
1624
1625 let len = child_stderr
1626 .read(&mut stderr_buffer[stderr_offset..])
1627 .await?;
1628 if len == 0 {
1629 return anyhow::Ok(());
1630 }
1631
1632 stderr_offset += len;
1633 let mut start_ix = 0;
1634 while let Some(ix) = stderr_buffer[start_ix..stderr_offset]
1635 .iter()
1636 .position(|b| b == &b'\n')
1637 {
1638 let line_ix = start_ix + ix;
1639 let content = &stderr_buffer[start_ix..line_ix];
1640 start_ix = line_ix + 1;
1641 if let Ok(record) = serde_json::from_slice::<LogRecord>(content) {
1642 record.log(log::logger())
1643 } else {
1644 eprintln!("(remote) {}", String::from_utf8_lossy(content));
1645 }
1646 }
1647 stderr_buffer.drain(0..start_ix);
1648 stderr_offset -= start_ix;
1649
1650 connection_activity_tx.try_send(()).ok();
1651 }
1652 });
1653
1654 cx.spawn(|_| async move {
1655 let result = futures::select! {
1656 result = stdin_task.fuse() => {
1657 result.context("stdin")
1658 }
1659 result = stdout_task.fuse() => {
1660 result.context("stdout")
1661 }
1662 result = stderr_task.fuse() => {
1663 result.context("stderr")
1664 }
1665 };
1666
1667 let status = ssh_proxy_process.status().await?.code().unwrap_or(1);
1668 match result {
1669 Ok(_) => Ok(status),
1670 Err(error) => Err(error),
1671 }
1672 })
1673 }
1674
1675 #[allow(unused)]
1676 async fn ensure_server_binary(
1677 &self,
1678 delegate: &Arc<dyn SshClientDelegate>,
1679 release_channel: ReleaseChannel,
1680 version: SemanticVersion,
1681 commit: Option<AppCommitSha>,
1682 cx: &mut AsyncAppContext,
1683 ) -> Result<PathBuf> {
1684 let version_str = match release_channel {
1685 ReleaseChannel::Nightly => {
1686 let commit = commit.map(|s| s.0.to_string()).unwrap_or_default();
1687
1688 format!("{}-{}", version, commit)
1689 }
1690 ReleaseChannel::Dev => "build".to_string(),
1691 _ => version.to_string(),
1692 };
1693 let binary_name = format!(
1694 "zed-remote-server-{}-{}",
1695 release_channel.dev_name(),
1696 version_str
1697 );
1698 let dst_path = paths::remote_server_dir_relative().join(binary_name);
1699 let tmp_path_gz = PathBuf::from(format!(
1700 "{}-download-{}.gz",
1701 dst_path.to_string_lossy(),
1702 std::process::id()
1703 ));
1704
1705 #[cfg(debug_assertions)]
1706 if std::env::var("ZED_BUILD_REMOTE_SERVER").is_ok() {
1707 let src_path = self
1708 .build_local(self.platform().await?, delegate, cx)
1709 .await?;
1710 self.upload_local_server_binary(&src_path, &tmp_path_gz, delegate, cx)
1711 .await?;
1712 self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
1713 .await?;
1714 return Ok(dst_path);
1715 }
1716
1717 if self
1718 .socket
1719 .run_command(&dst_path.to_string_lossy(), &["version"])
1720 .await
1721 .is_ok()
1722 {
1723 return Ok(dst_path);
1724 }
1725
1726 let wanted_version = cx.update(|cx| match release_channel {
1727 ReleaseChannel::Nightly => Ok(None),
1728 ReleaseChannel::Dev => {
1729 anyhow::bail!(
1730 "ZED_BUILD_REMOTE_SERVER is not set and no remote server exists at ({:?})",
1731 dst_path
1732 )
1733 }
1734 _ => Ok(Some(AppVersion::global(cx))),
1735 })??;
1736
1737 let platform = self.platform().await?;
1738
1739 if !self.socket.connection_options.upload_binary_over_ssh {
1740 if let Some((url, body)) = delegate
1741 .get_download_params(platform, release_channel, wanted_version, cx)
1742 .await?
1743 {
1744 match self
1745 .download_binary_on_server(&url, &body, &tmp_path_gz, delegate, cx)
1746 .await
1747 {
1748 Ok(_) => {
1749 self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
1750 .await?;
1751 return Ok(dst_path);
1752 }
1753 Err(e) => {
1754 log::error!(
1755 "Failed to download binary on server, attempting to upload server: {}",
1756 e
1757 )
1758 }
1759 }
1760 }
1761 }
1762
1763 let src_path = delegate
1764 .download_server_binary_locally(platform, release_channel, wanted_version, cx)
1765 .await?;
1766 self.upload_local_server_binary(&src_path, &tmp_path_gz, delegate, cx)
1767 .await?;
1768 self.extract_server_binary(&dst_path, &tmp_path_gz, delegate, cx)
1769 .await?;
1770 return Ok(dst_path);
1771 }
1772
1773 async fn download_binary_on_server(
1774 &self,
1775 url: &str,
1776 body: &str,
1777 tmp_path_gz: &Path,
1778 delegate: &Arc<dyn SshClientDelegate>,
1779 cx: &mut AsyncAppContext,
1780 ) -> Result<()> {
1781 if let Some(parent) = tmp_path_gz.parent() {
1782 self.socket
1783 .run_command("mkdir", &["-p", &parent.to_string_lossy()])
1784 .await?;
1785 }
1786
1787 delegate.set_status(Some("Downloading remote development server on host"), cx);
1788
1789 match self
1790 .socket
1791 .run_command(
1792 "curl",
1793 &[
1794 "-f",
1795 "-L",
1796 "-X",
1797 "GET",
1798 "-H",
1799 "Content-Type: application/json",
1800 "-d",
1801 &body,
1802 &url,
1803 "-o",
1804 &tmp_path_gz.to_string_lossy(),
1805 ],
1806 )
1807 .await
1808 {
1809 Ok(_) => {}
1810 Err(e) => {
1811 if self.socket.run_command("which", &["curl"]).await.is_ok() {
1812 return Err(e);
1813 }
1814
1815 match self
1816 .socket
1817 .run_command(
1818 "wget",
1819 &[
1820 "--max-redirect=5",
1821 "--method=GET",
1822 "--header=Content-Type: application/json",
1823 "--body-data",
1824 &body,
1825 &url,
1826 "-O",
1827 &tmp_path_gz.to_string_lossy(),
1828 ],
1829 )
1830 .await
1831 {
1832 Ok(_) => {}
1833 Err(e) => {
1834 if self.socket.run_command("which", &["wget"]).await.is_ok() {
1835 return Err(e);
1836 } else {
1837 anyhow::bail!("Neither curl nor wget is available");
1838 }
1839 }
1840 }
1841 }
1842 }
1843
1844 Ok(())
1845 }
1846
1847 async fn upload_local_server_binary(
1848 &self,
1849 src_path: &Path,
1850 tmp_path_gz: &Path,
1851 delegate: &Arc<dyn SshClientDelegate>,
1852 cx: &mut AsyncAppContext,
1853 ) -> Result<()> {
1854 if let Some(parent) = tmp_path_gz.parent() {
1855 self.socket
1856 .run_command("mkdir", &["-p", &parent.to_string_lossy()])
1857 .await?;
1858 }
1859
1860 let src_stat = fs::metadata(&src_path).await?;
1861 let size = src_stat.len();
1862
1863 let t0 = Instant::now();
1864 delegate.set_status(Some("Uploading remote development server"), cx);
1865 log::info!(
1866 "uploading remote development server to {:?} ({}kb)",
1867 tmp_path_gz,
1868 size / 1024
1869 );
1870 self.upload_file(&src_path, &tmp_path_gz)
1871 .await
1872 .context("failed to upload server binary")?;
1873 log::info!("uploaded remote development server in {:?}", t0.elapsed());
1874 Ok(())
1875 }
1876
1877 async fn extract_server_binary(
1878 &self,
1879 dst_path: &Path,
1880 tmp_path_gz: &Path,
1881 delegate: &Arc<dyn SshClientDelegate>,
1882 cx: &mut AsyncAppContext,
1883 ) -> Result<()> {
1884 delegate.set_status(Some("Extracting remote development server"), cx);
1885 let server_mode = 0o755;
1886
1887 let script = shell_script!(
1888 "gunzip -f {tmp_path_gz} && chmod {server_mode} {tmp_path} && mv {tmp_path} {dst_path}",
1889 tmp_path_gz = &tmp_path_gz.to_string_lossy(),
1890 tmp_path = &tmp_path_gz.to_string_lossy().strip_suffix(".gz").unwrap(),
1891 server_mode = &format!("{:o}", server_mode),
1892 dst_path = &dst_path.to_string_lossy()
1893 );
1894 self.socket.run_command("sh", &["-c", &script]).await?;
1895 Ok(())
1896 }
1897
1898 async fn upload_file(&self, src_path: &Path, dest_path: &Path) -> Result<()> {
1899 log::debug!("uploading file {:?} to {:?}", src_path, dest_path);
1900 let mut command = process::Command::new("scp");
1901 let output = self
1902 .socket
1903 .ssh_options(&mut command)
1904 .args(
1905 self.socket
1906 .connection_options
1907 .port
1908 .map(|port| vec!["-P".to_string(), port.to_string()])
1909 .unwrap_or_default(),
1910 )
1911 .arg(src_path)
1912 .arg(format!(
1913 "{}:{}",
1914 self.socket.connection_options.scp_url(),
1915 dest_path.display()
1916 ))
1917 .output()
1918 .await?;
1919
1920 if output.status.success() {
1921 Ok(())
1922 } else {
1923 Err(anyhow!(
1924 "failed to upload file {} -> {}: {}",
1925 src_path.display(),
1926 dest_path.display(),
1927 String::from_utf8_lossy(&output.stderr)
1928 ))
1929 }
1930 }
1931
1932 #[cfg(debug_assertions)]
1933 async fn build_local(
1934 &self,
1935 platform: SshPlatform,
1936 delegate: &Arc<dyn SshClientDelegate>,
1937 cx: &mut AsyncAppContext,
1938 ) -> Result<PathBuf> {
1939 use smol::process::{Command, Stdio};
1940
1941 async fn run_cmd(command: &mut Command) -> Result<()> {
1942 let output = command
1943 .kill_on_drop(true)
1944 .stderr(Stdio::inherit())
1945 .output()
1946 .await?;
1947 if !output.status.success() {
1948 Err(anyhow!("Failed to run command: {:?}", command))?;
1949 }
1950 Ok(())
1951 }
1952
1953 if platform.arch == std::env::consts::ARCH && platform.os == std::env::consts::OS {
1954 delegate.set_status(Some("Building remote server binary from source"), cx);
1955 log::info!("building remote server binary from source");
1956 run_cmd(Command::new("cargo").args([
1957 "build",
1958 "--package",
1959 "remote_server",
1960 "--features",
1961 "debug-embed",
1962 "--target-dir",
1963 "target/remote_server",
1964 ]))
1965 .await?;
1966
1967 delegate.set_status(Some("Compressing binary"), cx);
1968
1969 run_cmd(Command::new("gzip").args([
1970 "-9",
1971 "-f",
1972 "target/remote_server/debug/remote_server",
1973 ]))
1974 .await?;
1975
1976 let path = std::env::current_dir()?.join("target/remote_server/debug/remote_server.gz");
1977 return Ok(path);
1978 }
1979 let Some(triple) = platform.triple() else {
1980 anyhow::bail!("can't cross compile for: {:?}", platform);
1981 };
1982 smol::fs::create_dir_all("target/remote_server").await?;
1983
1984 delegate.set_status(Some("Installing cross.rs for cross-compilation"), cx);
1985 log::info!("installing cross");
1986 run_cmd(Command::new("cargo").args([
1987 "install",
1988 "cross",
1989 "--git",
1990 "https://github.com/cross-rs/cross",
1991 ]))
1992 .await?;
1993
1994 delegate.set_status(
1995 Some(&format!(
1996 "Building remote server binary from source for {} with Docker",
1997 &triple
1998 )),
1999 cx,
2000 );
2001 log::info!("building remote server binary from source for {}", &triple);
2002 run_cmd(
2003 Command::new("cross")
2004 .args([
2005 "build",
2006 "--package",
2007 "remote_server",
2008 "--features",
2009 "debug-embed",
2010 "--target-dir",
2011 "target/remote_server",
2012 "--target",
2013 &triple,
2014 ])
2015 .env(
2016 "CROSS_CONTAINER_OPTS",
2017 "--mount type=bind,src=./target,dst=/app/target",
2018 ),
2019 )
2020 .await?;
2021
2022 delegate.set_status(Some("Compressing binary"), cx);
2023
2024 run_cmd(Command::new("gzip").args([
2025 "-9",
2026 "-f",
2027 &format!("target/remote_server/{}/debug/remote_server", triple),
2028 ]))
2029 .await?;
2030
2031 let path = std::env::current_dir()?.join(format!(
2032 "target/remote_server/{}/debug/remote_server.gz",
2033 triple
2034 ));
2035
2036 return Ok(path);
2037 }
2038}
2039
2040type ResponseChannels = Mutex<HashMap<MessageId, oneshot::Sender<(Envelope, oneshot::Sender<()>)>>>;
2041
2042pub struct ChannelClient {
2043 next_message_id: AtomicU32,
2044 outgoing_tx: Mutex<mpsc::UnboundedSender<Envelope>>,
2045 buffer: Mutex<VecDeque<Envelope>>,
2046 response_channels: ResponseChannels,
2047 message_handlers: Mutex<ProtoMessageHandlerSet>,
2048 max_received: AtomicU32,
2049 name: &'static str,
2050 task: Mutex<Task<Result<()>>>,
2051}
2052
2053impl ChannelClient {
2054 pub fn new(
2055 incoming_rx: mpsc::UnboundedReceiver<Envelope>,
2056 outgoing_tx: mpsc::UnboundedSender<Envelope>,
2057 cx: &AppContext,
2058 name: &'static str,
2059 ) -> Arc<Self> {
2060 Arc::new_cyclic(|this| Self {
2061 outgoing_tx: Mutex::new(outgoing_tx),
2062 next_message_id: AtomicU32::new(0),
2063 max_received: AtomicU32::new(0),
2064 response_channels: ResponseChannels::default(),
2065 message_handlers: Default::default(),
2066 buffer: Mutex::new(VecDeque::new()),
2067 name,
2068 task: Mutex::new(Self::start_handling_messages(
2069 this.clone(),
2070 incoming_rx,
2071 &cx.to_async(),
2072 )),
2073 })
2074 }
2075
2076 fn start_handling_messages(
2077 this: Weak<Self>,
2078 mut incoming_rx: mpsc::UnboundedReceiver<Envelope>,
2079 cx: &AsyncAppContext,
2080 ) -> Task<Result<()>> {
2081 cx.spawn(|cx| async move {
2082 let peer_id = PeerId { owner_id: 0, id: 0 };
2083 while let Some(incoming) = incoming_rx.next().await {
2084 let Some(this) = this.upgrade() else {
2085 return anyhow::Ok(());
2086 };
2087 if let Some(ack_id) = incoming.ack_id {
2088 let mut buffer = this.buffer.lock();
2089 while buffer.front().is_some_and(|msg| msg.id <= ack_id) {
2090 buffer.pop_front();
2091 }
2092 }
2093 if let Some(proto::envelope::Payload::FlushBufferedMessages(_)) = &incoming.payload
2094 {
2095 log::debug!(
2096 "{}:ssh message received. name:FlushBufferedMessages",
2097 this.name
2098 );
2099 {
2100 let buffer = this.buffer.lock();
2101 for envelope in buffer.iter() {
2102 this.outgoing_tx
2103 .lock()
2104 .unbounded_send(envelope.clone())
2105 .ok();
2106 }
2107 }
2108 let mut envelope = proto::Ack {}.into_envelope(0, Some(incoming.id), None);
2109 envelope.id = this.next_message_id.fetch_add(1, SeqCst);
2110 this.outgoing_tx.lock().unbounded_send(envelope).ok();
2111 continue;
2112 }
2113
2114 this.max_received.store(incoming.id, SeqCst);
2115
2116 if let Some(request_id) = incoming.responding_to {
2117 let request_id = MessageId(request_id);
2118 let sender = this.response_channels.lock().remove(&request_id);
2119 if let Some(sender) = sender {
2120 let (tx, rx) = oneshot::channel();
2121 if incoming.payload.is_some() {
2122 sender.send((incoming, tx)).ok();
2123 }
2124 rx.await.ok();
2125 }
2126 } else if let Some(envelope) =
2127 build_typed_envelope(peer_id, Instant::now(), incoming)
2128 {
2129 let type_name = envelope.payload_type_name();
2130 if let Some(future) = ProtoMessageHandlerSet::handle_message(
2131 &this.message_handlers,
2132 envelope,
2133 this.clone().into(),
2134 cx.clone(),
2135 ) {
2136 log::debug!("{}:ssh message received. name:{type_name}", this.name);
2137 cx.foreground_executor()
2138 .spawn(async move {
2139 match future.await {
2140 Ok(_) => {
2141 log::debug!(
2142 "{}:ssh message handled. name:{type_name}",
2143 this.name
2144 );
2145 }
2146 Err(error) => {
2147 log::error!(
2148 "{}:error handling message. type:{}, error:{}",
2149 this.name,
2150 type_name,
2151 format!("{error:#}").lines().fold(
2152 String::new(),
2153 |mut message, line| {
2154 if !message.is_empty() {
2155 message.push(' ');
2156 }
2157 message.push_str(line);
2158 message
2159 }
2160 )
2161 );
2162 }
2163 }
2164 })
2165 .detach()
2166 } else {
2167 log::error!("{}:unhandled ssh message name:{type_name}", this.name);
2168 }
2169 }
2170 }
2171 anyhow::Ok(())
2172 })
2173 }
2174
2175 pub fn reconnect(
2176 self: &Arc<Self>,
2177 incoming_rx: UnboundedReceiver<Envelope>,
2178 outgoing_tx: UnboundedSender<Envelope>,
2179 cx: &AsyncAppContext,
2180 ) {
2181 *self.outgoing_tx.lock() = outgoing_tx;
2182 *self.task.lock() = Self::start_handling_messages(Arc::downgrade(self), incoming_rx, cx);
2183 }
2184
2185 pub fn subscribe_to_entity<E: 'static>(&self, remote_id: u64, entity: &Model<E>) {
2186 let id = (TypeId::of::<E>(), remote_id);
2187
2188 let mut message_handlers = self.message_handlers.lock();
2189 if message_handlers
2190 .entities_by_type_and_remote_id
2191 .contains_key(&id)
2192 {
2193 panic!("already subscribed to entity");
2194 }
2195
2196 message_handlers.entities_by_type_and_remote_id.insert(
2197 id,
2198 EntityMessageSubscriber::Entity {
2199 handle: entity.downgrade().into(),
2200 },
2201 );
2202 }
2203
2204 pub fn request<T: RequestMessage>(
2205 &self,
2206 payload: T,
2207 ) -> impl 'static + Future<Output = Result<T::Response>> {
2208 self.request_internal(payload, true)
2209 }
2210
2211 fn request_internal<T: RequestMessage>(
2212 &self,
2213 payload: T,
2214 use_buffer: bool,
2215 ) -> impl 'static + Future<Output = Result<T::Response>> {
2216 log::debug!("ssh request start. name:{}", T::NAME);
2217 let response =
2218 self.request_dynamic(payload.into_envelope(0, None, None), T::NAME, use_buffer);
2219 async move {
2220 let response = response.await?;
2221 log::debug!("ssh request finish. name:{}", T::NAME);
2222 T::Response::from_envelope(response)
2223 .ok_or_else(|| anyhow!("received a response of the wrong type"))
2224 }
2225 }
2226
2227 pub async fn resync(&self, timeout: Duration) -> Result<()> {
2228 smol::future::or(
2229 async {
2230 self.request_internal(proto::FlushBufferedMessages {}, false)
2231 .await?;
2232
2233 for envelope in self.buffer.lock().iter() {
2234 self.outgoing_tx
2235 .lock()
2236 .unbounded_send(envelope.clone())
2237 .ok();
2238 }
2239 Ok(())
2240 },
2241 async {
2242 smol::Timer::after(timeout).await;
2243 Err(anyhow!("Timeout detected"))
2244 },
2245 )
2246 .await
2247 }
2248
2249 pub async fn ping(&self, timeout: Duration) -> Result<()> {
2250 smol::future::or(
2251 async {
2252 self.request(proto::Ping {}).await?;
2253 Ok(())
2254 },
2255 async {
2256 smol::Timer::after(timeout).await;
2257 Err(anyhow!("Timeout detected"))
2258 },
2259 )
2260 .await
2261 }
2262
2263 pub fn send<T: EnvelopedMessage>(&self, payload: T) -> Result<()> {
2264 log::debug!("ssh send name:{}", T::NAME);
2265 self.send_dynamic(payload.into_envelope(0, None, None))
2266 }
2267
2268 fn request_dynamic(
2269 &self,
2270 mut envelope: proto::Envelope,
2271 type_name: &'static str,
2272 use_buffer: bool,
2273 ) -> impl 'static + Future<Output = Result<proto::Envelope>> {
2274 envelope.id = self.next_message_id.fetch_add(1, SeqCst);
2275 let (tx, rx) = oneshot::channel();
2276 let mut response_channels_lock = self.response_channels.lock();
2277 response_channels_lock.insert(MessageId(envelope.id), tx);
2278 drop(response_channels_lock);
2279
2280 let result = if use_buffer {
2281 self.send_buffered(envelope)
2282 } else {
2283 self.send_unbuffered(envelope)
2284 };
2285 async move {
2286 if let Err(error) = &result {
2287 log::error!("failed to send message: {}", error);
2288 return Err(anyhow!("failed to send message: {}", error));
2289 }
2290
2291 let response = rx.await.context("connection lost")?.0;
2292 if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
2293 return Err(RpcError::from_proto(error, type_name));
2294 }
2295 Ok(response)
2296 }
2297 }
2298
2299 pub fn send_dynamic(&self, mut envelope: proto::Envelope) -> Result<()> {
2300 envelope.id = self.next_message_id.fetch_add(1, SeqCst);
2301 self.send_buffered(envelope)
2302 }
2303
2304 fn send_buffered(&self, mut envelope: proto::Envelope) -> Result<()> {
2305 envelope.ack_id = Some(self.max_received.load(SeqCst));
2306 self.buffer.lock().push_back(envelope.clone());
2307 // ignore errors on send (happen while we're reconnecting)
2308 // assume that the global "disconnected" overlay is sufficient.
2309 self.outgoing_tx.lock().unbounded_send(envelope).ok();
2310 Ok(())
2311 }
2312
2313 fn send_unbuffered(&self, mut envelope: proto::Envelope) -> Result<()> {
2314 envelope.ack_id = Some(self.max_received.load(SeqCst));
2315 self.outgoing_tx.lock().unbounded_send(envelope).ok();
2316 Ok(())
2317 }
2318}
2319
2320impl ProtoClient for ChannelClient {
2321 fn request(
2322 &self,
2323 envelope: proto::Envelope,
2324 request_type: &'static str,
2325 ) -> BoxFuture<'static, Result<proto::Envelope>> {
2326 self.request_dynamic(envelope, request_type, true).boxed()
2327 }
2328
2329 fn send(&self, envelope: proto::Envelope, _message_type: &'static str) -> Result<()> {
2330 self.send_dynamic(envelope)
2331 }
2332
2333 fn send_response(&self, envelope: Envelope, _message_type: &'static str) -> anyhow::Result<()> {
2334 self.send_dynamic(envelope)
2335 }
2336
2337 fn message_handler_set(&self) -> &Mutex<ProtoMessageHandlerSet> {
2338 &self.message_handlers
2339 }
2340
2341 fn is_via_collab(&self) -> bool {
2342 false
2343 }
2344}
2345
2346#[cfg(any(test, feature = "test-support"))]
2347mod fake {
2348 use std::{path::PathBuf, sync::Arc};
2349
2350 use anyhow::Result;
2351 use async_trait::async_trait;
2352 use futures::{
2353 channel::{
2354 mpsc::{self, Sender},
2355 oneshot,
2356 },
2357 select_biased, FutureExt, SinkExt, StreamExt,
2358 };
2359 use gpui::{AppContext, AsyncAppContext, SemanticVersion, Task, TestAppContext};
2360 use release_channel::ReleaseChannel;
2361 use rpc::proto::Envelope;
2362
2363 use super::{
2364 ChannelClient, RemoteConnection, SshClientDelegate, SshConnectionOptions, SshPlatform,
2365 };
2366
2367 pub(super) struct FakeRemoteConnection {
2368 pub(super) connection_options: SshConnectionOptions,
2369 pub(super) server_channel: Arc<ChannelClient>,
2370 pub(super) server_cx: SendableCx,
2371 }
2372
2373 pub(super) struct SendableCx(AsyncAppContext);
2374 impl SendableCx {
2375 // SAFETY: When run in test mode, GPUI is always single threaded.
2376 pub(super) fn new(cx: &TestAppContext) -> Self {
2377 Self(cx.to_async())
2378 }
2379
2380 // SAFETY: Enforce that we're on the main thread by requiring a valid AsyncAppContext
2381 fn get(&self, _: &AsyncAppContext) -> AsyncAppContext {
2382 self.0.clone()
2383 }
2384 }
2385
2386 // SAFETY: There is no way to access a SendableCx from a different thread, see [`SendableCx::new`] and [`SendableCx::get`]
2387 unsafe impl Send for SendableCx {}
2388 unsafe impl Sync for SendableCx {}
2389
2390 #[async_trait(?Send)]
2391 impl RemoteConnection for FakeRemoteConnection {
2392 async fn kill(&self) -> Result<()> {
2393 Ok(())
2394 }
2395
2396 fn has_been_killed(&self) -> bool {
2397 false
2398 }
2399
2400 fn ssh_args(&self) -> Vec<String> {
2401 Vec::new()
2402 }
2403 fn upload_directory(
2404 &self,
2405 _src_path: PathBuf,
2406 _dest_path: PathBuf,
2407 _cx: &AppContext,
2408 ) -> Task<Result<()>> {
2409 unreachable!()
2410 }
2411
2412 fn connection_options(&self) -> SshConnectionOptions {
2413 self.connection_options.clone()
2414 }
2415
2416 fn simulate_disconnect(&self, cx: &AsyncAppContext) {
2417 let (outgoing_tx, _) = mpsc::unbounded::<Envelope>();
2418 let (_, incoming_rx) = mpsc::unbounded::<Envelope>();
2419 self.server_channel
2420 .reconnect(incoming_rx, outgoing_tx, &self.server_cx.get(&cx));
2421 }
2422
2423 fn start_proxy(
2424 &self,
2425
2426 _unique_identifier: String,
2427 _reconnect: bool,
2428 mut client_incoming_tx: mpsc::UnboundedSender<Envelope>,
2429 mut client_outgoing_rx: mpsc::UnboundedReceiver<Envelope>,
2430 mut connection_activity_tx: Sender<()>,
2431 _delegate: Arc<dyn SshClientDelegate>,
2432 cx: &mut AsyncAppContext,
2433 ) -> Task<Result<i32>> {
2434 let (mut server_incoming_tx, server_incoming_rx) = mpsc::unbounded::<Envelope>();
2435 let (server_outgoing_tx, mut server_outgoing_rx) = mpsc::unbounded::<Envelope>();
2436
2437 self.server_channel.reconnect(
2438 server_incoming_rx,
2439 server_outgoing_tx,
2440 &self.server_cx.get(cx),
2441 );
2442
2443 cx.background_executor().spawn(async move {
2444 loop {
2445 select_biased! {
2446 server_to_client = server_outgoing_rx.next().fuse() => {
2447 let Some(server_to_client) = server_to_client else {
2448 return Ok(1)
2449 };
2450 connection_activity_tx.try_send(()).ok();
2451 client_incoming_tx.send(server_to_client).await.ok();
2452 }
2453 client_to_server = client_outgoing_rx.next().fuse() => {
2454 let Some(client_to_server) = client_to_server else {
2455 return Ok(1)
2456 };
2457 server_incoming_tx.send(client_to_server).await.ok();
2458 }
2459 }
2460 }
2461 })
2462 }
2463 }
2464
2465 pub(super) struct Delegate;
2466
2467 impl SshClientDelegate for Delegate {
2468 fn ask_password(
2469 &self,
2470 _: String,
2471 _: &mut AsyncAppContext,
2472 ) -> oneshot::Receiver<Result<String>> {
2473 unreachable!()
2474 }
2475
2476 fn download_server_binary_locally(
2477 &self,
2478 _: SshPlatform,
2479 _: ReleaseChannel,
2480 _: Option<SemanticVersion>,
2481 _: &mut AsyncAppContext,
2482 ) -> Task<Result<PathBuf>> {
2483 unreachable!()
2484 }
2485
2486 fn get_download_params(
2487 &self,
2488 _platform: SshPlatform,
2489 _release_channel: ReleaseChannel,
2490 _version: Option<SemanticVersion>,
2491 _cx: &mut AsyncAppContext,
2492 ) -> Task<Result<Option<(String, String)>>> {
2493 unreachable!()
2494 }
2495
2496 fn set_status(&self, _: Option<&str>, _: &mut AsyncAppContext) {}
2497 }
2498}