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 if let Ok(path) = std::env::var("ZED_COPY_REMOTE_SERVER") {
185 let path = std::path::PathBuf::from(path);
186 if path.exists() {
187 return Ok(Some(path));
188 } else {
189 log::warn!(
190 "ZED_COPY_REMOTE_SERVER path does not exist, falling back to ZED_BUILD_REMOTE_SERVER: {}",
191 path.display()
192 );
193 }
194 }
195
196 // By default, we make building remote server from source opt-out and we do not force artifact compression
197 // for quicker builds.
198 let build_remote_server =
199 std::env::var("ZED_BUILD_REMOTE_SERVER").unwrap_or("nocompress".into());
200
201 if let "false" | "no" | "off" | "0" = &*build_remote_server {
202 return Ok(None);
203 }
204
205 async fn run_cmd(command: &mut Command) -> Result<()> {
206 let output = command
207 .kill_on_drop(true)
208 .stdout(Stdio::inherit())
209 .output()
210 .await?;
211 anyhow::ensure!(
212 output.status.success(),
213 "Failed to run command: {command:?}: output: {}",
214 String::from_utf8_lossy(&output.stderr)
215 );
216 Ok(())
217 }
218
219 let use_musl = !build_remote_server.contains("nomusl");
220 let triple = format!(
221 "{}-{}",
222 platform.arch,
223 match platform.os {
224 RemoteOs::Linux =>
225 if use_musl {
226 "unknown-linux-musl"
227 } else {
228 "unknown-linux-gnu"
229 },
230 RemoteOs::MacOs => "apple-darwin",
231 RemoteOs::Windows if cfg!(windows) => "pc-windows-msvc",
232 RemoteOs::Windows => "pc-windows-gnu",
233 }
234 );
235 let mut rust_flags = match std::env::var("RUSTFLAGS") {
236 Ok(val) => val,
237 Err(VarError::NotPresent) => String::new(),
238 Err(e) => {
239 log::error!("Failed to get env var `RUSTFLAGS` value: {e}");
240 String::new()
241 }
242 };
243 if platform.os == RemoteOs::Linux && use_musl {
244 rust_flags.push_str(" -C target-feature=+crt-static");
245
246 if let Ok(path) = std::env::var("ZED_ZSTD_MUSL_LIB") {
247 rust_flags.push_str(&format!(" -C link-arg=-L{path}"));
248 }
249 }
250 if build_remote_server.contains("mold") {
251 rust_flags.push_str(" -C link-arg=-fuse-ld=mold");
252 }
253
254 if platform.arch.as_str() == std::env::consts::ARCH
255 && platform.os.as_str() == std::env::consts::OS
256 {
257 delegate.set_status(Some("Building remote server binary from source"), cx);
258 log::info!("building remote server binary from source");
259 run_cmd(
260 new_smol_command("cargo")
261 .current_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
262 .args([
263 "build",
264 "--package",
265 "remote_server",
266 "--features",
267 "debug-embed",
268 "--target-dir",
269 "target/remote_server",
270 "--target",
271 &triple,
272 ])
273 .env("RUSTFLAGS", &rust_flags),
274 )
275 .await?;
276 } else {
277 if which("zig", cx).await?.is_none() {
278 anyhow::bail!(if cfg!(not(windows)) {
279 "zig not found on $PATH, install zig (see https://ziglang.org/learn/getting-started or use zigup)"
280 } else {
281 "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)"
282 });
283 }
284
285 let rustup = which("rustup", cx)
286 .await?
287 .context("rustup not found on $PATH, install rustup (see https://rustup.rs/)")?;
288 delegate.set_status(Some("Adding rustup target for cross-compilation"), cx);
289 log::info!("adding rustup target");
290 run_cmd(
291 new_smol_command(rustup)
292 .args(["target", "add"])
293 .arg(&triple),
294 )
295 .await?;
296
297 if which("cargo-zigbuild", cx).await?.is_none() {
298 delegate.set_status(Some("Installing cargo-zigbuild for cross-compilation"), cx);
299 log::info!("installing cargo-zigbuild");
300 run_cmd(new_smol_command("cargo").args(["install", "--locked", "cargo-zigbuild"]))
301 .await?;
302 }
303
304 delegate.set_status(
305 Some(&format!(
306 "Building remote binary from source for {triple} with Zig"
307 )),
308 cx,
309 );
310 log::info!("building remote binary from source for {triple} with Zig");
311 run_cmd(
312 new_smol_command("cargo")
313 .args([
314 "zigbuild",
315 "--package",
316 "remote_server",
317 "--features",
318 "debug-embed",
319 "--target-dir",
320 "target/remote_server",
321 "--target",
322 &triple,
323 ])
324 .env("RUSTFLAGS", &rust_flags),
325 )
326 .await?;
327 };
328 let bin_path = Path::new("target")
329 .join("remote_server")
330 .join(&triple)
331 .join("debug")
332 .join("remote_server")
333 .with_extension(if platform.os.is_windows() { "exe" } else { "" });
334
335 let path = if !build_remote_server.contains("nocompress") {
336 delegate.set_status(Some("Compressing binary"), cx);
337
338 #[cfg(not(target_os = "windows"))]
339 {
340 run_cmd(new_smol_command("gzip").args(["-f", &bin_path.to_string_lossy()])).await?;
341 }
342
343 #[cfg(target_os = "windows")]
344 {
345 // On Windows, we use 7z to compress the binary
346
347 let seven_zip = which("7z.exe",cx)
348 .await?
349 .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\"")?;
350 let gz_path = format!("target/remote_server/{}/debug/remote_server.gz", triple);
351 if smol::fs::metadata(&gz_path).await.is_ok() {
352 smol::fs::remove_file(&gz_path).await?;
353 }
354 run_cmd(new_smol_command(seven_zip).args([
355 "a",
356 "-tgzip",
357 &gz_path,
358 &bin_path.to_string_lossy(),
359 ]))
360 .await?;
361 }
362
363 let mut archive_path = bin_path;
364 archive_path.set_extension("gz");
365 std::env::current_dir()?.join(archive_path)
366 } else {
367 bin_path
368 };
369
370 Ok(Some(path))
371}
372
373#[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
374async fn which(
375 binary_name: impl AsRef<str>,
376 cx: &mut AsyncApp,
377) -> Result<Option<std::path::PathBuf>> {
378 let binary_name = binary_name.as_ref().to_string();
379 let binary_name_cloned = binary_name.clone();
380 let res = cx
381 .background_spawn(async move { which::which(binary_name_cloned) })
382 .await;
383 match res {
384 Ok(path) => Ok(Some(path)),
385 Err(which::Error::CannotFindBinaryPath) => Ok(None),
386 Err(err) => Err(anyhow::anyhow!(
387 "Failed to run 'which' to find the binary '{binary_name}': {err}"
388 )),
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395
396 #[test]
397 fn test_parse_platform() {
398 let result = parse_platform("Linux x86_64\n").unwrap();
399 assert_eq!(result.os, RemoteOs::Linux);
400 assert_eq!(result.arch, RemoteArch::X86_64);
401
402 let result = parse_platform("Darwin arm64\n").unwrap();
403 assert_eq!(result.os, RemoteOs::MacOs);
404 assert_eq!(result.arch, RemoteArch::Aarch64);
405
406 let result = parse_platform("Linux x86_64").unwrap();
407 assert_eq!(result.os, RemoteOs::Linux);
408 assert_eq!(result.arch, RemoteArch::X86_64);
409
410 let result = parse_platform("some shell init output\nLinux aarch64\n").unwrap();
411 assert_eq!(result.os, RemoteOs::Linux);
412 assert_eq!(result.arch, RemoteArch::Aarch64);
413
414 let result = parse_platform("some shell init output\nLinux aarch64").unwrap();
415 assert_eq!(result.os, RemoteOs::Linux);
416 assert_eq!(result.arch, RemoteArch::Aarch64);
417
418 assert_eq!(
419 parse_platform("Linux armv8l\n").unwrap().arch,
420 RemoteArch::Aarch64
421 );
422 assert_eq!(
423 parse_platform("Linux aarch64\n").unwrap().arch,
424 RemoteArch::Aarch64
425 );
426 assert_eq!(
427 parse_platform("Linux x86_64\n").unwrap().arch,
428 RemoteArch::X86_64
429 );
430
431 let result = parse_platform(
432 r#"Linux x86_64 - What you're referring to as Linux, is in fact, GNU/Linux...\n"#,
433 )
434 .unwrap();
435 assert_eq!(result.os, RemoteOs::Linux);
436 assert_eq!(result.arch, RemoteArch::X86_64);
437
438 assert!(parse_platform("Windows x86_64\n").is_err());
439 assert!(parse_platform("Linux armv7l\n").is_err());
440 }
441
442 #[test]
443 fn test_parse_shell() {
444 assert_eq!(parse_shell("/bin/bash\n", "sh"), "/bin/bash");
445 assert_eq!(parse_shell("/bin/zsh\n", "sh"), "/bin/zsh");
446
447 assert_eq!(parse_shell("/bin/bash", "sh"), "/bin/bash");
448 assert_eq!(
449 parse_shell("some shell init output\n/bin/bash\n", "sh"),
450 "/bin/bash"
451 );
452 assert_eq!(
453 parse_shell("some shell init output\n/bin/bash", "sh"),
454 "/bin/bash"
455 );
456 assert_eq!(parse_shell("", "sh"), "sh");
457 assert_eq!(parse_shell("\n", "sh"), "sh");
458 }
459}