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