1use crate::{
2 json_log::LogRecord,
3 protocol::{MESSAGE_LEN_SIZE, message_len_from_buffer, read_message_with_len, write_message},
4};
5use anyhow::{Context as _, Result};
6use futures::{
7 AsyncReadExt as _, FutureExt as _, StreamExt as _,
8 channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender},
9};
10use gpui::{AppContext as _, AsyncApp, Task};
11use rpc::proto::Envelope;
12use smol::process::Child;
13
14pub mod ssh;
15pub mod wsl;
16
17fn handle_rpc_messages_over_child_process_stdio(
18 mut ssh_proxy_process: Child,
19 incoming_tx: UnboundedSender<Envelope>,
20 mut outgoing_rx: UnboundedReceiver<Envelope>,
21 mut connection_activity_tx: Sender<()>,
22 cx: &AsyncApp,
23) -> Task<Result<i32>> {
24 let mut child_stderr = ssh_proxy_process.stderr.take().unwrap();
25 let mut child_stdout = ssh_proxy_process.stdout.take().unwrap();
26 let mut child_stdin = ssh_proxy_process.stdin.take().unwrap();
27
28 let mut stdin_buffer = Vec::new();
29 let mut stdout_buffer = Vec::new();
30 let mut stderr_buffer = Vec::new();
31 let mut stderr_offset = 0;
32
33 let stdin_task = cx.background_spawn(async move {
34 while let Some(outgoing) = outgoing_rx.next().await {
35 write_message(&mut child_stdin, &mut stdin_buffer, outgoing).await?;
36 }
37 anyhow::Ok(())
38 });
39
40 let stdout_task = cx.background_spawn({
41 let mut connection_activity_tx = connection_activity_tx.clone();
42 async move {
43 loop {
44 stdout_buffer.resize(MESSAGE_LEN_SIZE, 0);
45 let len = child_stdout.read(&mut stdout_buffer).await?;
46
47 if len == 0 {
48 return anyhow::Ok(());
49 }
50
51 if len < MESSAGE_LEN_SIZE {
52 child_stdout.read_exact(&mut stdout_buffer[len..]).await?;
53 }
54
55 let message_len = message_len_from_buffer(&stdout_buffer);
56 let envelope =
57 read_message_with_len(&mut child_stdout, &mut stdout_buffer, message_len)
58 .await?;
59 connection_activity_tx.try_send(()).ok();
60 incoming_tx.unbounded_send(envelope).ok();
61 }
62 }
63 });
64
65 let stderr_task: Task<anyhow::Result<()>> = cx.background_spawn(async move {
66 loop {
67 stderr_buffer.resize(stderr_offset + 1024, 0);
68
69 let len = child_stderr
70 .read(&mut stderr_buffer[stderr_offset..])
71 .await?;
72 if len == 0 {
73 return anyhow::Ok(());
74 }
75
76 stderr_offset += len;
77 let mut start_ix = 0;
78 while let Some(ix) = stderr_buffer[start_ix..stderr_offset]
79 .iter()
80 .position(|b| b == &b'\n')
81 {
82 let line_ix = start_ix + ix;
83 let content = &stderr_buffer[start_ix..line_ix];
84 start_ix = line_ix + 1;
85 if let Ok(record) = serde_json::from_slice::<LogRecord>(content) {
86 record.log(log::logger())
87 } else {
88 eprintln!("(remote) {}", String::from_utf8_lossy(content));
89 }
90 }
91 stderr_buffer.drain(0..start_ix);
92 stderr_offset -= start_ix;
93
94 connection_activity_tx.try_send(()).ok();
95 }
96 });
97
98 cx.background_spawn(async move {
99 let result = futures::select! {
100 result = stdin_task.fuse() => {
101 result.context("stdin")
102 }
103 result = stdout_task.fuse() => {
104 result.context("stdout")
105 }
106 result = stderr_task.fuse() => {
107 result.context("stderr")
108 }
109 };
110 let status = ssh_proxy_process.status().await?.code().unwrap_or(1);
111 match result {
112 Ok(_) => Ok(status),
113 Err(error) => Err(error),
114 }
115 })
116}
117
118#[cfg(debug_assertions)]
119async fn build_remote_server_from_source(
120 platform: &crate::RemotePlatform,
121 delegate: &dyn crate::RemoteClientDelegate,
122 cx: &mut AsyncApp,
123) -> Result<Option<std::path::PathBuf>> {
124 use std::path::Path;
125
126 let Some(build_remote_server) = std::env::var("ZED_BUILD_REMOTE_SERVER").ok() else {
127 return Ok(None);
128 };
129
130 use smol::process::{Command, Stdio};
131 use std::env::VarError;
132
133 async fn run_cmd(command: &mut Command) -> Result<()> {
134 let output = command
135 .kill_on_drop(true)
136 .stderr(Stdio::inherit())
137 .output()
138 .await?;
139 anyhow::ensure!(
140 output.status.success(),
141 "Failed to run command: {command:?}"
142 );
143 Ok(())
144 }
145
146 let use_musl = !build_remote_server.contains("nomusl");
147 let triple = format!(
148 "{}-{}",
149 platform.arch,
150 match platform.os {
151 "linux" =>
152 if use_musl {
153 "unknown-linux-musl"
154 } else {
155 "unknown-linux-gnu"
156 },
157 "macos" => "apple-darwin",
158 _ => anyhow::bail!("can't cross compile for: {:?}", platform),
159 }
160 );
161 let mut rust_flags = match std::env::var("RUSTFLAGS") {
162 Ok(val) => val,
163 Err(VarError::NotPresent) => String::new(),
164 Err(e) => {
165 log::error!("Failed to get env var `RUSTFLAGS` value: {e}");
166 String::new()
167 }
168 };
169 if platform.os == "linux" && use_musl {
170 rust_flags.push_str(" -C target-feature=+crt-static");
171 }
172 if build_remote_server.contains("mold") {
173 rust_flags.push_str(" -C link-arg=-fuse-ld=mold");
174 }
175
176 if platform.arch == std::env::consts::ARCH && platform.os == std::env::consts::OS {
177 delegate.set_status(Some("Building remote server binary from source"), cx);
178 log::info!("building remote server binary from source");
179 run_cmd(
180 Command::new("cargo")
181 .args([
182 "build",
183 "--package",
184 "remote_server",
185 "--features",
186 "debug-embed",
187 "--target-dir",
188 "target/remote_server",
189 "--target",
190 &triple,
191 ])
192 .env("RUSTFLAGS", &rust_flags),
193 )
194 .await?;
195 } else if build_remote_server.contains("cross") {
196 use util::paths::SanitizedPath;
197
198 delegate.set_status(Some("Installing cross.rs for cross-compilation"), cx);
199 log::info!("installing cross");
200 run_cmd(Command::new("cargo").args([
201 "install",
202 "cross",
203 "--git",
204 "https://github.com/cross-rs/cross",
205 ]))
206 .await?;
207
208 delegate.set_status(
209 Some(&format!(
210 "Building remote server binary from source for {} with Docker",
211 &triple
212 )),
213 cx,
214 );
215 log::info!("building remote server binary from source for {}", &triple);
216
217 let src = SanitizedPath::new(&smol::fs::canonicalize("target").await?).to_string();
218
219 run_cmd(
220 Command::new("cross")
221 .args([
222 "build",
223 "--package",
224 "remote_server",
225 "--features",
226 "debug-embed",
227 "--target-dir",
228 "target/remote_server",
229 "--target",
230 &triple,
231 ])
232 .env(
233 "CROSS_CONTAINER_OPTS",
234 format!("--mount type=bind,src={src},dst=/app/target"),
235 )
236 .env("RUSTFLAGS", &rust_flags),
237 )
238 .await?;
239 } else {
240 let which = cx
241 .background_spawn(async move { which::which("zig") })
242 .await;
243
244 if which.is_err() {
245 #[cfg(not(target_os = "windows"))]
246 {
247 anyhow::bail!(
248 "zig not found on $PATH, install zig (see https://ziglang.org/learn/getting-started or use zigup) or pass ZED_BUILD_REMOTE_SERVER=cross to use cross"
249 )
250 }
251 #[cfg(target_os = "windows")]
252 {
253 anyhow::bail!(
254 "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) or pass ZED_BUILD_REMOTE_SERVER=cross to use cross"
255 )
256 }
257 }
258
259 delegate.set_status(Some("Adding rustup target for cross-compilation"), cx);
260 log::info!("adding rustup target");
261 run_cmd(Command::new("rustup").args(["target", "add"]).arg(&triple)).await?;
262
263 delegate.set_status(Some("Installing cargo-zigbuild for cross-compilation"), cx);
264 log::info!("installing cargo-zigbuild");
265 run_cmd(Command::new("cargo").args(["install", "--locked", "cargo-zigbuild"])).await?;
266
267 delegate.set_status(
268 Some(&format!(
269 "Building remote binary from source for {triple} with Zig"
270 )),
271 cx,
272 );
273 log::info!("building remote binary from source for {triple} with Zig");
274 run_cmd(
275 Command::new("cargo")
276 .args([
277 "zigbuild",
278 "--package",
279 "remote_server",
280 "--features",
281 "debug-embed",
282 "--target-dir",
283 "target/remote_server",
284 "--target",
285 &triple,
286 ])
287 .env("RUSTFLAGS", &rust_flags),
288 )
289 .await?;
290 };
291 let bin_path = Path::new("target")
292 .join("remote_server")
293 .join(&triple)
294 .join("debug")
295 .join("remote_server");
296
297 let path = if !build_remote_server.contains("nocompress") {
298 delegate.set_status(Some("Compressing binary"), cx);
299
300 #[cfg(not(target_os = "windows"))]
301 {
302 run_cmd(Command::new("gzip").args(["-f", &bin_path.to_string_lossy()])).await?;
303 }
304
305 #[cfg(target_os = "windows")]
306 {
307 // On Windows, we use 7z to compress the binary
308 let seven_zip = which::which("7z.exe").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\"")?;
309 let gz_path = format!("target/remote_server/{}/debug/remote_server.gz", triple);
310 if smol::fs::metadata(&gz_path).await.is_ok() {
311 smol::fs::remove_file(&gz_path).await?;
312 }
313 run_cmd(Command::new(seven_zip).args([
314 "a",
315 "-tgzip",
316 &gz_path,
317 &bin_path.to_string_lossy(),
318 ]))
319 .await?;
320 }
321
322 let mut archive_path = bin_path;
323 archive_path.set_extension("gz");
324 std::env::current_dir()?.join(archive_path)
325 } else {
326 bin_path
327 };
328
329 Ok(Some(path))
330}