wsl.rs

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