wsl.rs

  1use crate::{
  2    RemoteClientDelegate, 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 { os: "", arch: "" },
 74            shell: String::new(),
 75            shell_kind: ShellKind::Posix,
 76            default_system_shell: String::from("/bin/sh"),
 77            has_wsl_interop: false,
 78        };
 79        delegate.set_status(Some("Detecting WSL environment"), cx);
 80        this.shell = this
 81            .detect_shell()
 82            .await
 83            .context("failed detecting shell")?;
 84        log::info!("Remote shell discovered: {}", this.shell);
 85        this.shell_kind = ShellKind::new(&this.shell, false);
 86        this.has_wsl_interop = this.detect_has_wsl_interop().await.unwrap_or_default();
 87        log::info!(
 88            "Remote has wsl interop {}",
 89            if this.has_wsl_interop {
 90                "enabled"
 91            } else {
 92                "disabled"
 93            }
 94        );
 95        this.platform = this
 96            .detect_platform()
 97            .await
 98            .context("failed detecting platform")?;
 99        log::info!("Remote platform discovered: {:?}", this.platform);
100        this.remote_binary_path = Some(
101            this.ensure_server_binary(&delegate, release_channel, version, cx)
102                .await
103                .context("failed ensuring server binary")?,
104        );
105        log::debug!("Detected WSL environment: {this:#?}");
106
107        Ok(this)
108    }
109
110    async fn detect_platform(&self) -> Result<RemotePlatform> {
111        let program = self.shell_kind.prepend_command_prefix("uname");
112        let output = self.run_wsl_command_with_output(&program, &["-sm"]).await?;
113        parse_platform(&output)
114    }
115
116    async fn detect_shell(&self) -> Result<String> {
117        const DEFAULT_SHELL: &str = "sh";
118        match self
119            .run_wsl_command_with_output("sh", &["-c", "echo $SHELL"])
120            .await
121        {
122            Ok(output) => Ok(parse_shell(&output, DEFAULT_SHELL)),
123            Err(e) => {
124                log::error!("Failed to detect remote shell: {e}");
125                Ok(DEFAULT_SHELL.to_owned())
126            }
127        }
128    }
129
130    async fn detect_has_wsl_interop(&self) -> Result<bool> {
131        Ok(self
132            .run_wsl_command_with_output("cat", &["/proc/sys/fs/binfmt_misc/WSLInterop"])
133            .await
134            .inspect_err(|err| log::error!("Failed to detect wsl interop: {err}"))?
135            .contains("enabled"))
136    }
137
138    async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
139        windows_path_to_wsl_path_impl(&self.connection_options, source).await
140    }
141
142    async fn run_wsl_command_with_output(&self, program: &str, args: &[&str]) -> Result<String> {
143        run_wsl_command_with_output_impl(&self.connection_options, program, args).await
144    }
145
146    async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<()> {
147        run_wsl_command_impl(&self.connection_options, program, args, false)
148            .await
149            .map(|_| ())
150    }
151
152    async fn ensure_server_binary(
153        &self,
154        delegate: &Arc<dyn RemoteClientDelegate>,
155        release_channel: ReleaseChannel,
156        version: Version,
157        cx: &mut AsyncApp,
158    ) -> Result<Arc<RelPath>> {
159        let version_str = match release_channel {
160            ReleaseChannel::Dev => "build".to_string(),
161            _ => version.to_string(),
162        };
163
164        let binary_name = format!(
165            "zed-remote-server-{}-{}",
166            release_channel.dev_name(),
167            version_str
168        );
169
170        let dst_path =
171            paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
172
173        if let Some(parent) = dst_path.parent() {
174            let parent = parent.display(PathStyle::Posix);
175            let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
176            self.run_wsl_command(&mkdir, &["-p", &parent])
177                .await
178                .map_err(|e| anyhow!("Failed to create directory: {}", e))?;
179        }
180
181        #[cfg(debug_assertions)]
182        if let Some(remote_server_path) =
183            super::build_remote_server_from_source(&self.platform, delegate.as_ref(), cx).await?
184        {
185            let tmp_path = paths::remote_wsl_server_dir_relative().join(
186                &RelPath::unix(&format!(
187                    "download-{}-{}",
188                    std::process::id(),
189                    remote_server_path.file_name().unwrap().to_string_lossy()
190                ))
191                .unwrap(),
192            );
193            self.upload_file(&remote_server_path, &tmp_path, delegate, cx)
194                .await?;
195            self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
196                .await?;
197            return Ok(dst_path);
198        }
199
200        if self
201            .run_wsl_command(&dst_path.display(PathStyle::Posix), &["version"])
202            .await
203            .is_ok()
204        {
205            return Ok(dst_path);
206        }
207
208        let wanted_version = match release_channel {
209            ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
210            _ => Some(cx.update(|cx| AppVersion::global(cx))?),
211        };
212
213        let src_path = delegate
214            .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
215            .await?;
216
217        let tmp_path = format!(
218            "{}.{}.gz",
219            dst_path.display(PathStyle::Posix),
220            std::process::id()
221        );
222        let tmp_path = RelPath::unix(&tmp_path).unwrap();
223
224        self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
225        self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
226            .await?;
227
228        Ok(dst_path)
229    }
230
231    async fn upload_file(
232        &self,
233        src_path: &Path,
234        dst_path: &RelPath,
235        delegate: &Arc<dyn RemoteClientDelegate>,
236        cx: &mut AsyncApp,
237    ) -> Result<()> {
238        delegate.set_status(Some("Uploading remote server"), cx);
239
240        if let Some(parent) = dst_path.parent() {
241            let parent = parent.display(PathStyle::Posix);
242            let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
243            self.run_wsl_command(&mkdir, &["-p", &parent])
244                .await
245                .context("Failed to create directory when uploading file")?;
246        }
247
248        let t0 = Instant::now();
249        let src_stat = fs::metadata(&src_path)
250            .await
251            .with_context(|| format!("source path does not exist: {}", src_path.display()))?;
252        let size = src_stat.len();
253        log::info!(
254            "uploading remote server to WSL {:?} ({}kb)",
255            dst_path,
256            size / 1024
257        );
258
259        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
260        let cp = self.shell_kind.prepend_command_prefix("cp");
261        self.run_wsl_command(
262            &cp,
263            &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
264        )
265        .await
266        .map_err(|e| {
267            anyhow!(
268                "Failed to copy file {}({}) to WSL {:?}: {}",
269                src_path.display(),
270                src_path_in_wsl,
271                dst_path,
272                e
273            )
274        })?;
275
276        log::info!("uploaded remote server in {:?}", t0.elapsed());
277        Ok(())
278    }
279
280    async fn extract_and_install(
281        &self,
282        tmp_path: &RelPath,
283        dst_path: &RelPath,
284        delegate: &Arc<dyn RemoteClientDelegate>,
285        cx: &mut AsyncApp,
286    ) -> Result<()> {
287        delegate.set_status(Some("Extracting remote server"), cx);
288
289        let tmp_path_str = tmp_path.display(PathStyle::Posix);
290        let dst_path_str = dst_path.display(PathStyle::Posix);
291
292        // Build extraction script with proper error handling
293        let script = if tmp_path_str.ends_with(".gz") {
294            let uncompressed = tmp_path_str.trim_end_matches(".gz");
295            format!(
296                "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
297                tmp_path_str, uncompressed, uncompressed, dst_path_str
298            )
299        } else {
300            format!(
301                "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
302                tmp_path_str, tmp_path_str, dst_path_str
303            )
304        };
305
306        self.run_wsl_command("sh", &["-c", &script])
307            .await
308            .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
309        Ok(())
310    }
311}
312
313#[async_trait(?Send)]
314impl RemoteConnection for WslRemoteConnection {
315    fn start_proxy(
316        &self,
317        unique_identifier: String,
318        reconnect: bool,
319        incoming_tx: UnboundedSender<Envelope>,
320        outgoing_rx: UnboundedReceiver<Envelope>,
321        connection_activity_tx: Sender<()>,
322        delegate: Arc<dyn RemoteClientDelegate>,
323        cx: &mut AsyncApp,
324    ) -> Task<Result<i32>> {
325        delegate.set_status(Some("Starting proxy"), cx);
326
327        let Some(remote_binary_path) = &self.remote_binary_path else {
328            return Task::ready(Err(anyhow!("Remote binary path not set")));
329        };
330
331        let mut proxy_args = vec![];
332        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
333            if let Some(value) = std::env::var(env_var).ok() {
334                // We don't quote the value here as it seems excessive and may result in invalid envs for the
335                // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
336                // in the proxy server. Therefore, we pass the env vars as is.
337                proxy_args.push(format!("{}={}", env_var, value));
338            }
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
350        let proxy_process =
351            match wsl_command_impl(&self.connection_options, "env", &proxy_args, false)
352                .kill_on_drop(true)
353                .spawn()
354            {
355                Ok(process) => process,
356                Err(error) => {
357                    return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
358                }
359            };
360
361        super::handle_rpc_messages_over_child_process_stdio(
362            proxy_process,
363            incoming_tx,
364            outgoing_rx,
365            connection_activity_tx,
366            cx,
367        )
368    }
369
370    fn upload_directory(
371        &self,
372        src_path: PathBuf,
373        dest_path: RemotePathBuf,
374        cx: &App,
375    ) -> Task<Result<()>> {
376        cx.background_spawn({
377            let options = self.connection_options.clone();
378            async move {
379                let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path).await?;
380
381                run_wsl_command_impl(
382                    &options,
383                    "cp",
384                    &["-r", &wsl_src, &dest_path.to_string()],
385                    true,
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        let (command, args) =
458            ShellBuilder::new(&Shell::Program(self.shell.clone()), false).build(Some(exec), &[]);
459
460        let mut wsl_args = if let Some(user) = &self.connection_options.user {
461            vec![
462                "--distribution".to_string(),
463                self.connection_options.distro_name.clone(),
464                "--user".to_string(),
465                user.clone(),
466                "--cd".to_string(),
467                working_dir,
468                "--".to_string(),
469                command,
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                command,
479            ]
480        };
481        wsl_args.extend(args);
482
483        Ok(CommandTemplate {
484            program: "wsl.exe".to_string(),
485            args: wsl_args,
486            env: HashMap::default(),
487        })
488    }
489
490    fn build_forward_ports_command(
491        &self,
492        _: Vec<(u16, String, u16)>,
493    ) -> anyhow::Result<CommandTemplate> {
494        Err(anyhow!("WSL shares a network interface with the host"))
495    }
496
497    fn connection_options(&self) -> RemoteConnectionOptions {
498        RemoteConnectionOptions::Wsl(self.connection_options.clone())
499    }
500
501    fn path_style(&self) -> PathStyle {
502        PathStyle::Posix
503    }
504
505    fn shell(&self) -> String {
506        self.shell.clone()
507    }
508
509    fn default_system_shell(&self) -> String {
510        self.default_system_shell.clone()
511    }
512
513    fn has_wsl_interop(&self) -> bool {
514        self.has_wsl_interop
515    }
516}
517
518/// `wslpath` is a executable available in WSL, it's a linux binary.
519/// So it doesn't support Windows style paths.
520async fn sanitize_path(path: &Path) -> Result<String> {
521    let path = smol::fs::canonicalize(path)
522        .await
523        .with_context(|| format!("Failed to canonicalize path {}", path.display()))?;
524    let path_str = path.to_string_lossy();
525
526    let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
527    Ok(sanitized.replace('\\', "/"))
528}
529
530async fn run_wsl_command_with_output_impl(
531    options: &WslConnectionOptions,
532    program: &str,
533    args: &[&str],
534) -> Result<String> {
535    match run_wsl_command_impl(options, program, args, true).await {
536        Ok(res) => Ok(res),
537        Err(exec_err) => match run_wsl_command_impl(options, program, args, false).await {
538            Ok(res) => Ok(res),
539            Err(e) => Err(e.context(exec_err)),
540        },
541    }
542}
543
544async fn windows_path_to_wsl_path_impl(
545    options: &WslConnectionOptions,
546    source: &Path,
547) -> Result<String> {
548    let source = sanitize_path(source).await?;
549    run_wsl_command_with_output_impl(options, "wslpath", &["-u", &source]).await
550}
551
552async fn run_wsl_command_impl(
553    options: &WslConnectionOptions,
554    program: &str,
555    args: &[&str],
556    exec: bool,
557) -> Result<String> {
558    let mut command = wsl_command_impl(options, program, args, exec);
559    let output = command
560        .output()
561        .await
562        .with_context(|| format!("Failed to run command '{:?}'", command))?;
563
564    if !output.status.success() {
565        return Err(anyhow!(
566            "Command '{:?}' failed: {}",
567            command,
568            String::from_utf8_lossy(&output.stderr).trim()
569        ));
570    }
571
572    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
573}
574
575/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
576///
577/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
578fn wsl_command_impl(
579    options: &WslConnectionOptions,
580    program: &str,
581    args: &[impl AsRef<OsStr>],
582    exec: bool,
583) -> process::Command {
584    let mut command = util::command::new_smol_command("wsl.exe");
585
586    if let Some(user) = &options.user {
587        command.arg("--user").arg(user);
588    }
589
590    command
591        .stdin(Stdio::piped())
592        .stdout(Stdio::piped())
593        .stderr(Stdio::piped())
594        .arg("--distribution")
595        .arg(&options.distro_name)
596        .arg("--cd")
597        .arg("~");
598
599    if exec {
600        command.arg("--exec");
601    }
602
603    command.arg(program).args(args);
604
605    log::debug!("wsl {:?}", command);
606    command
607}