ssh_session.rs

  1use crate::{
  2    json_log::LogRecord,
  3    protocol::{
  4        message_len_from_buffer, read_message_with_len, write_message, MessageId, MESSAGE_LEN_SIZE,
  5    },
  6};
  7use anyhow::{anyhow, Context as _, Result};
  8use collections::HashMap;
  9use futures::{
 10    channel::{
 11        mpsc::{self, UnboundedReceiver, UnboundedSender},
 12        oneshot,
 13    },
 14    future::BoxFuture,
 15    select_biased, AsyncReadExt as _, AsyncWriteExt as _, Future, FutureExt as _, SinkExt,
 16    StreamExt as _,
 17};
 18use gpui::{AppContext, AsyncAppContext, Model, SemanticVersion, Task};
 19use parking_lot::Mutex;
 20use rpc::{
 21    proto::{self, build_typed_envelope, Envelope, EnvelopedMessage, PeerId, RequestMessage},
 22    AnyProtoClient, EntityMessageSubscriber, ProtoClient, ProtoMessageHandlerSet, RpcError,
 23};
 24use smol::{
 25    fs,
 26    process::{self, Child, Stdio},
 27};
 28use std::{
 29    any::TypeId,
 30    ffi::OsStr,
 31    path::{Path, PathBuf},
 32    sync::{
 33        atomic::{AtomicU32, Ordering::SeqCst},
 34        Arc,
 35    },
 36    time::Instant,
 37};
 38use tempfile::TempDir;
 39
 40#[derive(
 41    Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
 42)]
 43pub struct SshProjectId(pub u64);
 44
 45#[derive(Clone)]
 46pub struct SshSocket {
 47    connection_options: SshConnectionOptions,
 48    socket_path: PathBuf,
 49}
 50
 51#[derive(Debug, Clone, PartialEq, Eq)]
 52pub struct SshConnectionOptions {
 53    pub host: String,
 54    pub username: Option<String>,
 55    pub port: Option<u16>,
 56    pub password: Option<String>,
 57}
 58
 59impl SshConnectionOptions {
 60    pub fn ssh_url(&self) -> String {
 61        let mut result = String::from("ssh://");
 62        if let Some(username) = &self.username {
 63            result.push_str(username);
 64            result.push('@');
 65        }
 66        result.push_str(&self.host);
 67        if let Some(port) = self.port {
 68            result.push(':');
 69            result.push_str(&port.to_string());
 70        }
 71        result
 72    }
 73
 74    fn scp_url(&self) -> String {
 75        if let Some(username) = &self.username {
 76            format!("{}@{}", username, self.host)
 77        } else {
 78            self.host.clone()
 79        }
 80    }
 81
 82    pub fn connection_string(&self) -> String {
 83        let host = if let Some(username) = &self.username {
 84            format!("{}@{}", username, self.host)
 85        } else {
 86            self.host.clone()
 87        };
 88        if let Some(port) = &self.port {
 89            format!("{}:{}", host, port)
 90        } else {
 91            host
 92        }
 93    }
 94}
 95
 96#[derive(Copy, Clone, Debug)]
 97pub struct SshPlatform {
 98    pub os: &'static str,
 99    pub arch: &'static str,
100}
101
102pub trait SshClientDelegate: Send + Sync {
103    fn ask_password(
104        &self,
105        prompt: String,
106        cx: &mut AsyncAppContext,
107    ) -> oneshot::Receiver<Result<String>>;
108    fn remote_server_binary_path(&self, cx: &mut AsyncAppContext) -> Result<PathBuf>;
109    fn get_server_binary(
110        &self,
111        platform: SshPlatform,
112        cx: &mut AsyncAppContext,
113    ) -> oneshot::Receiver<Result<(PathBuf, SemanticVersion)>>;
114    fn set_status(&self, status: Option<&str>, cx: &mut AsyncAppContext);
115    fn set_error(&self, error_message: String, cx: &mut AsyncAppContext);
116}
117
118impl SshSocket {
119    fn ssh_command<S: AsRef<OsStr>>(&self, program: S) -> process::Command {
120        let mut command = process::Command::new("ssh");
121        self.ssh_options(&mut command)
122            .arg(self.connection_options.ssh_url())
123            .arg(program);
124        command
125    }
126
127    fn ssh_options<'a>(&self, command: &'a mut process::Command) -> &'a mut process::Command {
128        command
129            .stdin(Stdio::piped())
130            .stdout(Stdio::piped())
131            .stderr(Stdio::piped())
132            .args(["-o", "ControlMaster=no", "-o"])
133            .arg(format!("ControlPath={}", self.socket_path.display()))
134    }
135
136    fn ssh_args(&self) -> Vec<String> {
137        vec![
138            "-o".to_string(),
139            "ControlMaster=no".to_string(),
140            "-o".to_string(),
141            format!("ControlPath={}", self.socket_path.display()),
142            self.connection_options.ssh_url(),
143        ]
144    }
145}
146
147async fn run_cmd(command: &mut process::Command) -> Result<String> {
148    let output = command.output().await?;
149    if output.status.success() {
150        Ok(String::from_utf8_lossy(&output.stdout).to_string())
151    } else {
152        Err(anyhow!(
153            "failed to run command: {}",
154            String::from_utf8_lossy(&output.stderr)
155        ))
156    }
157}
158#[cfg(unix)]
159async fn read_with_timeout(
160    stdout: &mut process::ChildStdout,
161    timeout: std::time::Duration,
162    output: &mut Vec<u8>,
163) -> Result<(), std::io::Error> {
164    smol::future::or(
165        async {
166            stdout.read_to_end(output).await?;
167            Ok::<_, std::io::Error>(())
168        },
169        async {
170            smol::Timer::after(timeout).await;
171
172            Err(std::io::Error::new(
173                std::io::ErrorKind::TimedOut,
174                "Read operation timed out",
175            ))
176        },
177    )
178    .await
179}
180
181struct ChannelForwarder {
182    quit_tx: UnboundedSender<()>,
183    forwarding_task: Task<(UnboundedSender<Envelope>, UnboundedReceiver<Envelope>)>,
184}
185
186impl ChannelForwarder {
187    fn new(
188        mut incoming_tx: UnboundedSender<Envelope>,
189        mut outgoing_rx: UnboundedReceiver<Envelope>,
190        cx: &mut AsyncAppContext,
191    ) -> (Self, UnboundedSender<Envelope>, UnboundedReceiver<Envelope>) {
192        let (quit_tx, mut quit_rx) = mpsc::unbounded::<()>();
193
194        let (proxy_incoming_tx, mut proxy_incoming_rx) = mpsc::unbounded::<Envelope>();
195        let (mut proxy_outgoing_tx, proxy_outgoing_rx) = mpsc::unbounded::<Envelope>();
196
197        let forwarding_task = cx.background_executor().spawn(async move {
198            loop {
199                select_biased! {
200                    _ = quit_rx.next().fuse() => {
201                        break;
202                    },
203                    incoming_envelope = proxy_incoming_rx.next().fuse() => {
204                        if let Some(envelope) = incoming_envelope {
205                            if incoming_tx.send(envelope).await.is_err() {
206                                break;
207                            }
208                        } else {
209                            break;
210                        }
211                    }
212                    outgoing_envelope = outgoing_rx.next().fuse() => {
213                        if let Some(envelope) = outgoing_envelope {
214                            if proxy_outgoing_tx.send(envelope).await.is_err() {
215                                break;
216                            }
217                        } else {
218                            break;
219                        }
220                    }
221                }
222            }
223
224            (incoming_tx, outgoing_rx)
225        });
226
227        (
228            Self {
229                forwarding_task,
230                quit_tx,
231            },
232            proxy_incoming_tx,
233            proxy_outgoing_rx,
234        )
235    }
236
237    async fn into_channels(mut self) -> (UnboundedSender<Envelope>, UnboundedReceiver<Envelope>) {
238        let _ = self.quit_tx.send(()).await;
239        self.forwarding_task.await
240    }
241}
242
243struct SshRemoteClientState {
244    ssh_connection: SshRemoteConnection,
245    delegate: Arc<dyn SshClientDelegate>,
246    forwarder: ChannelForwarder,
247    _multiplex_task: Task<Result<()>>,
248}
249
250pub struct SshRemoteClient {
251    client: Arc<ChannelClient>,
252    inner_state: Arc<Mutex<Option<SshRemoteClientState>>>,
253}
254
255impl SshRemoteClient {
256    pub async fn new(
257        connection_options: SshConnectionOptions,
258        delegate: Arc<dyn SshClientDelegate>,
259        cx: &mut AsyncAppContext,
260    ) -> Result<Arc<Self>> {
261        let (outgoing_tx, outgoing_rx) = mpsc::unbounded::<Envelope>();
262        let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
263
264        let client = cx.update(|cx| ChannelClient::new(incoming_rx, outgoing_tx, cx))?;
265        let this = Arc::new(Self {
266            client,
267            inner_state: Arc::new(Mutex::new(None)),
268        });
269
270        let inner_state = {
271            let (proxy, proxy_incoming_tx, proxy_outgoing_rx) =
272                ChannelForwarder::new(incoming_tx, outgoing_rx, cx);
273
274            let (ssh_connection, ssh_process) =
275                Self::establish_connection(connection_options.clone(), delegate.clone(), cx)
276                    .await?;
277
278            let multiplex_task = Self::multiplex(
279                this.clone(),
280                ssh_process,
281                proxy_incoming_tx,
282                proxy_outgoing_rx,
283                cx,
284            );
285
286            SshRemoteClientState {
287                ssh_connection,
288                delegate,
289                forwarder: proxy,
290                _multiplex_task: multiplex_task,
291            }
292        };
293
294        this.inner_state.lock().replace(inner_state);
295
296        Ok(this)
297    }
298
299    fn reconnect(this: Arc<Self>, cx: &mut AsyncAppContext) -> Result<()> {
300        let Some(state) = this.inner_state.lock().take() else {
301            return Err(anyhow!("reconnect is already in progress"));
302        };
303
304        let SshRemoteClientState {
305            mut ssh_connection,
306            delegate,
307            forwarder: proxy,
308            _multiplex_task,
309        } = state;
310        drop(_multiplex_task);
311
312        cx.spawn(|mut cx| async move {
313            let (incoming_tx, outgoing_rx) = proxy.into_channels().await;
314
315            ssh_connection.master_process.kill()?;
316            ssh_connection
317                .master_process
318                .status()
319                .await
320                .context("Failed to kill ssh process")?;
321
322            let connection_options = ssh_connection.socket.connection_options.clone();
323
324            let (ssh_connection, ssh_process) =
325                Self::establish_connection(connection_options, delegate.clone(), &mut cx).await?;
326
327            let (proxy, proxy_incoming_tx, proxy_outgoing_rx) =
328                ChannelForwarder::new(incoming_tx, outgoing_rx, &mut cx);
329
330            let inner_state = SshRemoteClientState {
331                ssh_connection,
332                delegate,
333                forwarder: proxy,
334                _multiplex_task: Self::multiplex(
335                    this.clone(),
336                    ssh_process,
337                    proxy_incoming_tx,
338                    proxy_outgoing_rx,
339                    &mut cx,
340                ),
341            };
342            this.inner_state.lock().replace(inner_state);
343
344            anyhow::Ok(())
345        })
346        .detach();
347
348        anyhow::Ok(())
349    }
350
351    fn multiplex(
352        this: Arc<Self>,
353        mut ssh_process: Child,
354        incoming_tx: UnboundedSender<Envelope>,
355        mut outgoing_rx: UnboundedReceiver<Envelope>,
356        cx: &mut AsyncAppContext,
357    ) -> Task<Result<()>> {
358        let mut child_stderr = ssh_process.stderr.take().unwrap();
359        let mut child_stdout = ssh_process.stdout.take().unwrap();
360        let mut child_stdin = ssh_process.stdin.take().unwrap();
361
362        let io_task = cx.background_executor().spawn(async move {
363            let mut stdin_buffer = Vec::new();
364            let mut stdout_buffer = Vec::new();
365            let mut stderr_buffer = Vec::new();
366            let mut stderr_offset = 0;
367
368            loop {
369                stdout_buffer.resize(MESSAGE_LEN_SIZE, 0);
370                stderr_buffer.resize(stderr_offset + 1024, 0);
371
372                select_biased! {
373                    outgoing = outgoing_rx.next().fuse() => {
374                        let Some(outgoing) = outgoing else {
375                            return anyhow::Ok(());
376                        };
377
378                        write_message(&mut child_stdin, &mut stdin_buffer, outgoing).await?;
379                    }
380
381                    result = child_stdout.read(&mut stdout_buffer).fuse() => {
382                        match result {
383                            Ok(0) => {
384                                child_stdin.close().await?;
385                                outgoing_rx.close();
386                                let status = ssh_process.status().await?;
387                                if !status.success() {
388                                    log::error!("ssh process exited with status: {status:?}");
389                                    return Err(anyhow!("ssh process exited with non-zero status code: {:?}", status.code()));
390                                }
391                                return Ok(());
392                            }
393                            Ok(len) => {
394                                if len < stdout_buffer.len() {
395                                    child_stdout.read_exact(&mut stdout_buffer[len..]).await?;
396                                }
397
398                                let message_len = message_len_from_buffer(&stdout_buffer);
399                                match read_message_with_len(&mut child_stdout, &mut stdout_buffer, message_len).await {
400                                    Ok(envelope) => {
401                                        incoming_tx.unbounded_send(envelope).ok();
402                                    }
403                                    Err(error) => {
404                                        log::error!("error decoding message {error:?}");
405                                    }
406                                }
407                            }
408                            Err(error) => {
409                                Err(anyhow!("error reading stdout: {error:?}"))?;
410                            }
411                        }
412                    }
413
414                    result = child_stderr.read(&mut stderr_buffer[stderr_offset..]).fuse() => {
415                        match result {
416                            Ok(len) => {
417                                stderr_offset += len;
418                                let mut start_ix = 0;
419                                while let Some(ix) = stderr_buffer[start_ix..stderr_offset].iter().position(|b| b == &b'\n') {
420                                    let line_ix = start_ix + ix;
421                                    let content = &stderr_buffer[start_ix..line_ix];
422                                    start_ix = line_ix + 1;
423                                    if let Ok(mut record) = serde_json::from_slice::<LogRecord>(content) {
424                                        record.message = format!("(remote) {}", record.message);
425                                        record.log(log::logger())
426                                    } else {
427                                        eprintln!("(remote) {}", String::from_utf8_lossy(content));
428                                    }
429                                }
430                                stderr_buffer.drain(0..start_ix);
431                                stderr_offset -= start_ix;
432                            }
433                            Err(error) => {
434                                Err(anyhow!("error reading stderr: {error:?}"))?;
435                            }
436                        }
437                    }
438                }
439            }
440        });
441
442        cx.spawn(|mut cx| async move {
443            let result = io_task.await;
444
445            if let Err(error) = result {
446                log::warn!("ssh io task died with error: {:?}. reconnecting...", error);
447                Self::reconnect(this, &mut cx).ok();
448            }
449
450            Ok(())
451        })
452    }
453
454    async fn establish_connection(
455        connection_options: SshConnectionOptions,
456        delegate: Arc<dyn SshClientDelegate>,
457        cx: &mut AsyncAppContext,
458    ) -> Result<(SshRemoteConnection, Child)> {
459        let ssh_connection =
460            SshRemoteConnection::new(connection_options, delegate.clone(), cx).await?;
461
462        let platform = ssh_connection.query_platform().await?;
463        let (local_binary_path, version) = delegate.get_server_binary(platform, cx).await??;
464        let remote_binary_path = delegate.remote_server_binary_path(cx)?;
465        ssh_connection
466            .ensure_server_binary(
467                &delegate,
468                &local_binary_path,
469                &remote_binary_path,
470                version,
471                cx,
472            )
473            .await?;
474
475        let socket = ssh_connection.socket.clone();
476        run_cmd(socket.ssh_command(&remote_binary_path).arg("version")).await?;
477
478        let ssh_process = socket
479            .ssh_command(format!(
480                "RUST_LOG={} RUST_BACKTRACE={} {:?} run",
481                std::env::var("RUST_LOG").unwrap_or_default(),
482                std::env::var("RUST_BACKTRACE").unwrap_or_default(),
483                remote_binary_path,
484            ))
485            .spawn()
486            .context("failed to spawn remote server")?;
487
488        Ok((ssh_connection, ssh_process))
489    }
490
491    pub fn subscribe_to_entity<E: 'static>(&self, remote_id: u64, entity: &Model<E>) {
492        self.client.subscribe_to_entity(remote_id, entity);
493    }
494
495    pub fn ssh_args(&self) -> Option<Vec<String>> {
496        let state = self.inner_state.lock();
497        state
498            .as_ref()
499            .map(|state| state.ssh_connection.socket.ssh_args())
500    }
501
502    pub fn to_proto_client(&self) -> AnyProtoClient {
503        self.client.clone().into()
504    }
505
506    #[cfg(any(test, feature = "test-support"))]
507    pub fn fake(
508        client_cx: &mut gpui::TestAppContext,
509        server_cx: &mut gpui::TestAppContext,
510    ) -> (Arc<Self>, Arc<ChannelClient>) {
511        let (server_to_client_tx, server_to_client_rx) = mpsc::unbounded();
512        let (client_to_server_tx, client_to_server_rx) = mpsc::unbounded();
513
514        (
515            client_cx.update(|cx| {
516                let client = ChannelClient::new(server_to_client_rx, client_to_server_tx, cx);
517                Arc::new(Self {
518                    client,
519                    inner_state: Arc::new(Mutex::new(None)),
520                })
521            }),
522            server_cx.update(|cx| ChannelClient::new(client_to_server_rx, server_to_client_tx, cx)),
523        )
524    }
525}
526
527impl From<SshRemoteClient> for AnyProtoClient {
528    fn from(client: SshRemoteClient) -> Self {
529        AnyProtoClient::new(client.client.clone())
530    }
531}
532
533struct SshRemoteConnection {
534    socket: SshSocket,
535    master_process: process::Child,
536    _temp_dir: TempDir,
537}
538
539impl Drop for SshRemoteConnection {
540    fn drop(&mut self) {
541        if let Err(error) = self.master_process.kill() {
542            log::error!("failed to kill SSH master process: {}", error);
543        }
544    }
545}
546
547impl SshRemoteConnection {
548    #[cfg(not(unix))]
549    async fn new(
550        _connection_options: SshConnectionOptions,
551        _delegate: Arc<dyn SshClientDelegate>,
552        _cx: &mut AsyncAppContext,
553    ) -> Result<Self> {
554        Err(anyhow!("ssh is not supported on this platform"))
555    }
556
557    #[cfg(unix)]
558    async fn new(
559        connection_options: SshConnectionOptions,
560        delegate: Arc<dyn SshClientDelegate>,
561        cx: &mut AsyncAppContext,
562    ) -> Result<Self> {
563        use futures::{io::BufReader, AsyncBufReadExt as _};
564        use smol::{fs::unix::PermissionsExt as _, net::unix::UnixListener};
565        use util::ResultExt as _;
566
567        delegate.set_status(Some("connecting"), cx);
568
569        let url = connection_options.ssh_url();
570        let temp_dir = tempfile::Builder::new()
571            .prefix("zed-ssh-session")
572            .tempdir()?;
573
574        // Create a domain socket listener to handle requests from the askpass program.
575        let askpass_socket = temp_dir.path().join("askpass.sock");
576        let listener =
577            UnixListener::bind(&askpass_socket).context("failed to create askpass socket")?;
578
579        let askpass_task = cx.spawn({
580            let delegate = delegate.clone();
581            |mut cx| async move {
582                while let Ok((mut stream, _)) = listener.accept().await {
583                    let mut buffer = Vec::new();
584                    let mut reader = BufReader::new(&mut stream);
585                    if reader.read_until(b'\0', &mut buffer).await.is_err() {
586                        buffer.clear();
587                    }
588                    let password_prompt = String::from_utf8_lossy(&buffer);
589                    if let Some(password) = delegate
590                        .ask_password(password_prompt.to_string(), &mut cx)
591                        .await
592                        .context("failed to get ssh password")
593                        .and_then(|p| p)
594                        .log_err()
595                    {
596                        stream.write_all(password.as_bytes()).await.log_err();
597                    }
598                }
599            }
600        });
601
602        // Create an askpass script that communicates back to this process.
603        let askpass_script = format!(
604            "{shebang}\n{print_args} | nc -U {askpass_socket} 2> /dev/null \n",
605            askpass_socket = askpass_socket.display(),
606            print_args = "printf '%s\\0' \"$@\"",
607            shebang = "#!/bin/sh",
608        );
609        let askpass_script_path = temp_dir.path().join("askpass.sh");
610        fs::write(&askpass_script_path, askpass_script).await?;
611        fs::set_permissions(&askpass_script_path, std::fs::Permissions::from_mode(0o755)).await?;
612
613        // Start the master SSH process, which does not do anything except for establish
614        // the connection and keep it open, allowing other ssh commands to reuse it
615        // via a control socket.
616        let socket_path = temp_dir.path().join("ssh.sock");
617        let mut master_process = process::Command::new("ssh")
618            .stdin(Stdio::null())
619            .stdout(Stdio::piped())
620            .stderr(Stdio::piped())
621            .env("SSH_ASKPASS_REQUIRE", "force")
622            .env("SSH_ASKPASS", &askpass_script_path)
623            .args(["-N", "-o", "ControlMaster=yes", "-o"])
624            .arg(format!("ControlPath={}", socket_path.display()))
625            .arg(&url)
626            .spawn()?;
627
628        // Wait for this ssh process to close its stdout, indicating that authentication
629        // has completed.
630        let stdout = master_process.stdout.as_mut().unwrap();
631        let mut output = Vec::new();
632        let connection_timeout = std::time::Duration::from_secs(10);
633        let result = read_with_timeout(stdout, connection_timeout, &mut output).await;
634        if let Err(e) = result {
635            let error_message = if e.kind() == std::io::ErrorKind::TimedOut {
636                format!(
637                    "Failed to connect to host. Timed out after {:?}.",
638                    connection_timeout
639                )
640            } else {
641                format!("Failed to connect to host: {}.", e)
642            };
643
644            delegate.set_error(error_message, cx);
645            return Err(e.into());
646        }
647
648        drop(askpass_task);
649
650        if master_process.try_status()?.is_some() {
651            output.clear();
652            let mut stderr = master_process.stderr.take().unwrap();
653            stderr.read_to_end(&mut output).await?;
654            Err(anyhow!(
655                "failed to connect: {}",
656                String::from_utf8_lossy(&output)
657            ))?;
658        }
659
660        Ok(Self {
661            socket: SshSocket {
662                connection_options,
663                socket_path,
664            },
665            master_process,
666            _temp_dir: temp_dir,
667        })
668    }
669
670    async fn ensure_server_binary(
671        &self,
672        delegate: &Arc<dyn SshClientDelegate>,
673        src_path: &Path,
674        dst_path: &Path,
675        version: SemanticVersion,
676        cx: &mut AsyncAppContext,
677    ) -> Result<()> {
678        let mut dst_path_gz = dst_path.to_path_buf();
679        dst_path_gz.set_extension("gz");
680
681        if let Some(parent) = dst_path.parent() {
682            run_cmd(self.socket.ssh_command("mkdir").arg("-p").arg(parent)).await?;
683        }
684
685        let mut server_binary_exists = false;
686        if cfg!(not(debug_assertions)) {
687            if let Ok(installed_version) =
688                run_cmd(self.socket.ssh_command(dst_path).arg("version")).await
689            {
690                if installed_version.trim() == version.to_string() {
691                    server_binary_exists = true;
692                }
693            }
694        }
695
696        if server_binary_exists {
697            log::info!("remote development server already present",);
698            return Ok(());
699        }
700
701        let src_stat = fs::metadata(src_path).await?;
702        let size = src_stat.len();
703        let server_mode = 0o755;
704
705        let t0 = Instant::now();
706        delegate.set_status(Some("uploading remote development server"), cx);
707        log::info!("uploading remote development server ({}kb)", size / 1024);
708        self.upload_file(src_path, &dst_path_gz)
709            .await
710            .context("failed to upload server binary")?;
711        log::info!("uploaded remote development server in {:?}", t0.elapsed());
712
713        delegate.set_status(Some("extracting remote development server"), cx);
714        run_cmd(
715            self.socket
716                .ssh_command("gunzip")
717                .arg("--force")
718                .arg(&dst_path_gz),
719        )
720        .await?;
721
722        delegate.set_status(Some("unzipping remote development server"), cx);
723        run_cmd(
724            self.socket
725                .ssh_command("chmod")
726                .arg(format!("{:o}", server_mode))
727                .arg(dst_path),
728        )
729        .await?;
730
731        Ok(())
732    }
733
734    async fn query_platform(&self) -> Result<SshPlatform> {
735        let os = run_cmd(self.socket.ssh_command("uname").arg("-s")).await?;
736        let arch = run_cmd(self.socket.ssh_command("uname").arg("-m")).await?;
737
738        let os = match os.trim() {
739            "Darwin" => "macos",
740            "Linux" => "linux",
741            _ => Err(anyhow!("unknown uname os {os:?}"))?,
742        };
743        let arch = if arch.starts_with("arm") || arch.starts_with("aarch64") {
744            "aarch64"
745        } else if arch.starts_with("x86") || arch.starts_with("i686") {
746            "x86_64"
747        } else {
748            Err(anyhow!("unknown uname architecture {arch:?}"))?
749        };
750
751        Ok(SshPlatform { os, arch })
752    }
753
754    async fn upload_file(&self, src_path: &Path, dest_path: &Path) -> Result<()> {
755        let mut command = process::Command::new("scp");
756        let output = self
757            .socket
758            .ssh_options(&mut command)
759            .args(
760                self.socket
761                    .connection_options
762                    .port
763                    .map(|port| vec!["-P".to_string(), port.to_string()])
764                    .unwrap_or_default(),
765            )
766            .arg(src_path)
767            .arg(format!(
768                "{}:{}",
769                self.socket.connection_options.scp_url(),
770                dest_path.display()
771            ))
772            .output()
773            .await?;
774
775        if output.status.success() {
776            Ok(())
777        } else {
778            Err(anyhow!(
779                "failed to upload file {} -> {}: {}",
780                src_path.display(),
781                dest_path.display(),
782                String::from_utf8_lossy(&output.stderr)
783            ))
784        }
785    }
786}
787
788type ResponseChannels = Mutex<HashMap<MessageId, oneshot::Sender<(Envelope, oneshot::Sender<()>)>>>;
789
790pub struct ChannelClient {
791    next_message_id: AtomicU32,
792    outgoing_tx: mpsc::UnboundedSender<Envelope>,
793    response_channels: ResponseChannels,             // Lock
794    message_handlers: Mutex<ProtoMessageHandlerSet>, // Lock
795}
796
797impl ChannelClient {
798    pub fn new(
799        incoming_rx: mpsc::UnboundedReceiver<Envelope>,
800        outgoing_tx: mpsc::UnboundedSender<Envelope>,
801        cx: &AppContext,
802    ) -> Arc<Self> {
803        let this = Arc::new(Self {
804            outgoing_tx,
805            next_message_id: AtomicU32::new(0),
806            response_channels: ResponseChannels::default(),
807            message_handlers: Default::default(),
808        });
809
810        Self::start_handling_messages(this.clone(), incoming_rx, cx);
811
812        this
813    }
814
815    fn start_handling_messages(
816        this: Arc<Self>,
817        mut incoming_rx: mpsc::UnboundedReceiver<Envelope>,
818        cx: &AppContext,
819    ) {
820        cx.spawn(|cx| {
821            let this = Arc::downgrade(&this);
822            async move {
823                let peer_id = PeerId { owner_id: 0, id: 0 };
824                while let Some(incoming) = incoming_rx.next().await {
825                    let Some(this) = this.upgrade() else {
826                        return anyhow::Ok(());
827                    };
828
829                    if let Some(request_id) = incoming.responding_to {
830                        let request_id = MessageId(request_id);
831                        let sender = this.response_channels.lock().remove(&request_id);
832                        if let Some(sender) = sender {
833                            let (tx, rx) = oneshot::channel();
834                            if incoming.payload.is_some() {
835                                sender.send((incoming, tx)).ok();
836                            }
837                            rx.await.ok();
838                        }
839                    } else if let Some(envelope) =
840                        build_typed_envelope(peer_id, Instant::now(), incoming)
841                    {
842                        let type_name = envelope.payload_type_name();
843                        if let Some(future) = ProtoMessageHandlerSet::handle_message(
844                            &this.message_handlers,
845                            envelope,
846                            this.clone().into(),
847                            cx.clone(),
848                        ) {
849                            log::debug!("ssh message received. name:{type_name}");
850                            match future.await {
851                                Ok(_) => {
852                                    log::debug!("ssh message handled. name:{type_name}");
853                                }
854                                Err(error) => {
855                                    log::error!(
856                                        "error handling message. type:{type_name}, error:{error}",
857                                    );
858                                }
859                            }
860                        } else {
861                            log::error!("unhandled ssh message name:{type_name}");
862                        }
863                    }
864                }
865                anyhow::Ok(())
866            }
867        })
868        .detach();
869    }
870
871    pub fn subscribe_to_entity<E: 'static>(&self, remote_id: u64, entity: &Model<E>) {
872        let id = (TypeId::of::<E>(), remote_id);
873
874        let mut message_handlers = self.message_handlers.lock();
875        if message_handlers
876            .entities_by_type_and_remote_id
877            .contains_key(&id)
878        {
879            panic!("already subscribed to entity");
880        }
881
882        message_handlers.entities_by_type_and_remote_id.insert(
883            id,
884            EntityMessageSubscriber::Entity {
885                handle: entity.downgrade().into(),
886            },
887        );
888    }
889
890    pub fn request<T: RequestMessage>(
891        &self,
892        payload: T,
893    ) -> impl 'static + Future<Output = Result<T::Response>> {
894        log::debug!("ssh request start. name:{}", T::NAME);
895        let response = self.request_dynamic(payload.into_envelope(0, None, None), T::NAME);
896        async move {
897            let response = response.await?;
898            log::debug!("ssh request finish. name:{}", T::NAME);
899            T::Response::from_envelope(response)
900                .ok_or_else(|| anyhow!("received a response of the wrong type"))
901        }
902    }
903
904    pub fn send<T: EnvelopedMessage>(&self, payload: T) -> Result<()> {
905        log::debug!("ssh send name:{}", T::NAME);
906        self.send_dynamic(payload.into_envelope(0, None, None))
907    }
908
909    pub fn request_dynamic(
910        &self,
911        mut envelope: proto::Envelope,
912        type_name: &'static str,
913    ) -> impl 'static + Future<Output = Result<proto::Envelope>> {
914        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
915        let (tx, rx) = oneshot::channel();
916        let mut response_channels_lock = self.response_channels.lock();
917        response_channels_lock.insert(MessageId(envelope.id), tx);
918        drop(response_channels_lock);
919        let result = self.outgoing_tx.unbounded_send(envelope);
920        async move {
921            if let Err(error) = &result {
922                log::error!("failed to send message: {}", error);
923                return Err(anyhow!("failed to send message: {}", error));
924            }
925
926            let response = rx.await.context("connection lost")?.0;
927            if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
928                return Err(RpcError::from_proto(error, type_name));
929            }
930            Ok(response)
931        }
932    }
933
934    pub fn send_dynamic(&self, mut envelope: proto::Envelope) -> Result<()> {
935        envelope.id = self.next_message_id.fetch_add(1, SeqCst);
936        self.outgoing_tx.unbounded_send(envelope)?;
937        Ok(())
938    }
939}
940
941impl ProtoClient for ChannelClient {
942    fn request(
943        &self,
944        envelope: proto::Envelope,
945        request_type: &'static str,
946    ) -> BoxFuture<'static, Result<proto::Envelope>> {
947        self.request_dynamic(envelope, request_type).boxed()
948    }
949
950    fn send(&self, envelope: proto::Envelope, _message_type: &'static str) -> Result<()> {
951        self.send_dynamic(envelope)
952    }
953
954    fn send_response(&self, envelope: Envelope, _message_type: &'static str) -> anyhow::Result<()> {
955        self.send_dynamic(envelope)
956    }
957
958    fn message_handler_set(&self) -> &Mutex<ProtoMessageHandlerSet> {
959        &self.message_handlers
960    }
961
962    fn is_via_collab(&self) -> bool {
963        false
964    }
965}