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