1use crate::{
2 RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
3 remote_client::{CommandTemplate, Interactive, RemoteConnection, RemoteConnectionOptions},
4 transport::{parse_platform, parse_shell},
5};
6use anyhow::{Context, Result, anyhow, bail};
7use async_trait::async_trait;
8use collections::HashMap;
9use futures::channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender};
10use gpui::{App, AppContext as _, AsyncApp, Task};
11use release_channel::{AppVersion, ReleaseChannel};
12use rpc::proto::Envelope;
13use semver::Version;
14use smol::{fs, process};
15use std::{
16 ffi::OsStr,
17 fmt::Write as _,
18 path::{Path, PathBuf},
19 process::Stdio,
20 sync::Arc,
21 time::Instant,
22};
23use util::{
24 paths::{PathStyle, RemotePathBuf},
25 rel_path::RelPath,
26 shell::{Shell, ShellKind},
27 shell_builder::ShellBuilder,
28};
29
30#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, schemars::JsonSchema)]
31pub struct WslConnectionOptions {
32 pub distro_name: String,
33 pub user: Option<String>,
34}
35
36impl From<settings::WslConnection> for WslConnectionOptions {
37 fn from(val: settings::WslConnection) -> Self {
38 WslConnectionOptions {
39 distro_name: val.distro_name.into(),
40 user: val.user,
41 }
42 }
43}
44
45#[derive(Debug)]
46pub(crate) struct WslRemoteConnection {
47 remote_binary_path: Option<Arc<RelPath>>,
48 platform: RemotePlatform,
49 shell: String,
50 shell_kind: ShellKind,
51 default_system_shell: String,
52 has_wsl_interop: bool,
53 connection_options: WslConnectionOptions,
54}
55
56impl WslRemoteConnection {
57 pub(crate) async fn new(
58 connection_options: WslConnectionOptions,
59 delegate: Arc<dyn RemoteClientDelegate>,
60 cx: &mut AsyncApp,
61 ) -> Result<Self> {
62 log::info!(
63 "Connecting to WSL distro {} with user {:?}",
64 connection_options.distro_name,
65 connection_options.user
66 );
67 let (release_channel, version) =
68 cx.update(|cx| (ReleaseChannel::global(cx), AppVersion::global(cx)));
69
70 let mut this = Self {
71 connection_options,
72 remote_binary_path: None,
73 platform: RemotePlatform {
74 os: RemoteOs::Linux,
75 arch: RemoteArch::X86_64,
76 },
77 shell: String::new(),
78 shell_kind: ShellKind::Posix,
79 default_system_shell: String::from("/bin/sh"),
80 has_wsl_interop: false,
81 };
82 delegate.set_status(Some("Detecting WSL environment"), cx);
83 this.shell = this
84 .detect_shell()
85 .await
86 .context("failed detecting shell")?;
87 log::info!("Remote shell discovered: {}", this.shell);
88 this.shell_kind = ShellKind::new(&this.shell, false);
89 this.has_wsl_interop = this.detect_has_wsl_interop().await.unwrap_or_default();
90 log::info!(
91 "Remote has wsl interop {}",
92 if this.has_wsl_interop {
93 "enabled"
94 } else {
95 "disabled"
96 }
97 );
98 this.platform = this
99 .detect_platform()
100 .await
101 .context("failed detecting platform")?;
102 log::info!("Remote platform discovered: {:?}", this.platform);
103 this.remote_binary_path = Some(
104 this.ensure_server_binary(&delegate, release_channel, version, cx)
105 .await
106 .context("failed ensuring server binary")?,
107 );
108 log::debug!("Detected WSL environment: {this:#?}");
109
110 Ok(this)
111 }
112
113 async fn detect_platform(&self) -> Result<RemotePlatform> {
114 let program = self.shell_kind.prepend_command_prefix("uname");
115 let output = self.run_wsl_command_with_output(&program, &["-sm"]).await?;
116 parse_platform(&output)
117 }
118
119 async fn detect_shell(&self) -> Result<String> {
120 const DEFAULT_SHELL: &str = "sh";
121 match self
122 .run_wsl_command_with_output("sh", &["-c", "echo $SHELL"])
123 .await
124 {
125 Ok(output) => Ok(parse_shell(&output, DEFAULT_SHELL)),
126 Err(e) => {
127 log::error!("Failed to detect remote shell: {e}");
128 Ok(DEFAULT_SHELL.to_owned())
129 }
130 }
131 }
132
133 async fn detect_has_wsl_interop(&self) -> Result<bool> {
134 Ok(self
135 .run_wsl_command_with_output("cat", &["/proc/sys/fs/binfmt_misc/WSLInterop"])
136 .await
137 .inspect_err(|err| log::error!("Failed to detect wsl interop: {err}"))?
138 .contains("enabled"))
139 }
140
141 async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
142 windows_path_to_wsl_path_impl(&self.connection_options, source).await
143 }
144
145 async fn run_wsl_command_with_output(&self, program: &str, args: &[&str]) -> Result<String> {
146 run_wsl_command_with_output_impl(&self.connection_options, program, args).await
147 }
148
149 async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<()> {
150 run_wsl_command_impl(&self.connection_options, program, args, false)
151 .await
152 .map(|_| ())
153 }
154
155 async fn ensure_server_binary(
156 &self,
157 delegate: &Arc<dyn RemoteClientDelegate>,
158 release_channel: ReleaseChannel,
159 version: Version,
160 cx: &mut AsyncApp,
161 ) -> Result<Arc<RelPath>> {
162 let version_str = match release_channel {
163 ReleaseChannel::Dev => "build".to_string(),
164 _ => version.to_string(),
165 };
166
167 let binary_name = format!(
168 "zed-remote-server-{}-{}",
169 release_channel.dev_name(),
170 version_str
171 );
172
173 let dst_path =
174 paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
175
176 if let Some(parent) = dst_path.parent() {
177 let parent = parent.display(PathStyle::Posix);
178 let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
179 self.run_wsl_command(&mkdir, &["-p", &parent])
180 .await
181 .map_err(|e| anyhow!("Failed to create directory: {}", e))?;
182 }
183
184 #[cfg(any(debug_assertions, feature = "build-remote-server-binary"))]
185 if let Some(remote_server_path) =
186 super::build_remote_server_from_source(&self.platform, delegate.as_ref(), cx).await?
187 {
188 let tmp_path = paths::remote_wsl_server_dir_relative().join(
189 &RelPath::unix(&format!(
190 "download-{}-{}",
191 std::process::id(),
192 remote_server_path.file_name().unwrap().to_string_lossy()
193 ))
194 .unwrap(),
195 );
196 self.upload_file(&remote_server_path, &tmp_path, delegate, cx)
197 .await?;
198 self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
199 .await?;
200 return Ok(dst_path);
201 }
202
203 if self
204 .run_wsl_command(&dst_path.display(PathStyle::Posix), &["version"])
205 .await
206 .is_ok()
207 {
208 return Ok(dst_path);
209 }
210
211 let wanted_version = match release_channel {
212 ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
213 _ => Some(cx.update(|cx| AppVersion::global(cx))),
214 };
215
216 let src_path = delegate
217 .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
218 .await?;
219
220 let tmp_path = format!(
221 "{}.{}.gz",
222 dst_path.display(PathStyle::Posix),
223 std::process::id()
224 );
225 let tmp_path = RelPath::unix(&tmp_path).unwrap();
226
227 self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
228 self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
229 .await?;
230
231 Ok(dst_path)
232 }
233
234 async fn upload_file(
235 &self,
236 src_path: &Path,
237 dst_path: &RelPath,
238 delegate: &Arc<dyn RemoteClientDelegate>,
239 cx: &mut AsyncApp,
240 ) -> Result<()> {
241 delegate.set_status(Some("Uploading remote server"), cx);
242
243 if let Some(parent) = dst_path.parent() {
244 let parent = parent.display(PathStyle::Posix);
245 let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
246 self.run_wsl_command(&mkdir, &["-p", &parent])
247 .await
248 .context("Failed to create directory when uploading file")?;
249 }
250
251 let t0 = Instant::now();
252 let src_stat = fs::metadata(&src_path)
253 .await
254 .with_context(|| format!("source path does not exist: {}", src_path.display()))?;
255 let size = src_stat.len();
256 log::info!(
257 "uploading remote server to WSL {:?} ({}kb)",
258 dst_path,
259 size / 1024
260 );
261
262 let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
263 let cp = self.shell_kind.prepend_command_prefix("cp");
264 self.run_wsl_command(
265 &cp,
266 &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
267 )
268 .await
269 .map_err(|e| {
270 anyhow!(
271 "Failed to copy file {}({}) to WSL {:?}: {}",
272 src_path.display(),
273 src_path_in_wsl,
274 dst_path,
275 e
276 )
277 })?;
278
279 log::info!("uploaded remote server in {:?}", t0.elapsed());
280 Ok(())
281 }
282
283 async fn extract_and_install(
284 &self,
285 tmp_path: &RelPath,
286 dst_path: &RelPath,
287 delegate: &Arc<dyn RemoteClientDelegate>,
288 cx: &mut AsyncApp,
289 ) -> Result<()> {
290 delegate.set_status(Some("Extracting remote server"), cx);
291
292 let tmp_path_str = tmp_path.display(PathStyle::Posix);
293 let dst_path_str = dst_path.display(PathStyle::Posix);
294
295 // Build extraction script with proper error handling
296 let script = if tmp_path_str.ends_with(".gz") {
297 let uncompressed = tmp_path_str.trim_end_matches(".gz");
298 format!(
299 "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
300 tmp_path_str, uncompressed, uncompressed, dst_path_str
301 )
302 } else {
303 format!(
304 "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
305 tmp_path_str, tmp_path_str, dst_path_str
306 )
307 };
308
309 self.run_wsl_command("sh", &["-c", &script])
310 .await
311 .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
312 Ok(())
313 }
314}
315
316#[async_trait(?Send)]
317impl RemoteConnection for WslRemoteConnection {
318 fn start_proxy(
319 &self,
320 unique_identifier: String,
321 reconnect: bool,
322 incoming_tx: UnboundedSender<Envelope>,
323 outgoing_rx: UnboundedReceiver<Envelope>,
324 connection_activity_tx: Sender<()>,
325 delegate: Arc<dyn RemoteClientDelegate>,
326 cx: &mut AsyncApp,
327 ) -> Task<Result<i32>> {
328 delegate.set_status(Some("Starting proxy"), cx);
329
330 let Some(remote_binary_path) = &self.remote_binary_path else {
331 return Task::ready(Err(anyhow!("Remote binary path not set")));
332 };
333
334 let mut proxy_args = vec![];
335 for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
336 if let Some(value) = std::env::var(env_var).ok() {
337 // We don't quote the value here as it seems excessive and may result in invalid envs for the
338 // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
339 // in the proxy server. Therefore, we pass the env vars as is.
340 proxy_args.push(format!("{}={}", env_var, value));
341 }
342 }
343
344 proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
345 proxy_args.push("proxy".to_owned());
346 proxy_args.push("--identifier".to_owned());
347 proxy_args.push(unique_identifier);
348
349 if reconnect {
350 proxy_args.push("--reconnect".to_owned());
351 }
352
353 let proxy_process =
354 match wsl_command_impl(&self.connection_options, "env", &proxy_args, false)
355 .kill_on_drop(true)
356 .spawn()
357 {
358 Ok(process) => process,
359 Err(error) => {
360 return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
361 }
362 };
363
364 super::handle_rpc_messages_over_child_process_stdio(
365 proxy_process,
366 incoming_tx,
367 outgoing_rx,
368 connection_activity_tx,
369 cx,
370 )
371 }
372
373 fn upload_directory(
374 &self,
375 src_path: PathBuf,
376 dest_path: RemotePathBuf,
377 cx: &App,
378 ) -> Task<Result<()>> {
379 cx.background_spawn({
380 let options = self.connection_options.clone();
381 async move {
382 let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path).await?;
383
384 run_wsl_command_impl(
385 &options,
386 "cp",
387 &["-r", &wsl_src, &dest_path.to_string()],
388 true,
389 )
390 .await
391 .map_err(|e| {
392 anyhow!(
393 "failed to upload directory {} -> {}: {}",
394 src_path.display(),
395 dest_path,
396 e
397 )
398 })?;
399
400 Ok(())
401 }
402 })
403 }
404
405 async fn kill(&self) -> Result<()> {
406 Ok(())
407 }
408
409 fn has_been_killed(&self) -> bool {
410 false
411 }
412
413 fn shares_network_interface(&self) -> bool {
414 true
415 }
416
417 fn build_command(
418 &self,
419 program: Option<String>,
420 args: &[String],
421 env: &HashMap<String, String>,
422 working_dir: Option<String>,
423 port_forward: Option<(u16, String, u16)>,
424 _interactive: Interactive,
425 ) -> Result<CommandTemplate> {
426 if port_forward.is_some() {
427 bail!("WSL shares the network interface with the host system");
428 }
429
430 let shell_kind = self.shell_kind;
431 let working_dir = working_dir
432 .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
433 .unwrap_or("~".to_string());
434
435 let mut exec = String::from("exec env ");
436
437 for (k, v) in env.iter() {
438 write!(
439 exec,
440 "{}={} ",
441 k,
442 shell_kind.try_quote(v).context("shell quoting")?
443 )?;
444 }
445
446 if let Some(program) = program {
447 write!(
448 exec,
449 "{}",
450 shell_kind
451 .try_quote_prefix_aware(&program)
452 .context("shell quoting")?
453 )?;
454 for arg in args {
455 let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
456 write!(exec, " {}", &arg)?;
457 }
458 } else {
459 write!(&mut exec, "{} -l", self.shell)?;
460 }
461 let (command, args) =
462 ShellBuilder::new(&Shell::Program(self.shell.clone()), false).build(Some(exec), &[]);
463
464 let mut wsl_args = if let Some(user) = &self.connection_options.user {
465 vec![
466 "--distribution".to_string(),
467 self.connection_options.distro_name.clone(),
468 "--user".to_string(),
469 user.clone(),
470 "--cd".to_string(),
471 working_dir,
472 "--".to_string(),
473 command,
474 ]
475 } else {
476 vec![
477 "--distribution".to_string(),
478 self.connection_options.distro_name.clone(),
479 "--cd".to_string(),
480 working_dir,
481 "--".to_string(),
482 command,
483 ]
484 };
485 wsl_args.extend(args);
486
487 Ok(CommandTemplate {
488 program: "wsl.exe".to_string(),
489 args: wsl_args,
490 env: HashMap::default(),
491 })
492 }
493
494 fn build_forward_ports_command(
495 &self,
496 _: Vec<(u16, String, u16)>,
497 ) -> anyhow::Result<CommandTemplate> {
498 Err(anyhow!("WSL shares a network interface with the host"))
499 }
500
501 fn connection_options(&self) -> RemoteConnectionOptions {
502 RemoteConnectionOptions::Wsl(self.connection_options.clone())
503 }
504
505 fn path_style(&self) -> PathStyle {
506 PathStyle::Posix
507 }
508
509 fn shell(&self) -> String {
510 self.shell.clone()
511 }
512
513 fn default_system_shell(&self) -> String {
514 self.default_system_shell.clone()
515 }
516
517 fn has_wsl_interop(&self) -> bool {
518 self.has_wsl_interop
519 }
520}
521
522/// `wslpath` is a executable available in WSL, it's a linux binary.
523/// So it doesn't support Windows style paths.
524async fn sanitize_path(path: &Path) -> Result<String> {
525 let path = smol::fs::canonicalize(path)
526 .await
527 .with_context(|| format!("Failed to canonicalize path {}", path.display()))?;
528 let path_str = path.to_string_lossy();
529
530 let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
531 Ok(sanitized.replace('\\', "/"))
532}
533
534async fn run_wsl_command_with_output_impl(
535 options: &WslConnectionOptions,
536 program: &str,
537 args: &[&str],
538) -> Result<String> {
539 match run_wsl_command_impl(options, program, args, true).await {
540 Ok(res) => Ok(res),
541 Err(exec_err) => match run_wsl_command_impl(options, program, args, false).await {
542 Ok(res) => Ok(res),
543 Err(e) => Err(e.context(exec_err)),
544 },
545 }
546}
547
548async fn windows_path_to_wsl_path_impl(
549 options: &WslConnectionOptions,
550 source: &Path,
551) -> Result<String> {
552 let source = sanitize_path(source).await?;
553 run_wsl_command_with_output_impl(options, "wslpath", &["-u", &source]).await
554}
555
556async fn run_wsl_command_impl(
557 options: &WslConnectionOptions,
558 program: &str,
559 args: &[&str],
560 exec: bool,
561) -> Result<String> {
562 let mut command = wsl_command_impl(options, program, args, exec);
563 let output = command
564 .output()
565 .await
566 .with_context(|| format!("Failed to run command '{:?}'", command))?;
567
568 if !output.status.success() {
569 return Err(anyhow!(
570 "Command '{:?}' failed: {}",
571 command,
572 String::from_utf8_lossy(&output.stderr).trim()
573 ));
574 }
575
576 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
577}
578
579/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
580///
581/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
582fn wsl_command_impl(
583 options: &WslConnectionOptions,
584 program: &str,
585 args: &[impl AsRef<OsStr>],
586 exec: bool,
587) -> process::Command {
588 let mut command = util::command::new_smol_command("wsl.exe");
589
590 if let Some(user) = &options.user {
591 command.arg("--user").arg(user);
592 }
593
594 command
595 .stdin(Stdio::piped())
596 .stdout(Stdio::piped())
597 .stderr(Stdio::piped())
598 .arg("--distribution")
599 .arg(&options.distro_name)
600 .arg("--cd")
601 .arg("~");
602
603 if exec {
604 command.arg("--exec");
605 }
606
607 command.arg(program).args(args);
608
609 log::debug!("wsl {:?}", command);
610 command
611}