1use crate::{
2 RemoteArch, RemoteOs, RemotePlatform,
3 json_log::LogRecord,
4 protocol::{MESSAGE_LEN_SIZE, message_len_from_buffer, read_message_with_len, write_message},
5};
6use anyhow::{Context as _, Result};
7use futures::{
8 AsyncReadExt as _, FutureExt as _, StreamExt as _,
9 channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender},
10};
11use gpui::{AppContext as _, AsyncApp, Task};
12use rpc::proto::Envelope;
13use smol::process::Child;
14
15pub mod docker;
16#[cfg(any(test, feature = "test-support"))]
17pub mod mock;
18pub mod ssh;
19pub mod wsl;
20
21/// Parses the output of `uname -sm` to determine the remote platform.
22/// Takes the last line to skip possible shell initialization output.
23fn parse_platform(output: &str) -> Result<RemotePlatform> {
24 let output = output.trim();
25 let uname = output.rsplit_once('\n').map_or(output, |(_, last)| last);
26 let Some((os, arch)) = uname.split_once(" ") else {
27 anyhow::bail!("unknown uname: {uname:?}")
28 };
29
30 let os = match os {
31 "Darwin" => RemoteOs::MacOs,
32 "Linux" => RemoteOs::Linux,
33 _ => anyhow::bail!(
34 "Prebuilt remote servers are not yet available for {os:?}. See https://zed.dev/docs/remote-development"
35 ),
36 };
37
38 // exclude armv5,6,7 as they are 32-bit.
39 let arch = if arch.starts_with("armv8")
40 || arch.starts_with("armv9")
41 || arch.starts_with("arm64")
42 || arch.starts_with("aarch64")
43 {
44 RemoteArch::Aarch64
45 } else if arch.starts_with("x86") {
46 RemoteArch::X86_64
47 } else {
48 anyhow::bail!(
49 "Prebuilt remote servers are not yet available for {arch:?}. See https://zed.dev/docs/remote-development"
50 )
51 };
52
53 Ok(RemotePlatform { os, arch })
54}
55
56/// Parses the output of `echo $SHELL` to determine the remote shell.
57/// Takes the last line to skip possible shell initialization output.
58fn parse_shell(output: &str, fallback_shell: &str) -> String {
59 let output = output.trim();
60 let shell = output.rsplit_once('\n').map_or(output, |(_, last)| last);
61 if shell.is_empty() {
62 log::error!("$SHELL is not set, falling back to {fallback_shell}");
63 fallback_shell.to_owned()
64 } else {
65 shell.to_owned()
66 }
67}
68
69fn handle_rpc_messages_over_child_process_stdio(
70 mut remote_proxy_process: Child,
71 incoming_tx: UnboundedSender<Envelope>,
72 mut outgoing_rx: UnboundedReceiver<Envelope>,
73 mut connection_activity_tx: Sender<()>,
74 cx: &AsyncApp,
75) -> Task<Result<i32>> {
76 let mut child_stderr = remote_proxy_process.stderr.take().unwrap();
77 let mut child_stdout = remote_proxy_process.stdout.take().unwrap();
78 let mut child_stdin = remote_proxy_process.stdin.take().unwrap();
79
80 let mut stdin_buffer = Vec::new();
81 let mut stdout_buffer = Vec::new();
82 let mut stderr_buffer = Vec::new();
83 let mut stderr_offset = 0;
84
85 let stdin_task = cx.background_spawn(async move {
86 while let Some(outgoing) = outgoing_rx.next().await {
87 write_message(&mut child_stdin, &mut stdin_buffer, outgoing).await?;
88 }
89 anyhow::Ok(())
90 });
91
92 let stdout_task = cx.background_spawn({
93 let mut connection_activity_tx = connection_activity_tx.clone();
94 async move {
95 loop {
96 stdout_buffer.resize(MESSAGE_LEN_SIZE, 0);
97 let len = child_stdout.read(&mut stdout_buffer).await?;
98
99 if len == 0 {
100 return anyhow::Ok(());
101 }
102
103 if len < MESSAGE_LEN_SIZE {
104 child_stdout.read_exact(&mut stdout_buffer[len..]).await?;
105 }
106
107 let message_len = message_len_from_buffer(&stdout_buffer);
108 let envelope =
109 read_message_with_len(&mut child_stdout, &mut stdout_buffer, message_len)
110 .await?;
111 connection_activity_tx.try_send(()).ok();
112 incoming_tx.unbounded_send(envelope).ok();
113 }
114 }
115 });
116
117 let stderr_task: Task<anyhow::Result<()>> = cx.background_spawn(async move {
118 loop {
119 stderr_buffer.resize(stderr_offset + 1024, 0);
120
121 let len = child_stderr
122 .read(&mut stderr_buffer[stderr_offset..])
123 .await?;
124 if len == 0 {
125 return anyhow::Ok(());
126 }
127
128 stderr_offset += len;
129 let mut start_ix = 0;
130 while let Some(ix) = stderr_buffer[start_ix..stderr_offset]
131 .iter()
132 .position(|b| b == &b'\n')
133 {
134 let line_ix = start_ix + ix;
135 let content = &stderr_buffer[start_ix..line_ix];
136 start_ix = line_ix + 1;
137 if let Ok(record) = serde_json::from_slice::<LogRecord>(content) {
138 record.log(log::logger())
139 } else {
140 eprintln!("(remote) {}", String::from_utf8_lossy(content));
141 }
142 }
143 stderr_buffer.drain(0..start_ix);
144 stderr_offset -= start_ix;
145
146 connection_activity_tx.try_send(()).ok();
147 }
148 });
149
150 cx.background_spawn(async move {
151 let result = futures::select! {
152 result = stdin_task.fuse() => {
153 result.context("stdin")
154 }
155 result = stdout_task.fuse() => {
156 result.context("stdout")
157 }
158 result = stderr_task.fuse() => {
159 result.context("stderr")
160 }
161 };
162 let status = remote_proxy_process.status().await?.code().unwrap_or(1);
163 if status != 0 {
164 anyhow::bail!("Remote server exited with status {status}");
165 }
166 match result {
167 Ok(_) => Ok(status),
168 Err(error) => Err(error),
169 }
170 })
171}
172
173#[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
174async fn build_remote_server_from_source(
175 platform: &crate::RemotePlatform,
176 delegate: &dyn crate::RemoteClientDelegate,
177 cx: &mut AsyncApp,
178) -> Result<Option<std::path::PathBuf>> {
179 use smol::process::{Command, Stdio};
180 use std::env::VarError;
181 use std::path::Path;
182 use util::command::new_smol_command;
183
184 // By default, we make building remote server from source opt-out and we do not force artifact compression
185 // for quicker builds.
186 let build_remote_server =
187 std::env::var("ZED_BUILD_REMOTE_SERVER").unwrap_or("nocompress".into());
188
189 if let "false" | "no" | "off" | "0" = &*build_remote_server {
190 return Ok(None);
191 }
192
193 async fn run_cmd(command: &mut Command) -> Result<()> {
194 let output = command
195 .kill_on_drop(true)
196 .stderr(Stdio::inherit())
197 .output()
198 .await?;
199 anyhow::ensure!(
200 output.status.success(),
201 "Failed to run command: {command:?}: output: {}",
202 String::from_utf8_lossy(&output.stderr)
203 );
204 Ok(())
205 }
206
207 let use_musl = !build_remote_server.contains("nomusl");
208 let triple = format!(
209 "{}-{}",
210 platform.arch,
211 match platform.os {
212 RemoteOs::Linux =>
213 if use_musl {
214 "unknown-linux-musl"
215 } else {
216 "unknown-linux-gnu"
217 },
218 RemoteOs::MacOs => "apple-darwin",
219 RemoteOs::Windows if cfg!(windows) => "pc-windows-msvc",
220 RemoteOs::Windows => "pc-windows-gnu",
221 }
222 );
223 let mut rust_flags = match std::env::var("RUSTFLAGS") {
224 Ok(val) => val,
225 Err(VarError::NotPresent) => String::new(),
226 Err(e) => {
227 log::error!("Failed to get env var `RUSTFLAGS` value: {e}");
228 String::new()
229 }
230 };
231 if platform.os == RemoteOs::Linux && use_musl {
232 rust_flags.push_str(" -C target-feature=+crt-static");
233
234 if let Ok(path) = std::env::var("ZED_ZSTD_MUSL_LIB") {
235 rust_flags.push_str(&format!(" -C link-arg=-L{path}"));
236 }
237 }
238 if build_remote_server.contains("mold") {
239 rust_flags.push_str(" -C link-arg=-fuse-ld=mold");
240 }
241
242 if platform.arch.as_str() == std::env::consts::ARCH
243 && platform.os.as_str() == std::env::consts::OS
244 {
245 delegate.set_status(Some("Building remote server binary from source"), cx);
246 log::info!("building remote server binary from source");
247 run_cmd(
248 new_smol_command("cargo")
249 .current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
250 .args([
251 "build",
252 "--package",
253 "remote_server",
254 "--features",
255 "debug-embed",
256 "--target-dir",
257 "target/remote_server",
258 "--target",
259 &triple,
260 ])
261 .env("RUSTFLAGS", &rust_flags),
262 )
263 .await?;
264 } else {
265 if which("zig", cx).await?.is_none() {
266 anyhow::bail!(if cfg!(not(windows)) {
267 "zig not found on $PATH, install zig (see https://ziglang.org/learn/getting-started or use zigup)"
268 } else {
269 "zig not found on $PATH, install zig (use `winget install -e --id zig.zig` or see https://ziglang.org/learn/getting-started or use zigup)"
270 });
271 }
272
273 let rustup = which("rustup", cx)
274 .await?
275 .context("rustup not found on $PATH, install rustup (see https://rustup.rs/)")?;
276 delegate.set_status(Some("Adding rustup target for cross-compilation"), cx);
277 log::info!("adding rustup target");
278 run_cmd(
279 new_smol_command(rustup)
280 .args(["target", "add"])
281 .arg(&triple),
282 )
283 .await?;
284
285 if which("cargo-zigbuild", cx).await?.is_none() {
286 delegate.set_status(Some("Installing cargo-zigbuild for cross-compilation"), cx);
287 log::info!("installing cargo-zigbuild");
288 run_cmd(new_smol_command("cargo").args(["install", "--locked", "cargo-zigbuild"]))
289 .await?;
290 }
291
292 delegate.set_status(
293 Some(&format!(
294 "Building remote binary from source for {triple} with Zig"
295 )),
296 cx,
297 );
298 log::info!("building remote binary from source for {triple} with Zig");
299 run_cmd(
300 new_smol_command("cargo")
301 .args([
302 "zigbuild",
303 "--package",
304 "remote_server",
305 "--features",
306 "debug-embed",
307 "--target-dir",
308 "target/remote_server",
309 "--target",
310 &triple,
311 ])
312 .env("RUSTFLAGS", &rust_flags),
313 )
314 .await?;
315 };
316 let bin_path = Path::new("target")
317 .join("remote_server")
318 .join(&triple)
319 .join("debug")
320 .join("remote_server")
321 .with_extension(if platform.os.is_windows() { "exe" } else { "" });
322
323 let path = if !build_remote_server.contains("nocompress") {
324 delegate.set_status(Some("Compressing binary"), cx);
325
326 #[cfg(not(target_os = "windows"))]
327 {
328 run_cmd(new_smol_command("gzip").args(["-f", &bin_path.to_string_lossy()])).await?;
329 }
330
331 #[cfg(target_os = "windows")]
332 {
333 // On Windows, we use 7z to compress the binary
334
335 let seven_zip = which("7z.exe",cx)
336 .await?
337 .context("7z.exe not found on $PATH, install it (e.g. with `winget install -e --id 7zip.7zip`) or, if you don't want this behaviour, set $env:ZED_BUILD_REMOTE_SERVER=\"nocompress\"")?;
338 let gz_path = format!("target/remote_server/{}/debug/remote_server.gz", triple);
339 if smol::fs::metadata(&gz_path).await.is_ok() {
340 smol::fs::remove_file(&gz_path).await?;
341 }
342 run_cmd(new_smol_command(seven_zip).args([
343 "a",
344 "-tgzip",
345 &gz_path,
346 &bin_path.to_string_lossy(),
347 ]))
348 .await?;
349 }
350
351 let mut archive_path = bin_path;
352 archive_path.set_extension("gz");
353 std::env::current_dir()?.join(archive_path)
354 } else {
355 bin_path
356 };
357
358 Ok(Some(path))
359}
360
361#[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
362async fn which(
363 binary_name: impl AsRef<str>,
364 cx: &mut AsyncApp,
365) -> Result<Option<std::path::PathBuf>> {
366 let binary_name = binary_name.as_ref().to_string();
367 let binary_name_cloned = binary_name.clone();
368 let res = cx
369 .background_spawn(async move { which::which(binary_name_cloned) })
370 .await;
371 match res {
372 Ok(path) => Ok(Some(path)),
373 Err(which::Error::CannotFindBinaryPath) => Ok(None),
374 Err(err) => Err(anyhow::anyhow!(
375 "Failed to run 'which' to find the binary '{binary_name}': {err}"
376 )),
377 }
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 #[test]
385 fn test_parse_platform() {
386 let result = parse_platform("Linux x86_64\n").unwrap();
387 assert_eq!(result.os, RemoteOs::Linux);
388 assert_eq!(result.arch, RemoteArch::X86_64);
389
390 let result = parse_platform("Darwin arm64\n").unwrap();
391 assert_eq!(result.os, RemoteOs::MacOs);
392 assert_eq!(result.arch, RemoteArch::Aarch64);
393
394 let result = parse_platform("Linux x86_64").unwrap();
395 assert_eq!(result.os, RemoteOs::Linux);
396 assert_eq!(result.arch, RemoteArch::X86_64);
397
398 let result = parse_platform("some shell init output\nLinux aarch64\n").unwrap();
399 assert_eq!(result.os, RemoteOs::Linux);
400 assert_eq!(result.arch, RemoteArch::Aarch64);
401
402 let result = parse_platform("some shell init output\nLinux aarch64").unwrap();
403 assert_eq!(result.os, RemoteOs::Linux);
404 assert_eq!(result.arch, RemoteArch::Aarch64);
405
406 assert_eq!(
407 parse_platform("Linux armv8l\n").unwrap().arch,
408 RemoteArch::Aarch64
409 );
410 assert_eq!(
411 parse_platform("Linux aarch64\n").unwrap().arch,
412 RemoteArch::Aarch64
413 );
414 assert_eq!(
415 parse_platform("Linux x86_64\n").unwrap().arch,
416 RemoteArch::X86_64
417 );
418
419 let result = parse_platform(
420 r#"Linux x86_64 - What you're referring to as Linux, is in fact, GNU/Linux...\n"#,
421 )
422 .unwrap();
423 assert_eq!(result.os, RemoteOs::Linux);
424 assert_eq!(result.arch, RemoteArch::X86_64);
425
426 assert!(parse_platform("Windows x86_64\n").is_err());
427 assert!(parse_platform("Linux armv7l\n").is_err());
428 }
429
430 #[test]
431 fn test_parse_shell() {
432 assert_eq!(parse_shell("/bin/bash\n", "sh"), "/bin/bash");
433 assert_eq!(parse_shell("/bin/zsh\n", "sh"), "/bin/zsh");
434
435 assert_eq!(parse_shell("/bin/bash", "sh"), "/bin/bash");
436 assert_eq!(
437 parse_shell("some shell init output\n/bin/bash\n", "sh"),
438 "/bin/bash"
439 );
440 assert_eq!(
441 parse_shell("some shell init output\n/bin/bash", "sh"),
442 "/bin/bash"
443 );
444 assert_eq!(parse_shell("", "sh"), "sh");
445 assert_eq!(parse_shell("\n", "sh"), "sh");
446 }
447}