wsl.rs

  1use crate::{
  2    RemoteArch, RemoteClientDelegate, RemoteOs, RemotePlatform,
  3    remote_client::{CommandTemplate, 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(debug_assertions)]
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    ) -> Result<CommandTemplate> {
425        if port_forward.is_some() {
426            bail!("WSL shares the network interface with the host system");
427        }
428
429        let shell_kind = self.shell_kind;
430        let working_dir = working_dir
431            .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
432            .unwrap_or("~".to_string());
433
434        let mut exec = String::from("exec env ");
435
436        for (k, v) in env.iter() {
437            write!(
438                exec,
439                "{}={} ",
440                k,
441                shell_kind.try_quote(v).context("shell quoting")?
442            )?;
443        }
444
445        if let Some(program) = program {
446            write!(
447                exec,
448                "{}",
449                shell_kind
450                    .try_quote_prefix_aware(&program)
451                    .context("shell quoting")?
452            )?;
453            for arg in args {
454                let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
455                write!(exec, " {}", &arg)?;
456            }
457        } else {
458            write!(&mut exec, "{} -l", self.shell)?;
459        }
460        let (command, args) =
461            ShellBuilder::new(&Shell::Program(self.shell.clone()), false).build(Some(exec), &[]);
462
463        let mut wsl_args = if let Some(user) = &self.connection_options.user {
464            vec![
465                "--distribution".to_string(),
466                self.connection_options.distro_name.clone(),
467                "--user".to_string(),
468                user.clone(),
469                "--cd".to_string(),
470                working_dir,
471                "--".to_string(),
472                command,
473            ]
474        } else {
475            vec![
476                "--distribution".to_string(),
477                self.connection_options.distro_name.clone(),
478                "--cd".to_string(),
479                working_dir,
480                "--".to_string(),
481                command,
482            ]
483        };
484        wsl_args.extend(args);
485
486        Ok(CommandTemplate {
487            program: "wsl.exe".to_string(),
488            args: wsl_args,
489            env: HashMap::default(),
490        })
491    }
492
493    fn build_forward_ports_command(
494        &self,
495        _: Vec<(u16, String, u16)>,
496    ) -> anyhow::Result<CommandTemplate> {
497        Err(anyhow!("WSL shares a network interface with the host"))
498    }
499
500    fn connection_options(&self) -> RemoteConnectionOptions {
501        RemoteConnectionOptions::Wsl(self.connection_options.clone())
502    }
503
504    fn path_style(&self) -> PathStyle {
505        PathStyle::Posix
506    }
507
508    fn shell(&self) -> String {
509        self.shell.clone()
510    }
511
512    fn default_system_shell(&self) -> String {
513        self.default_system_shell.clone()
514    }
515
516    fn has_wsl_interop(&self) -> bool {
517        self.has_wsl_interop
518    }
519}
520
521/// `wslpath` is a executable available in WSL, it's a linux binary.
522/// So it doesn't support Windows style paths.
523async fn sanitize_path(path: &Path) -> Result<String> {
524    let path = smol::fs::canonicalize(path)
525        .await
526        .with_context(|| format!("Failed to canonicalize path {}", path.display()))?;
527    let path_str = path.to_string_lossy();
528
529    let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
530    Ok(sanitized.replace('\\', "/"))
531}
532
533async fn run_wsl_command_with_output_impl(
534    options: &WslConnectionOptions,
535    program: &str,
536    args: &[&str],
537) -> Result<String> {
538    match run_wsl_command_impl(options, program, args, true).await {
539        Ok(res) => Ok(res),
540        Err(exec_err) => match run_wsl_command_impl(options, program, args, false).await {
541            Ok(res) => Ok(res),
542            Err(e) => Err(e.context(exec_err)),
543        },
544    }
545}
546
547async fn windows_path_to_wsl_path_impl(
548    options: &WslConnectionOptions,
549    source: &Path,
550) -> Result<String> {
551    let source = sanitize_path(source).await?;
552    run_wsl_command_with_output_impl(options, "wslpath", &["-u", &source]).await
553}
554
555async fn run_wsl_command_impl(
556    options: &WslConnectionOptions,
557    program: &str,
558    args: &[&str],
559    exec: bool,
560) -> Result<String> {
561    let mut command = wsl_command_impl(options, program, args, exec);
562    let output = command
563        .output()
564        .await
565        .with_context(|| format!("Failed to run command '{:?}'", command))?;
566
567    if !output.status.success() {
568        return Err(anyhow!(
569            "Command '{:?}' failed: {}",
570            command,
571            String::from_utf8_lossy(&output.stderr).trim()
572        ));
573    }
574
575    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
576}
577
578/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
579///
580/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
581fn wsl_command_impl(
582    options: &WslConnectionOptions,
583    program: &str,
584    args: &[impl AsRef<OsStr>],
585    exec: bool,
586) -> process::Command {
587    let mut command = util::command::new_smol_command("wsl.exe");
588
589    if let Some(user) = &options.user {
590        command.arg("--user").arg(user);
591    }
592
593    command
594        .stdin(Stdio::piped())
595        .stdout(Stdio::piped())
596        .stderr(Stdio::piped())
597        .arg("--distribution")
598        .arg(&options.distro_name)
599        .arg("--cd")
600        .arg("~");
601
602    if exec {
603        command.arg("--exec");
604    }
605
606    command.arg(program).args(args);
607
608    log::debug!("wsl {:?}", command);
609    command
610}